blob: 1316c76daf9c5a63faa08c44354ecd5f3280d84e [file] [log] [blame]
Gor Nishanov97e3b6d2016-10-03 22:44:48 +00001//===----- 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
14#include "CodeGenFunction.h"
Gor Nishanov5eb58582017-03-26 02:18:05 +000015#include "llvm/ADT/ScopeExit.h"
Gor Nishanov8df64e92016-10-27 16:28:31 +000016#include "clang/AST/StmtCXX.h"
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000017
18using namespace clang;
19using namespace CodeGen;
20
Gor Nishanov5eb58582017-03-26 02:18:05 +000021using llvm::Value;
22using llvm::BasicBlock;
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000023
Gor Nishanov5eb58582017-03-26 02:18:05 +000024namespace {
25enum class AwaitKind { Init, Normal, Yield, Final };
26static constexpr llvm::StringLiteral AwaitKindStr[] = {"init", "await", "yield",
27 "final"};
28}
Gor Nishanov90be1212017-03-06 21:12:54 +000029
Gor Nishanov5eb58582017-03-26 02:18:05 +000030struct clang::CodeGen::CGCoroData {
31 // What is the current await expression kind and how many
32 // await/yield expressions were encountered so far.
33 // These are used to generate pretty labels for await expressions in LLVM IR.
34 AwaitKind CurrentAwaitKind = AwaitKind::Init;
35 unsigned AwaitNum = 0;
36 unsigned YieldNum = 0;
37
38 // How many co_return statements are in the coroutine. Used to decide whether
39 // we need to add co_return; equivalent at the end of the user authored body.
40 unsigned CoreturnCount = 0;
41
42 // A branch to this block is emitted when coroutine needs to suspend.
43 llvm::BasicBlock *SuspendBB = nullptr;
44
45 // Stores the jump destination just before the coroutine memory is freed.
46 // This is the destination that every suspend point jumps to for the cleanup
47 // branch.
48 CodeGenFunction::JumpDest CleanupJD;
49
50 // Stores the jump destination just before the final suspend. The co_return
Gor Nishanov90be1212017-03-06 21:12:54 +000051 // statements jumps to this point after calling return_xxx promise member.
52 CodeGenFunction::JumpDest FinalJD;
53
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000054 // Stores the llvm.coro.id emitted in the function so that we can supply it
55 // as the first argument to coro.begin, coro.alloc and coro.free intrinsics.
56 // Note: llvm.coro.id returns a token that cannot be directly expressed in a
57 // builtin.
58 llvm::CallInst *CoroId = nullptr;
Gor Nishanov5eb58582017-03-26 02:18:05 +000059
Gor Nishanov68fe6ee2017-05-23 03:46:59 +000060 // Stores the llvm.coro.begin emitted in the function so that we can replace
61 // all coro.frame intrinsics with direct SSA value of coro.begin that returns
62 // the address of the coroutine frame of the current coroutine.
63 llvm::CallInst *CoroBegin = nullptr;
64
Gor Nishanov6c4530c2017-05-23 04:21:27 +000065 // Stores the last emitted coro.free for the deallocate expressions, we use it
66 // to wrap dealloc code with if(auto mem = coro.free) dealloc(mem).
67 llvm::CallInst *LastCoroFree = nullptr;
68
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000069 // If coro.id came from the builtin, remember the expression to give better
70 // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by
71 // EmitCoroutineBody.
72 CallExpr const *CoroIdExpr = nullptr;
73};
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000074
Gor Nishanov5eb58582017-03-26 02:18:05 +000075// Defining these here allows to keep CGCoroData private to this file.
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000076clang::CodeGen::CodeGenFunction::CGCoroInfo::CGCoroInfo() {}
77CodeGenFunction::CGCoroInfo::~CGCoroInfo() {}
78
Gor Nishanov8df64e92016-10-27 16:28:31 +000079static void createCoroData(CodeGenFunction &CGF,
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000080 CodeGenFunction::CGCoroInfo &CurCoro,
Gor Nishanov8df64e92016-10-27 16:28:31 +000081 llvm::CallInst *CoroId,
82 CallExpr const *CoroIdExpr = nullptr) {
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000083 if (CurCoro.Data) {
84 if (CurCoro.Data->CoroIdExpr)
85 CGF.CGM.Error(CoroIdExpr->getLocStart(),
86 "only one __builtin_coro_id can be used in a function");
87 else if (CoroIdExpr)
88 CGF.CGM.Error(CoroIdExpr->getLocStart(),
89 "__builtin_coro_id shall not be used in a C++ coroutine");
90 else
91 llvm_unreachable("EmitCoroutineBodyStatement called twice?");
92
Gor Nishanov8df64e92016-10-27 16:28:31 +000093 return;
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000094 }
95
96 CurCoro.Data = std::unique_ptr<CGCoroData>(new CGCoroData);
97 CurCoro.Data->CoroId = CoroId;
98 CurCoro.Data->CoroIdExpr = CoroIdExpr;
Gor Nishanov8df64e92016-10-27 16:28:31 +000099}
100
Gor Nishanov5eb58582017-03-26 02:18:05 +0000101// Synthesize a pretty name for a suspend point.
102static SmallString<32> buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind) {
103 unsigned No = 0;
104 switch (Kind) {
105 case AwaitKind::Init:
106 case AwaitKind::Final:
107 break;
108 case AwaitKind::Normal:
109 No = ++Coro.AwaitNum;
110 break;
111 case AwaitKind::Yield:
112 No = ++Coro.YieldNum;
113 break;
114 }
115 SmallString<32> Prefix(AwaitKindStr[static_cast<unsigned>(Kind)]);
116 if (No > 1) {
117 Twine(No).toVector(Prefix);
118 }
119 return Prefix;
120}
121
122// Emit suspend expression which roughly looks like:
123//
124// auto && x = CommonExpr();
125// if (!x.await_ready()) {
126// llvm_coro_save();
127// x.await_suspend(...); (*)
128// llvm_coro_suspend(); (**)
129// }
130// x.await_resume();
131//
132// where the result of the entire expression is the result of x.await_resume()
133//
134// (*) If x.await_suspend return type is bool, it allows to veto a suspend:
135// if (x.await_suspend(...))
136// llvm_coro_suspend();
137//
138// (**) llvm_coro_suspend() encodes three possible continuations as
139// a switch instruction:
140//
141// %where-to = call i8 @llvm.coro.suspend(...)
142// switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend
143// i8 0, label %yield.ready ; go here when resumed
144// i8 1, label %yield.cleanup ; go here when destroyed
145// ]
146//
147// See llvm's docs/Coroutines.rst for more details.
148//
149static RValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,
150 CoroutineSuspendExpr const &S,
151 AwaitKind Kind, AggValueSlot aggSlot,
152 bool ignoreResult) {
153 auto *E = S.getCommonExpr();
Gor Nishanove4f15a22017-05-23 05:25:31 +0000154
155 // FIXME: rsmith 5/22/2017. Does it still make sense for us to have a
156 // UO_Coawait at all? As I recall, the only purpose it ever had was to
157 // represent a dependent co_await expression that couldn't yet be resolved to
158 // a CoawaitExpr. But now we have (and need!) a separate DependentCoawaitExpr
159 // node to store unqualified lookup results, it seems that the UnaryOperator
160 // portion of the representation serves no purpose (and as seen in this patch,
161 // it's getting in the way). Can we remove it?
162
163 // Skip passthrough operator co_await (present when awaiting on an LValue).
164 if (auto *UO = dyn_cast<UnaryOperator>(E))
165 if (UO->getOpcode() == UO_Coawait)
166 E = UO->getSubExpr();
167
Gor Nishanov5eb58582017-03-26 02:18:05 +0000168 auto Binder =
169 CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E);
170 auto UnbindOnExit = llvm::make_scope_exit([&] { Binder.unbind(CGF); });
171
172 auto Prefix = buildSuspendPrefixStr(Coro, Kind);
173 BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
174 BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
175 BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));
176
177 // If expression is ready, no need to suspend.
178 CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);
179
180 // Otherwise, emit suspend logic.
181 CGF.EmitBlock(SuspendBlock);
182
183 auto &Builder = CGF.Builder;
184 llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
185 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
186 auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
187
188 auto *SuspendRet = CGF.EmitScalarExpr(S.getSuspendExpr());
189 if (SuspendRet != nullptr) {
190 // Veto suspension if requested by bool returning await_suspend.
191 assert(SuspendRet->getType()->isIntegerTy(1) &&
192 "Sema should have already checked that it is void or bool");
193 BasicBlock *RealSuspendBlock =
194 CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
195 CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
196 SuspendBlock = RealSuspendBlock;
197 CGF.EmitBlock(RealSuspendBlock);
198 }
199
200 // Emit the suspend point.
201 const bool IsFinalSuspend = (Kind == AwaitKind::Final);
202 llvm::Function *CoroSuspend =
203 CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);
204 auto *SuspendResult = Builder.CreateCall(
205 CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});
206
207 // Create a switch capturing three possible continuations.
208 auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);
209 Switch->addCase(Builder.getInt8(0), ReadyBlock);
210 Switch->addCase(Builder.getInt8(1), CleanupBlock);
211
212 // Emit cleanup for this suspend point.
213 CGF.EmitBlock(CleanupBlock);
214 CGF.EmitBranchThroughCleanup(Coro.CleanupJD);
215
216 // Emit await_resume expression.
217 CGF.EmitBlock(ReadyBlock);
218 return CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
219}
220
221RValue CodeGenFunction::EmitCoawaitExpr(const CoawaitExpr &E,
222 AggValueSlot aggSlot,
223 bool ignoreResult) {
224 return emitSuspendExpression(*this, *CurCoro.Data, E,
225 CurCoro.Data->CurrentAwaitKind, aggSlot,
226 ignoreResult);
227}
228RValue CodeGenFunction::EmitCoyieldExpr(const CoyieldExpr &E,
229 AggValueSlot aggSlot,
230 bool ignoreResult) {
231 return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,
232 aggSlot, ignoreResult);
233}
234
Gor Nishanov90be1212017-03-06 21:12:54 +0000235void CodeGenFunction::EmitCoreturnStmt(CoreturnStmt const &S) {
236 ++CurCoro.Data->CoreturnCount;
237 EmitStmt(S.getPromiseCall());
238 EmitBranchThroughCleanup(CurCoro.Data->FinalJD);
239}
240
Gor Nishanov818a7762017-04-05 04:55:03 +0000241// For WinEH exception representation backend need to know what funclet coro.end
242// belongs to. That information is passed in a funclet bundle.
243static SmallVector<llvm::OperandBundleDef, 1>
244getBundlesForCoroEnd(CodeGenFunction &CGF) {
245 SmallVector<llvm::OperandBundleDef, 1> BundleList;
246
247 if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
248 BundleList.emplace_back("funclet", EHPad);
249
250 return BundleList;
251}
252
253namespace {
254// We will insert coro.end to cut any of the destructors for objects that
255// do not need to be destroyed once the coroutine is resumed.
256// See llvm/docs/Coroutines.rst for more details about coro.end.
257struct CallCoroEnd final : public EHScopeStack::Cleanup {
258 void Emit(CodeGenFunction &CGF, Flags flags) override {
259 auto &CGM = CGF.CGM;
260 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
261 llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
262 // See if we have a funclet bundle to associate coro.end with. (WinEH)
263 auto Bundles = getBundlesForCoroEnd(CGF);
264 auto *CoroEnd = CGF.Builder.CreateCall(
265 CoroEndFn, {NullPtr, CGF.Builder.getTrue()}, Bundles);
266 if (Bundles.empty()) {
267 // Otherwise, (landingpad model), create a conditional branch that leads
268 // either to a cleanup block or a block with EH resume instruction.
269 auto *ResumeBB = CGF.getEHResumeBlock(/*cleanup=*/true);
270 auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont");
271 CGF.Builder.CreateCondBr(CoroEnd, ResumeBB, CleanupContBB);
272 CGF.EmitBlock(CleanupContBB);
273 }
274 }
275};
276}
277
Gor Nishanov63b6df42017-04-01 00:22:47 +0000278namespace {
279// Make sure to call coro.delete on scope exit.
280struct CallCoroDelete final : public EHScopeStack::Cleanup {
281 Stmt *Deallocate;
282
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000283 // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
284
285 // Note: That deallocation will be emitted twice: once for a normal exit and
286 // once for exceptional exit. This usage is safe because Deallocate does not
287 // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
288 // builds a single call to a deallocation function which is safe to emit
289 // multiple times.
Gor Nishanov63b6df42017-04-01 00:22:47 +0000290 void Emit(CodeGenFunction &CGF, Flags) override {
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000291 // Remember the current point, as we are going to emit deallocation code
292 // first to get to coro.free instruction that is an argument to a delete
293 // call.
294 BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();
295
296 auto *FreeBB = CGF.createBasicBlock("coro.free");
297 CGF.EmitBlock(FreeBB);
Gor Nishanov63b6df42017-04-01 00:22:47 +0000298 CGF.EmitStmt(Deallocate);
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000299
300 auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free");
301 CGF.EmitBlock(AfterFreeBB);
302
303 // We should have captured coro.free from the emission of deallocate.
304 auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;
305 if (!CoroFree) {
306 CGF.CGM.Error(Deallocate->getLocStart(),
307 "Deallocation expressoin does not refer to coro.free");
308 return;
309 }
310
311 // Get back to the block we were originally and move coro.free there.
312 auto *InsertPt = SaveInsertBlock->getTerminator();
313 CoroFree->moveBefore(InsertPt);
314 CGF.Builder.SetInsertPoint(InsertPt);
315
316 // Add if (auto *mem = coro.free) Deallocate;
317 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
318 auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr);
319 CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB);
320
321 // No longer need old terminator.
322 InsertPt->eraseFromParent();
323 CGF.Builder.SetInsertPoint(AfterFreeBB);
Gor Nishanov63b6df42017-04-01 00:22:47 +0000324 }
325 explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}
326};
327}
328
Gor Nishanov5b050e42017-05-22 22:33:17 +0000329static void emitBodyAndFallthrough(CodeGenFunction &CGF,
330 const CoroutineBodyStmt &S, Stmt *Body) {
331 CGF.EmitStmt(Body);
332 const bool CanFallthrough = CGF.Builder.GetInsertBlock();
333 if (CanFallthrough)
334 if (Stmt *OnFallthrough = S.getFallthroughHandler())
335 CGF.EmitStmt(OnFallthrough);
336}
337
Gor Nishanov8df64e92016-10-27 16:28:31 +0000338void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt &S) {
339 auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
340 auto &TI = CGM.getContext().getTargetInfo();
341 unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
342
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000343 auto *EntryBB = Builder.GetInsertBlock();
344 auto *AllocBB = createBasicBlock("coro.alloc");
345 auto *InitBB = createBasicBlock("coro.init");
Gor Nishanov90be1212017-03-06 21:12:54 +0000346 auto *FinalBB = createBasicBlock("coro.final");
Gor Nishanov5eb58582017-03-26 02:18:05 +0000347 auto *RetBB = createBasicBlock("coro.ret");
Gor Nishanov90be1212017-03-06 21:12:54 +0000348
Gor Nishanov8df64e92016-10-27 16:28:31 +0000349 auto *CoroId = Builder.CreateCall(
350 CGM.getIntrinsic(llvm::Intrinsic::coro_id),
351 {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
352 createCoroData(*this, CurCoro, CoroId);
Gor Nishanov5eb58582017-03-26 02:18:05 +0000353 CurCoro.Data->SuspendBB = RetBB;
Gor Nishanov8df64e92016-10-27 16:28:31 +0000354
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000355 // Backend is allowed to elide memory allocations, to help it, emit
356 // auto mem = coro.alloc() ? 0 : ... allocation code ...;
357 auto *CoroAlloc = Builder.CreateCall(
358 CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});
359
360 Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);
361
362 EmitBlock(AllocBB);
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000363 auto *AllocateCall = EmitScalarExpr(S.getAllocate());
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000364 auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000365
366 // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
367 if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
368 auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000369
370 // See if allocation was successful.
371 auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);
372 auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);
373 Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);
374
375 // If not, return OnAllocFailure object.
376 EmitBlock(RetOnFailureBB);
377 EmitStmt(RetOnAllocFailure);
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000378 }
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000379 else {
380 Builder.CreateBr(InitBB);
381 }
382
383 EmitBlock(InitBB);
384
385 // Pass the result of the allocation to coro.begin.
386 auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);
387 Phi->addIncoming(NullPtr, EntryBB);
388 Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000389 auto *CoroBegin = Builder.CreateCall(
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000390 CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000391 CurCoro.Data->CoroBegin = CoroBegin;
Gor Nishanov90be1212017-03-06 21:12:54 +0000392
Gor Nishanov5eb58582017-03-26 02:18:05 +0000393 CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
Gor Nishanov63b6df42017-04-01 00:22:47 +0000394 {
395 CodeGenFunction::RunCleanupsScope ResumeScope(*this);
396 EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
Gor Nishanov90be1212017-03-06 21:12:54 +0000397
Gor Nishanov63b6df42017-04-01 00:22:47 +0000398 EmitStmt(S.getPromiseDeclStmt());
Gor Nishanov6a470682017-05-22 20:22:23 +0000399 EmitStmt(S.getResultDecl()); // FIXME: Gro lifetime is wrong.
Gor Nishanov90be1212017-03-06 21:12:54 +0000400
Gor Nishanov818a7762017-04-05 04:55:03 +0000401 EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
402
Gor Nishanov63b6df42017-04-01 00:22:47 +0000403 CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
Gor Nishanov90be1212017-03-06 21:12:54 +0000404
Gor Nishanov5efc6182017-05-23 05:04:01 +0000405 // FIXME: Emit param moves.
406
407 CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
408 EmitStmt(S.getInitSuspendStmt());
Gor Nishanov63b6df42017-04-01 00:22:47 +0000409
410 CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
Gor Nishanov5b050e42017-05-22 22:33:17 +0000411
412 if (auto *OnException = S.getExceptionHandler()) {
413 auto Loc = S.getLocStart();
414 CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr, OnException);
415 auto *TryStmt = CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);
416
417 EnterCXXTryStmt(*TryStmt);
418 emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());
419 ExitCXXTryStmt(*TryStmt);
420 }
421 else {
422 emitBodyAndFallthrough(*this, S, S.getBody());
423 }
Gor Nishanov63b6df42017-04-01 00:22:47 +0000424
425 // See if we need to generate final suspend.
426 const bool CanFallthrough = Builder.GetInsertBlock();
427 const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
428 if (CanFallthrough || HasCoreturns) {
429 EmitBlock(FinalBB);
Gor Nishanov5efc6182017-05-23 05:04:01 +0000430 CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
431 EmitStmt(S.getFinalSuspendStmt());
Gor Nishanov63b6df42017-04-01 00:22:47 +0000432 }
Gor Nishanovdb615dd2017-05-24 01:54:37 +0000433 else {
434 // We don't need FinalBB. Emit it to make sure the block is deleted.
435 EmitBlock(FinalBB, /*IsFinished=*/true);
436 }
Gor Nishanov90be1212017-03-06 21:12:54 +0000437 }
Gor Nishanov90be1212017-03-06 21:12:54 +0000438
Gor Nishanov5eb58582017-03-26 02:18:05 +0000439 EmitBlock(RetBB);
Gor Nishanov6a470682017-05-22 20:22:23 +0000440 // Emit coro.end before getReturnStmt (and parameter destructors), since
441 // resume and destroy parts of the coroutine should not include them.
Gor Nishanov818a7762017-04-05 04:55:03 +0000442 llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
443 Builder.CreateCall(CoroEnd, {NullPtr, Builder.getFalse()});
Gor Nishanov5eb58582017-03-26 02:18:05 +0000444
Gor Nishanov6a470682017-05-22 20:22:23 +0000445 if (Stmt *Ret = S.getReturnStmt())
446 EmitStmt(Ret);
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000447}
448
449// Emit coroutine intrinsic and patch up arguments of the token type.
450RValue CodeGenFunction::EmitCoroutineIntrinsic(const CallExpr *E,
451 unsigned int IID) {
452 SmallVector<llvm::Value *, 8> Args;
453 switch (IID) {
454 default:
455 break;
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000456 // The coro.frame builtin is replaced with an SSA value of the coro.begin
457 // intrinsic.
458 case llvm::Intrinsic::coro_frame: {
459 if (CurCoro.Data && CurCoro.Data->CoroBegin) {
460 return RValue::get(CurCoro.Data->CoroBegin);
461 }
462 CGM.Error(E->getLocStart(), "this builtin expect that __builtin_coro_begin "
463 "has been used earlier in this function");
464 auto NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
465 return RValue::get(NullPtr);
466 }
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000467 // The following three intrinsics take a token parameter referring to a token
468 // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
469 // builtins, we patch it up here.
470 case llvm::Intrinsic::coro_alloc:
471 case llvm::Intrinsic::coro_begin:
472 case llvm::Intrinsic::coro_free: {
473 if (CurCoro.Data && CurCoro.Data->CoroId) {
474 Args.push_back(CurCoro.Data->CoroId);
475 break;
476 }
477 CGM.Error(E->getLocStart(), "this builtin expect that __builtin_coro_id has"
478 " been used earlier in this function");
479 // Fallthrough to the next case to add TokenNone as the first argument.
480 }
481 // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
482 // argument.
483 case llvm::Intrinsic::coro_suspend:
484 Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
485 break;
486 }
487 for (auto &Arg : E->arguments())
488 Args.push_back(EmitScalarExpr(Arg));
489
490 llvm::Value *F = CGM.getIntrinsic(IID);
491 llvm::CallInst *Call = Builder.CreateCall(F, Args);
492
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000493 // Note: The following code is to enable to emit coro.id and coro.begin by
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000494 // hand to experiment with coroutines in C.
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000495 // If we see @llvm.coro.id remember it in the CoroData. We will update
496 // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
497 if (IID == llvm::Intrinsic::coro_id) {
498 createCoroData(*this, CurCoro, Call, E);
499 }
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000500 else if (IID == llvm::Intrinsic::coro_begin) {
501 if (CurCoro.Data)
502 CurCoro.Data->CoroBegin = Call;
503 }
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000504 else if (IID == llvm::Intrinsic::coro_free) {
505 // Remember the last coro_free as we need it to build the conditional
506 // deletion of the coroutine frame.
507 if (CurCoro.Data)
508 CurCoro.Data->LastCoroFree = Call;
509 } return RValue::get(Call);
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000510}