Gor Nishanov | 97e3b6d | 2016-10-03 22:44:48 +0000 | [diff] [blame] | 1 | //===----- CGCoroutine.cpp - Emit LLVM Code for C++ coroutines ------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This contains code dealing with C++ code generation of coroutines. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
Gor Nishanov | 4c2f68f | 2017-05-24 02:38:26 +0000 | [diff] [blame^] | 14 | #include "CGCleanup.h" |
Gor Nishanov | 97e3b6d | 2016-10-03 22:44:48 +0000 | [diff] [blame] | 15 | #include "CodeGenFunction.h" |
Gor Nishanov | 5eb5858 | 2017-03-26 02:18:05 +0000 | [diff] [blame] | 16 | #include "llvm/ADT/ScopeExit.h" |
Gor Nishanov | 8df64e9 | 2016-10-27 16:28:31 +0000 | [diff] [blame] | 17 | #include "clang/AST/StmtCXX.h" |
Gor Nishanov | 97e3b6d | 2016-10-03 22:44:48 +0000 | [diff] [blame] | 18 | |
| 19 | using namespace clang; |
| 20 | using namespace CodeGen; |
| 21 | |
Gor Nishanov | 5eb5858 | 2017-03-26 02:18:05 +0000 | [diff] [blame] | 22 | using llvm::Value; |
| 23 | using llvm::BasicBlock; |
Gor Nishanov | 97e3b6d | 2016-10-03 22:44:48 +0000 | [diff] [blame] | 24 | |
Gor Nishanov | 5eb5858 | 2017-03-26 02:18:05 +0000 | [diff] [blame] | 25 | namespace { |
| 26 | enum class AwaitKind { Init, Normal, Yield, Final }; |
| 27 | static constexpr llvm::StringLiteral AwaitKindStr[] = {"init", "await", "yield", |
| 28 | "final"}; |
| 29 | } |
Gor Nishanov | 90be121 | 2017-03-06 21:12:54 +0000 | [diff] [blame] | 30 | |
Gor Nishanov | 5eb5858 | 2017-03-26 02:18:05 +0000 | [diff] [blame] | 31 | struct clang::CodeGen::CGCoroData { |
| 32 | // What is the current await expression kind and how many |
| 33 | // await/yield expressions were encountered so far. |
| 34 | // These are used to generate pretty labels for await expressions in LLVM IR. |
| 35 | AwaitKind CurrentAwaitKind = AwaitKind::Init; |
| 36 | unsigned AwaitNum = 0; |
| 37 | unsigned YieldNum = 0; |
| 38 | |
| 39 | // How many co_return statements are in the coroutine. Used to decide whether |
| 40 | // we need to add co_return; equivalent at the end of the user authored body. |
| 41 | unsigned CoreturnCount = 0; |
| 42 | |
| 43 | // A branch to this block is emitted when coroutine needs to suspend. |
| 44 | llvm::BasicBlock *SuspendBB = nullptr; |
| 45 | |
| 46 | // Stores the jump destination just before the coroutine memory is freed. |
| 47 | // This is the destination that every suspend point jumps to for the cleanup |
| 48 | // branch. |
| 49 | CodeGenFunction::JumpDest CleanupJD; |
| 50 | |
| 51 | // Stores the jump destination just before the final suspend. The co_return |
Gor Nishanov | 90be121 | 2017-03-06 21:12:54 +0000 | [diff] [blame] | 52 | // statements jumps to this point after calling return_xxx promise member. |
| 53 | CodeGenFunction::JumpDest FinalJD; |
| 54 | |
Gor Nishanov | 97e3b6d | 2016-10-03 22:44:48 +0000 | [diff] [blame] | 55 | // Stores the llvm.coro.id emitted in the function so that we can supply it |
| 56 | // as the first argument to coro.begin, coro.alloc and coro.free intrinsics. |
| 57 | // Note: llvm.coro.id returns a token that cannot be directly expressed in a |
| 58 | // builtin. |
| 59 | llvm::CallInst *CoroId = nullptr; |
Gor Nishanov | 5eb5858 | 2017-03-26 02:18:05 +0000 | [diff] [blame] | 60 | |
Gor Nishanov | 68fe6ee | 2017-05-23 03:46:59 +0000 | [diff] [blame] | 61 | // Stores the llvm.coro.begin emitted in the function so that we can replace |
| 62 | // all coro.frame intrinsics with direct SSA value of coro.begin that returns |
| 63 | // the address of the coroutine frame of the current coroutine. |
| 64 | llvm::CallInst *CoroBegin = nullptr; |
| 65 | |
Gor Nishanov | 6c4530c | 2017-05-23 04:21:27 +0000 | [diff] [blame] | 66 | // Stores the last emitted coro.free for the deallocate expressions, we use it |
| 67 | // to wrap dealloc code with if(auto mem = coro.free) dealloc(mem). |
| 68 | llvm::CallInst *LastCoroFree = nullptr; |
| 69 | |
Gor Nishanov | 97e3b6d | 2016-10-03 22:44:48 +0000 | [diff] [blame] | 70 | // If coro.id came from the builtin, remember the expression to give better |
| 71 | // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by |
| 72 | // EmitCoroutineBody. |
| 73 | CallExpr const *CoroIdExpr = nullptr; |
| 74 | }; |
Gor Nishanov | 97e3b6d | 2016-10-03 22:44:48 +0000 | [diff] [blame] | 75 | |
Gor Nishanov | 5eb5858 | 2017-03-26 02:18:05 +0000 | [diff] [blame] | 76 | // Defining these here allows to keep CGCoroData private to this file. |
Gor Nishanov | 97e3b6d | 2016-10-03 22:44:48 +0000 | [diff] [blame] | 77 | clang::CodeGen::CodeGenFunction::CGCoroInfo::CGCoroInfo() {} |
| 78 | CodeGenFunction::CGCoroInfo::~CGCoroInfo() {} |
| 79 | |
Gor Nishanov | 8df64e9 | 2016-10-27 16:28:31 +0000 | [diff] [blame] | 80 | static void createCoroData(CodeGenFunction &CGF, |
Gor Nishanov | 97e3b6d | 2016-10-03 22:44:48 +0000 | [diff] [blame] | 81 | CodeGenFunction::CGCoroInfo &CurCoro, |
Gor Nishanov | 8df64e9 | 2016-10-27 16:28:31 +0000 | [diff] [blame] | 82 | llvm::CallInst *CoroId, |
| 83 | CallExpr const *CoroIdExpr = nullptr) { |
Gor Nishanov | 97e3b6d | 2016-10-03 22:44:48 +0000 | [diff] [blame] | 84 | if (CurCoro.Data) { |
| 85 | if (CurCoro.Data->CoroIdExpr) |
| 86 | CGF.CGM.Error(CoroIdExpr->getLocStart(), |
| 87 | "only one __builtin_coro_id can be used in a function"); |
| 88 | else if (CoroIdExpr) |
| 89 | CGF.CGM.Error(CoroIdExpr->getLocStart(), |
| 90 | "__builtin_coro_id shall not be used in a C++ coroutine"); |
| 91 | else |
| 92 | llvm_unreachable("EmitCoroutineBodyStatement called twice?"); |
| 93 | |
Gor Nishanov | 8df64e9 | 2016-10-27 16:28:31 +0000 | [diff] [blame] | 94 | return; |
Gor Nishanov | 97e3b6d | 2016-10-03 22:44:48 +0000 | [diff] [blame] | 95 | } |
| 96 | |
| 97 | CurCoro.Data = std::unique_ptr<CGCoroData>(new CGCoroData); |
| 98 | CurCoro.Data->CoroId = CoroId; |
| 99 | CurCoro.Data->CoroIdExpr = CoroIdExpr; |
Gor Nishanov | 8df64e9 | 2016-10-27 16:28:31 +0000 | [diff] [blame] | 100 | } |
| 101 | |
Gor Nishanov | 5eb5858 | 2017-03-26 02:18:05 +0000 | [diff] [blame] | 102 | // Synthesize a pretty name for a suspend point. |
| 103 | static SmallString<32> buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind) { |
| 104 | unsigned No = 0; |
| 105 | switch (Kind) { |
| 106 | case AwaitKind::Init: |
| 107 | case AwaitKind::Final: |
| 108 | break; |
| 109 | case AwaitKind::Normal: |
| 110 | No = ++Coro.AwaitNum; |
| 111 | break; |
| 112 | case AwaitKind::Yield: |
| 113 | No = ++Coro.YieldNum; |
| 114 | break; |
| 115 | } |
| 116 | SmallString<32> Prefix(AwaitKindStr[static_cast<unsigned>(Kind)]); |
| 117 | if (No > 1) { |
| 118 | Twine(No).toVector(Prefix); |
| 119 | } |
| 120 | return Prefix; |
| 121 | } |
| 122 | |
| 123 | // Emit suspend expression which roughly looks like: |
| 124 | // |
| 125 | // auto && x = CommonExpr(); |
| 126 | // if (!x.await_ready()) { |
| 127 | // llvm_coro_save(); |
| 128 | // x.await_suspend(...); (*) |
| 129 | // llvm_coro_suspend(); (**) |
| 130 | // } |
| 131 | // x.await_resume(); |
| 132 | // |
| 133 | // where the result of the entire expression is the result of x.await_resume() |
| 134 | // |
| 135 | // (*) If x.await_suspend return type is bool, it allows to veto a suspend: |
| 136 | // if (x.await_suspend(...)) |
| 137 | // llvm_coro_suspend(); |
| 138 | // |
| 139 | // (**) llvm_coro_suspend() encodes three possible continuations as |
| 140 | // a switch instruction: |
| 141 | // |
| 142 | // %where-to = call i8 @llvm.coro.suspend(...) |
| 143 | // switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend |
| 144 | // i8 0, label %yield.ready ; go here when resumed |
| 145 | // i8 1, label %yield.cleanup ; go here when destroyed |
| 146 | // ] |
| 147 | // |
| 148 | // See llvm's docs/Coroutines.rst for more details. |
| 149 | // |
| 150 | static RValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro, |
| 151 | CoroutineSuspendExpr const &S, |
| 152 | AwaitKind Kind, AggValueSlot aggSlot, |
| 153 | bool ignoreResult) { |
| 154 | auto *E = S.getCommonExpr(); |
Gor Nishanov | e4f15a2 | 2017-05-23 05:25:31 +0000 | [diff] [blame] | 155 | |
| 156 | // FIXME: rsmith 5/22/2017. Does it still make sense for us to have a |
| 157 | // UO_Coawait at all? As I recall, the only purpose it ever had was to |
| 158 | // represent a dependent co_await expression that couldn't yet be resolved to |
| 159 | // a CoawaitExpr. But now we have (and need!) a separate DependentCoawaitExpr |
| 160 | // node to store unqualified lookup results, it seems that the UnaryOperator |
| 161 | // portion of the representation serves no purpose (and as seen in this patch, |
| 162 | // it's getting in the way). Can we remove it? |
| 163 | |
| 164 | // Skip passthrough operator co_await (present when awaiting on an LValue). |
| 165 | if (auto *UO = dyn_cast<UnaryOperator>(E)) |
| 166 | if (UO->getOpcode() == UO_Coawait) |
| 167 | E = UO->getSubExpr(); |
| 168 | |
Gor Nishanov | 5eb5858 | 2017-03-26 02:18:05 +0000 | [diff] [blame] | 169 | auto Binder = |
| 170 | CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E); |
| 171 | auto UnbindOnExit = llvm::make_scope_exit([&] { Binder.unbind(CGF); }); |
| 172 | |
| 173 | auto Prefix = buildSuspendPrefixStr(Coro, Kind); |
| 174 | BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready")); |
| 175 | BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend")); |
| 176 | BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup")); |
| 177 | |
| 178 | // If expression is ready, no need to suspend. |
| 179 | CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0); |
| 180 | |
| 181 | // Otherwise, emit suspend logic. |
| 182 | CGF.EmitBlock(SuspendBlock); |
| 183 | |
| 184 | auto &Builder = CGF.Builder; |
| 185 | llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save); |
| 186 | auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy); |
| 187 | auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr}); |
| 188 | |
| 189 | auto *SuspendRet = CGF.EmitScalarExpr(S.getSuspendExpr()); |
| 190 | if (SuspendRet != nullptr) { |
| 191 | // Veto suspension if requested by bool returning await_suspend. |
| 192 | assert(SuspendRet->getType()->isIntegerTy(1) && |
| 193 | "Sema should have already checked that it is void or bool"); |
| 194 | BasicBlock *RealSuspendBlock = |
| 195 | CGF.createBasicBlock(Prefix + Twine(".suspend.bool")); |
| 196 | CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock); |
| 197 | SuspendBlock = RealSuspendBlock; |
| 198 | CGF.EmitBlock(RealSuspendBlock); |
| 199 | } |
| 200 | |
| 201 | // Emit the suspend point. |
| 202 | const bool IsFinalSuspend = (Kind == AwaitKind::Final); |
| 203 | llvm::Function *CoroSuspend = |
| 204 | CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend); |
| 205 | auto *SuspendResult = Builder.CreateCall( |
| 206 | CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)}); |
| 207 | |
| 208 | // Create a switch capturing three possible continuations. |
| 209 | auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2); |
| 210 | Switch->addCase(Builder.getInt8(0), ReadyBlock); |
| 211 | Switch->addCase(Builder.getInt8(1), CleanupBlock); |
| 212 | |
| 213 | // Emit cleanup for this suspend point. |
| 214 | CGF.EmitBlock(CleanupBlock); |
| 215 | CGF.EmitBranchThroughCleanup(Coro.CleanupJD); |
| 216 | |
| 217 | // Emit await_resume expression. |
| 218 | CGF.EmitBlock(ReadyBlock); |
| 219 | return CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult); |
| 220 | } |
| 221 | |
| 222 | RValue CodeGenFunction::EmitCoawaitExpr(const CoawaitExpr &E, |
| 223 | AggValueSlot aggSlot, |
| 224 | bool ignoreResult) { |
| 225 | return emitSuspendExpression(*this, *CurCoro.Data, E, |
| 226 | CurCoro.Data->CurrentAwaitKind, aggSlot, |
| 227 | ignoreResult); |
| 228 | } |
| 229 | RValue CodeGenFunction::EmitCoyieldExpr(const CoyieldExpr &E, |
| 230 | AggValueSlot aggSlot, |
| 231 | bool ignoreResult) { |
| 232 | return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield, |
| 233 | aggSlot, ignoreResult); |
| 234 | } |
| 235 | |
Gor Nishanov | 90be121 | 2017-03-06 21:12:54 +0000 | [diff] [blame] | 236 | void CodeGenFunction::EmitCoreturnStmt(CoreturnStmt const &S) { |
| 237 | ++CurCoro.Data->CoreturnCount; |
| 238 | EmitStmt(S.getPromiseCall()); |
| 239 | EmitBranchThroughCleanup(CurCoro.Data->FinalJD); |
| 240 | } |
| 241 | |
Gor Nishanov | 818a776 | 2017-04-05 04:55:03 +0000 | [diff] [blame] | 242 | // For WinEH exception representation backend need to know what funclet coro.end |
| 243 | // belongs to. That information is passed in a funclet bundle. |
| 244 | static SmallVector<llvm::OperandBundleDef, 1> |
| 245 | getBundlesForCoroEnd(CodeGenFunction &CGF) { |
| 246 | SmallVector<llvm::OperandBundleDef, 1> BundleList; |
| 247 | |
| 248 | if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad) |
| 249 | BundleList.emplace_back("funclet", EHPad); |
| 250 | |
| 251 | return BundleList; |
| 252 | } |
| 253 | |
| 254 | namespace { |
| 255 | // We will insert coro.end to cut any of the destructors for objects that |
| 256 | // do not need to be destroyed once the coroutine is resumed. |
| 257 | // See llvm/docs/Coroutines.rst for more details about coro.end. |
| 258 | struct CallCoroEnd final : public EHScopeStack::Cleanup { |
| 259 | void Emit(CodeGenFunction &CGF, Flags flags) override { |
| 260 | auto &CGM = CGF.CGM; |
| 261 | auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy); |
| 262 | llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end); |
| 263 | // See if we have a funclet bundle to associate coro.end with. (WinEH) |
| 264 | auto Bundles = getBundlesForCoroEnd(CGF); |
| 265 | auto *CoroEnd = CGF.Builder.CreateCall( |
| 266 | CoroEndFn, {NullPtr, CGF.Builder.getTrue()}, Bundles); |
| 267 | if (Bundles.empty()) { |
| 268 | // Otherwise, (landingpad model), create a conditional branch that leads |
| 269 | // either to a cleanup block or a block with EH resume instruction. |
| 270 | auto *ResumeBB = CGF.getEHResumeBlock(/*cleanup=*/true); |
| 271 | auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont"); |
| 272 | CGF.Builder.CreateCondBr(CoroEnd, ResumeBB, CleanupContBB); |
| 273 | CGF.EmitBlock(CleanupContBB); |
| 274 | } |
| 275 | } |
| 276 | }; |
| 277 | } |
| 278 | |
Gor Nishanov | 63b6df4 | 2017-04-01 00:22:47 +0000 | [diff] [blame] | 279 | namespace { |
| 280 | // Make sure to call coro.delete on scope exit. |
| 281 | struct CallCoroDelete final : public EHScopeStack::Cleanup { |
| 282 | Stmt *Deallocate; |
| 283 | |
Gor Nishanov | 6c4530c | 2017-05-23 04:21:27 +0000 | [diff] [blame] | 284 | // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;" |
| 285 | |
| 286 | // Note: That deallocation will be emitted twice: once for a normal exit and |
| 287 | // once for exceptional exit. This usage is safe because Deallocate does not |
| 288 | // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr() |
| 289 | // builds a single call to a deallocation function which is safe to emit |
| 290 | // multiple times. |
Gor Nishanov | 63b6df4 | 2017-04-01 00:22:47 +0000 | [diff] [blame] | 291 | void Emit(CodeGenFunction &CGF, Flags) override { |
Gor Nishanov | 6c4530c | 2017-05-23 04:21:27 +0000 | [diff] [blame] | 292 | // Remember the current point, as we are going to emit deallocation code |
| 293 | // first to get to coro.free instruction that is an argument to a delete |
| 294 | // call. |
| 295 | BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock(); |
| 296 | |
| 297 | auto *FreeBB = CGF.createBasicBlock("coro.free"); |
| 298 | CGF.EmitBlock(FreeBB); |
Gor Nishanov | 63b6df4 | 2017-04-01 00:22:47 +0000 | [diff] [blame] | 299 | CGF.EmitStmt(Deallocate); |
Gor Nishanov | 6c4530c | 2017-05-23 04:21:27 +0000 | [diff] [blame] | 300 | |
| 301 | auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free"); |
| 302 | CGF.EmitBlock(AfterFreeBB); |
| 303 | |
| 304 | // We should have captured coro.free from the emission of deallocate. |
| 305 | auto *CoroFree = CGF.CurCoro.Data->LastCoroFree; |
| 306 | if (!CoroFree) { |
| 307 | CGF.CGM.Error(Deallocate->getLocStart(), |
| 308 | "Deallocation expressoin does not refer to coro.free"); |
| 309 | return; |
| 310 | } |
| 311 | |
| 312 | // Get back to the block we were originally and move coro.free there. |
| 313 | auto *InsertPt = SaveInsertBlock->getTerminator(); |
| 314 | CoroFree->moveBefore(InsertPt); |
| 315 | CGF.Builder.SetInsertPoint(InsertPt); |
| 316 | |
| 317 | // Add if (auto *mem = coro.free) Deallocate; |
| 318 | auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy); |
| 319 | auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr); |
| 320 | CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB); |
| 321 | |
| 322 | // No longer need old terminator. |
| 323 | InsertPt->eraseFromParent(); |
| 324 | CGF.Builder.SetInsertPoint(AfterFreeBB); |
Gor Nishanov | 63b6df4 | 2017-04-01 00:22:47 +0000 | [diff] [blame] | 325 | } |
| 326 | explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {} |
| 327 | }; |
| 328 | } |
| 329 | |
Gor Nishanov | 4c2f68f | 2017-05-24 02:38:26 +0000 | [diff] [blame^] | 330 | namespace { |
| 331 | struct GetReturnObjectManager { |
| 332 | CodeGenFunction &CGF; |
| 333 | CGBuilderTy &Builder; |
| 334 | const CoroutineBodyStmt &S; |
| 335 | |
| 336 | Address GroActiveFlag; |
| 337 | CodeGenFunction::AutoVarEmission GroEmission; |
| 338 | |
| 339 | GetReturnObjectManager(CodeGenFunction &CGF, const CoroutineBodyStmt &S) |
| 340 | : CGF(CGF), Builder(CGF.Builder), S(S), GroActiveFlag(Address::invalid()), |
| 341 | GroEmission(CodeGenFunction::AutoVarEmission::invalid()) {} |
| 342 | |
| 343 | // The gro variable has to outlive coroutine frame and coroutine promise, but, |
| 344 | // it can only be initialized after coroutine promise was created, thus, we |
| 345 | // split its emission in two parts. EmitGroAlloca emits an alloca and sets up |
| 346 | // cleanups. Later when coroutine promise is available we initialize the gro |
| 347 | // and sets the flag that the cleanup is now active. |
| 348 | |
| 349 | void EmitGroAlloca() { |
| 350 | auto *GroDeclStmt = dyn_cast<DeclStmt>(S.getResultDecl()); |
| 351 | if (!GroDeclStmt) { |
| 352 | // If get_return_object returns void, no need to do an alloca. |
| 353 | return; |
| 354 | } |
| 355 | |
| 356 | auto *GroVarDecl = cast<VarDecl>(GroDeclStmt->getSingleDecl()); |
| 357 | |
| 358 | // Set GRO flag that it is not initialized yet |
| 359 | GroActiveFlag = |
| 360 | CGF.CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(), "gro.active"); |
| 361 | Builder.CreateStore(Builder.getFalse(), GroActiveFlag); |
| 362 | |
| 363 | GroEmission = CGF.EmitAutoVarAlloca(*GroVarDecl); |
| 364 | |
| 365 | // Remember the top of EHStack before emitting the cleanup. |
| 366 | auto old_top = CGF.EHStack.stable_begin(); |
| 367 | CGF.EmitAutoVarCleanups(GroEmission); |
| 368 | auto top = CGF.EHStack.stable_begin(); |
| 369 | |
| 370 | // Make the cleanup conditional on gro.active |
| 371 | for (auto b = CGF.EHStack.find(top), e = CGF.EHStack.find(old_top); |
| 372 | b != e; b++) { |
| 373 | if (auto *Cleanup = dyn_cast<EHCleanupScope>(&*b)) { |
| 374 | assert(!Cleanup->hasActiveFlag() && "cleanup already has active flag?"); |
| 375 | Cleanup->setActiveFlag(GroActiveFlag); |
| 376 | Cleanup->setTestFlagInEHCleanup(); |
| 377 | Cleanup->setTestFlagInNormalCleanup(); |
| 378 | } |
| 379 | } |
| 380 | } |
| 381 | |
| 382 | void EmitGroInit() { |
| 383 | if (!GroActiveFlag.isValid()) { |
| 384 | // No Gro variable was allocated. Simply emit the call to |
| 385 | // get_return_object. |
| 386 | CGF.EmitStmt(S.getResultDecl()); |
| 387 | return; |
| 388 | } |
| 389 | |
| 390 | CGF.EmitAutoVarInit(GroEmission); |
| 391 | Builder.CreateStore(Builder.getTrue(), GroActiveFlag); |
| 392 | } |
| 393 | }; |
| 394 | } |
| 395 | |
Gor Nishanov | 5b050e4 | 2017-05-22 22:33:17 +0000 | [diff] [blame] | 396 | static void emitBodyAndFallthrough(CodeGenFunction &CGF, |
| 397 | const CoroutineBodyStmt &S, Stmt *Body) { |
| 398 | CGF.EmitStmt(Body); |
| 399 | const bool CanFallthrough = CGF.Builder.GetInsertBlock(); |
| 400 | if (CanFallthrough) |
| 401 | if (Stmt *OnFallthrough = S.getFallthroughHandler()) |
| 402 | CGF.EmitStmt(OnFallthrough); |
| 403 | } |
| 404 | |
Gor Nishanov | 8df64e9 | 2016-10-27 16:28:31 +0000 | [diff] [blame] | 405 | void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt &S) { |
| 406 | auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy()); |
| 407 | auto &TI = CGM.getContext().getTargetInfo(); |
| 408 | unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth(); |
| 409 | |
Gor Nishanov | aa6e9a9 | 2017-05-23 01:13:17 +0000 | [diff] [blame] | 410 | auto *EntryBB = Builder.GetInsertBlock(); |
| 411 | auto *AllocBB = createBasicBlock("coro.alloc"); |
| 412 | auto *InitBB = createBasicBlock("coro.init"); |
Gor Nishanov | 90be121 | 2017-03-06 21:12:54 +0000 | [diff] [blame] | 413 | auto *FinalBB = createBasicBlock("coro.final"); |
Gor Nishanov | 5eb5858 | 2017-03-26 02:18:05 +0000 | [diff] [blame] | 414 | auto *RetBB = createBasicBlock("coro.ret"); |
Gor Nishanov | 90be121 | 2017-03-06 21:12:54 +0000 | [diff] [blame] | 415 | |
Gor Nishanov | 8df64e9 | 2016-10-27 16:28:31 +0000 | [diff] [blame] | 416 | auto *CoroId = Builder.CreateCall( |
| 417 | CGM.getIntrinsic(llvm::Intrinsic::coro_id), |
| 418 | {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr}); |
| 419 | createCoroData(*this, CurCoro, CoroId); |
Gor Nishanov | 5eb5858 | 2017-03-26 02:18:05 +0000 | [diff] [blame] | 420 | CurCoro.Data->SuspendBB = RetBB; |
Gor Nishanov | 8df64e9 | 2016-10-27 16:28:31 +0000 | [diff] [blame] | 421 | |
Gor Nishanov | aa6e9a9 | 2017-05-23 01:13:17 +0000 | [diff] [blame] | 422 | // Backend is allowed to elide memory allocations, to help it, emit |
| 423 | // auto mem = coro.alloc() ? 0 : ... allocation code ...; |
| 424 | auto *CoroAlloc = Builder.CreateCall( |
| 425 | CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId}); |
| 426 | |
| 427 | Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB); |
| 428 | |
| 429 | EmitBlock(AllocBB); |
Gor Nishanov | 3aa9eb3 | 2017-03-27 23:36:59 +0000 | [diff] [blame] | 430 | auto *AllocateCall = EmitScalarExpr(S.getAllocate()); |
Gor Nishanov | aa6e9a9 | 2017-05-23 01:13:17 +0000 | [diff] [blame] | 431 | auto *AllocOrInvokeContBB = Builder.GetInsertBlock(); |
Gor Nishanov | 3aa9eb3 | 2017-03-27 23:36:59 +0000 | [diff] [blame] | 432 | |
| 433 | // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided. |
| 434 | if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) { |
| 435 | auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure"); |
Gor Nishanov | 3aa9eb3 | 2017-03-27 23:36:59 +0000 | [diff] [blame] | 436 | |
| 437 | // See if allocation was successful. |
| 438 | auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy); |
| 439 | auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr); |
| 440 | Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB); |
| 441 | |
| 442 | // If not, return OnAllocFailure object. |
| 443 | EmitBlock(RetOnFailureBB); |
| 444 | EmitStmt(RetOnAllocFailure); |
Gor Nishanov | 3aa9eb3 | 2017-03-27 23:36:59 +0000 | [diff] [blame] | 445 | } |
Gor Nishanov | aa6e9a9 | 2017-05-23 01:13:17 +0000 | [diff] [blame] | 446 | else { |
| 447 | Builder.CreateBr(InitBB); |
| 448 | } |
| 449 | |
| 450 | EmitBlock(InitBB); |
| 451 | |
| 452 | // Pass the result of the allocation to coro.begin. |
| 453 | auto *Phi = Builder.CreatePHI(VoidPtrTy, 2); |
| 454 | Phi->addIncoming(NullPtr, EntryBB); |
| 455 | Phi->addIncoming(AllocateCall, AllocOrInvokeContBB); |
Gor Nishanov | 68fe6ee | 2017-05-23 03:46:59 +0000 | [diff] [blame] | 456 | auto *CoroBegin = Builder.CreateCall( |
Gor Nishanov | aa6e9a9 | 2017-05-23 01:13:17 +0000 | [diff] [blame] | 457 | CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi}); |
Gor Nishanov | 68fe6ee | 2017-05-23 03:46:59 +0000 | [diff] [blame] | 458 | CurCoro.Data->CoroBegin = CoroBegin; |
Gor Nishanov | 90be121 | 2017-03-06 21:12:54 +0000 | [diff] [blame] | 459 | |
Gor Nishanov | 4c2f68f | 2017-05-24 02:38:26 +0000 | [diff] [blame^] | 460 | GetReturnObjectManager GroManager(*this, S); |
| 461 | GroManager.EmitGroAlloca(); |
| 462 | |
Gor Nishanov | 5eb5858 | 2017-03-26 02:18:05 +0000 | [diff] [blame] | 463 | CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB); |
Gor Nishanov | 63b6df4 | 2017-04-01 00:22:47 +0000 | [diff] [blame] | 464 | { |
| 465 | CodeGenFunction::RunCleanupsScope ResumeScope(*this); |
| 466 | EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate()); |
Gor Nishanov | 90be121 | 2017-03-06 21:12:54 +0000 | [diff] [blame] | 467 | |
Gor Nishanov | 63b6df4 | 2017-04-01 00:22:47 +0000 | [diff] [blame] | 468 | EmitStmt(S.getPromiseDeclStmt()); |
Gor Nishanov | 90be121 | 2017-03-06 21:12:54 +0000 | [diff] [blame] | 469 | |
Gor Nishanov | 4c2f68f | 2017-05-24 02:38:26 +0000 | [diff] [blame^] | 470 | // Now we have the promise, initialize the GRO |
| 471 | GroManager.EmitGroInit(); |
Gor Nishanov | 818a776 | 2017-04-05 04:55:03 +0000 | [diff] [blame] | 472 | EHStack.pushCleanup<CallCoroEnd>(EHCleanup); |
| 473 | |
Gor Nishanov | 63b6df4 | 2017-04-01 00:22:47 +0000 | [diff] [blame] | 474 | CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB); |
Gor Nishanov | 90be121 | 2017-03-06 21:12:54 +0000 | [diff] [blame] | 475 | |
Gor Nishanov | 5efc618 | 2017-05-23 05:04:01 +0000 | [diff] [blame] | 476 | // FIXME: Emit param moves. |
| 477 | |
| 478 | CurCoro.Data->CurrentAwaitKind = AwaitKind::Init; |
| 479 | EmitStmt(S.getInitSuspendStmt()); |
Gor Nishanov | 63b6df4 | 2017-04-01 00:22:47 +0000 | [diff] [blame] | 480 | |
| 481 | CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal; |
Gor Nishanov | 5b050e4 | 2017-05-22 22:33:17 +0000 | [diff] [blame] | 482 | |
| 483 | if (auto *OnException = S.getExceptionHandler()) { |
| 484 | auto Loc = S.getLocStart(); |
| 485 | CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr, OnException); |
| 486 | auto *TryStmt = CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch); |
| 487 | |
| 488 | EnterCXXTryStmt(*TryStmt); |
| 489 | emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock()); |
| 490 | ExitCXXTryStmt(*TryStmt); |
| 491 | } |
| 492 | else { |
| 493 | emitBodyAndFallthrough(*this, S, S.getBody()); |
| 494 | } |
Gor Nishanov | 63b6df4 | 2017-04-01 00:22:47 +0000 | [diff] [blame] | 495 | |
| 496 | // See if we need to generate final suspend. |
| 497 | const bool CanFallthrough = Builder.GetInsertBlock(); |
| 498 | const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0; |
| 499 | if (CanFallthrough || HasCoreturns) { |
| 500 | EmitBlock(FinalBB); |
Gor Nishanov | 5efc618 | 2017-05-23 05:04:01 +0000 | [diff] [blame] | 501 | CurCoro.Data->CurrentAwaitKind = AwaitKind::Final; |
| 502 | EmitStmt(S.getFinalSuspendStmt()); |
Gor Nishanov | 63b6df4 | 2017-04-01 00:22:47 +0000 | [diff] [blame] | 503 | } |
Gor Nishanov | db615dd | 2017-05-24 01:54:37 +0000 | [diff] [blame] | 504 | else { |
| 505 | // We don't need FinalBB. Emit it to make sure the block is deleted. |
| 506 | EmitBlock(FinalBB, /*IsFinished=*/true); |
| 507 | } |
Gor Nishanov | 90be121 | 2017-03-06 21:12:54 +0000 | [diff] [blame] | 508 | } |
Gor Nishanov | 90be121 | 2017-03-06 21:12:54 +0000 | [diff] [blame] | 509 | |
Gor Nishanov | 5eb5858 | 2017-03-26 02:18:05 +0000 | [diff] [blame] | 510 | EmitBlock(RetBB); |
Gor Nishanov | 6a47068 | 2017-05-22 20:22:23 +0000 | [diff] [blame] | 511 | // Emit coro.end before getReturnStmt (and parameter destructors), since |
| 512 | // resume and destroy parts of the coroutine should not include them. |
Gor Nishanov | 818a776 | 2017-04-05 04:55:03 +0000 | [diff] [blame] | 513 | llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end); |
| 514 | Builder.CreateCall(CoroEnd, {NullPtr, Builder.getFalse()}); |
Gor Nishanov | 5eb5858 | 2017-03-26 02:18:05 +0000 | [diff] [blame] | 515 | |
Gor Nishanov | 6a47068 | 2017-05-22 20:22:23 +0000 | [diff] [blame] | 516 | if (Stmt *Ret = S.getReturnStmt()) |
| 517 | EmitStmt(Ret); |
Gor Nishanov | 97e3b6d | 2016-10-03 22:44:48 +0000 | [diff] [blame] | 518 | } |
| 519 | |
| 520 | // Emit coroutine intrinsic and patch up arguments of the token type. |
| 521 | RValue CodeGenFunction::EmitCoroutineIntrinsic(const CallExpr *E, |
| 522 | unsigned int IID) { |
| 523 | SmallVector<llvm::Value *, 8> Args; |
| 524 | switch (IID) { |
| 525 | default: |
| 526 | break; |
Gor Nishanov | 68fe6ee | 2017-05-23 03:46:59 +0000 | [diff] [blame] | 527 | // The coro.frame builtin is replaced with an SSA value of the coro.begin |
| 528 | // intrinsic. |
| 529 | case llvm::Intrinsic::coro_frame: { |
| 530 | if (CurCoro.Data && CurCoro.Data->CoroBegin) { |
| 531 | return RValue::get(CurCoro.Data->CoroBegin); |
| 532 | } |
| 533 | CGM.Error(E->getLocStart(), "this builtin expect that __builtin_coro_begin " |
| 534 | "has been used earlier in this function"); |
| 535 | auto NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy()); |
| 536 | return RValue::get(NullPtr); |
| 537 | } |
Gor Nishanov | 97e3b6d | 2016-10-03 22:44:48 +0000 | [diff] [blame] | 538 | // The following three intrinsics take a token parameter referring to a token |
| 539 | // returned by earlier call to @llvm.coro.id. Since we cannot represent it in |
| 540 | // builtins, we patch it up here. |
| 541 | case llvm::Intrinsic::coro_alloc: |
| 542 | case llvm::Intrinsic::coro_begin: |
| 543 | case llvm::Intrinsic::coro_free: { |
| 544 | if (CurCoro.Data && CurCoro.Data->CoroId) { |
| 545 | Args.push_back(CurCoro.Data->CoroId); |
| 546 | break; |
| 547 | } |
| 548 | CGM.Error(E->getLocStart(), "this builtin expect that __builtin_coro_id has" |
| 549 | " been used earlier in this function"); |
| 550 | // Fallthrough to the next case to add TokenNone as the first argument. |
| 551 | } |
| 552 | // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first |
| 553 | // argument. |
| 554 | case llvm::Intrinsic::coro_suspend: |
| 555 | Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext())); |
| 556 | break; |
| 557 | } |
| 558 | for (auto &Arg : E->arguments()) |
| 559 | Args.push_back(EmitScalarExpr(Arg)); |
| 560 | |
| 561 | llvm::Value *F = CGM.getIntrinsic(IID); |
| 562 | llvm::CallInst *Call = Builder.CreateCall(F, Args); |
| 563 | |
Gor Nishanov | 6c4530c | 2017-05-23 04:21:27 +0000 | [diff] [blame] | 564 | // Note: The following code is to enable to emit coro.id and coro.begin by |
Gor Nishanov | 68fe6ee | 2017-05-23 03:46:59 +0000 | [diff] [blame] | 565 | // hand to experiment with coroutines in C. |
Gor Nishanov | 97e3b6d | 2016-10-03 22:44:48 +0000 | [diff] [blame] | 566 | // If we see @llvm.coro.id remember it in the CoroData. We will update |
| 567 | // coro.alloc, coro.begin and coro.free intrinsics to refer to it. |
| 568 | if (IID == llvm::Intrinsic::coro_id) { |
| 569 | createCoroData(*this, CurCoro, Call, E); |
| 570 | } |
Gor Nishanov | 68fe6ee | 2017-05-23 03:46:59 +0000 | [diff] [blame] | 571 | else if (IID == llvm::Intrinsic::coro_begin) { |
| 572 | if (CurCoro.Data) |
| 573 | CurCoro.Data->CoroBegin = Call; |
| 574 | } |
Gor Nishanov | 6c4530c | 2017-05-23 04:21:27 +0000 | [diff] [blame] | 575 | else if (IID == llvm::Intrinsic::coro_free) { |
| 576 | // Remember the last coro_free as we need it to build the conditional |
| 577 | // deletion of the coroutine frame. |
| 578 | if (CurCoro.Data) |
| 579 | CurCoro.Data->LastCoroFree = Call; |
| 580 | } return RValue::get(Call); |
Gor Nishanov | 97e3b6d | 2016-10-03 22:44:48 +0000 | [diff] [blame] | 581 | } |