blob: bb98c2489086e0f346db35f52c99dfb06083eb4c [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();
154 auto Binder =
155 CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E);
156 auto UnbindOnExit = llvm::make_scope_exit([&] { Binder.unbind(CGF); });
157
158 auto Prefix = buildSuspendPrefixStr(Coro, Kind);
159 BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
160 BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
161 BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));
162
163 // If expression is ready, no need to suspend.
164 CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);
165
166 // Otherwise, emit suspend logic.
167 CGF.EmitBlock(SuspendBlock);
168
169 auto &Builder = CGF.Builder;
170 llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
171 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
172 auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
173
174 auto *SuspendRet = CGF.EmitScalarExpr(S.getSuspendExpr());
175 if (SuspendRet != nullptr) {
176 // Veto suspension if requested by bool returning await_suspend.
177 assert(SuspendRet->getType()->isIntegerTy(1) &&
178 "Sema should have already checked that it is void or bool");
179 BasicBlock *RealSuspendBlock =
180 CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
181 CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
182 SuspendBlock = RealSuspendBlock;
183 CGF.EmitBlock(RealSuspendBlock);
184 }
185
186 // Emit the suspend point.
187 const bool IsFinalSuspend = (Kind == AwaitKind::Final);
188 llvm::Function *CoroSuspend =
189 CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);
190 auto *SuspendResult = Builder.CreateCall(
191 CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});
192
193 // Create a switch capturing three possible continuations.
194 auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);
195 Switch->addCase(Builder.getInt8(0), ReadyBlock);
196 Switch->addCase(Builder.getInt8(1), CleanupBlock);
197
198 // Emit cleanup for this suspend point.
199 CGF.EmitBlock(CleanupBlock);
200 CGF.EmitBranchThroughCleanup(Coro.CleanupJD);
201
202 // Emit await_resume expression.
203 CGF.EmitBlock(ReadyBlock);
204 return CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
205}
206
207RValue CodeGenFunction::EmitCoawaitExpr(const CoawaitExpr &E,
208 AggValueSlot aggSlot,
209 bool ignoreResult) {
210 return emitSuspendExpression(*this, *CurCoro.Data, E,
211 CurCoro.Data->CurrentAwaitKind, aggSlot,
212 ignoreResult);
213}
214RValue CodeGenFunction::EmitCoyieldExpr(const CoyieldExpr &E,
215 AggValueSlot aggSlot,
216 bool ignoreResult) {
217 return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,
218 aggSlot, ignoreResult);
219}
220
Gor Nishanov90be1212017-03-06 21:12:54 +0000221void CodeGenFunction::EmitCoreturnStmt(CoreturnStmt const &S) {
222 ++CurCoro.Data->CoreturnCount;
223 EmitStmt(S.getPromiseCall());
224 EmitBranchThroughCleanup(CurCoro.Data->FinalJD);
225}
226
Gor Nishanov818a7762017-04-05 04:55:03 +0000227// For WinEH exception representation backend need to know what funclet coro.end
228// belongs to. That information is passed in a funclet bundle.
229static SmallVector<llvm::OperandBundleDef, 1>
230getBundlesForCoroEnd(CodeGenFunction &CGF) {
231 SmallVector<llvm::OperandBundleDef, 1> BundleList;
232
233 if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
234 BundleList.emplace_back("funclet", EHPad);
235
236 return BundleList;
237}
238
239namespace {
240// We will insert coro.end to cut any of the destructors for objects that
241// do not need to be destroyed once the coroutine is resumed.
242// See llvm/docs/Coroutines.rst for more details about coro.end.
243struct CallCoroEnd final : public EHScopeStack::Cleanup {
244 void Emit(CodeGenFunction &CGF, Flags flags) override {
245 auto &CGM = CGF.CGM;
246 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
247 llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
248 // See if we have a funclet bundle to associate coro.end with. (WinEH)
249 auto Bundles = getBundlesForCoroEnd(CGF);
250 auto *CoroEnd = CGF.Builder.CreateCall(
251 CoroEndFn, {NullPtr, CGF.Builder.getTrue()}, Bundles);
252 if (Bundles.empty()) {
253 // Otherwise, (landingpad model), create a conditional branch that leads
254 // either to a cleanup block or a block with EH resume instruction.
255 auto *ResumeBB = CGF.getEHResumeBlock(/*cleanup=*/true);
256 auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont");
257 CGF.Builder.CreateCondBr(CoroEnd, ResumeBB, CleanupContBB);
258 CGF.EmitBlock(CleanupContBB);
259 }
260 }
261};
262}
263
Gor Nishanov63b6df42017-04-01 00:22:47 +0000264namespace {
265// Make sure to call coro.delete on scope exit.
266struct CallCoroDelete final : public EHScopeStack::Cleanup {
267 Stmt *Deallocate;
268
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000269 // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
270
271 // Note: That deallocation will be emitted twice: once for a normal exit and
272 // once for exceptional exit. This usage is safe because Deallocate does not
273 // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
274 // builds a single call to a deallocation function which is safe to emit
275 // multiple times.
Gor Nishanov63b6df42017-04-01 00:22:47 +0000276 void Emit(CodeGenFunction &CGF, Flags) override {
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000277 // Remember the current point, as we are going to emit deallocation code
278 // first to get to coro.free instruction that is an argument to a delete
279 // call.
280 BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();
281
282 auto *FreeBB = CGF.createBasicBlock("coro.free");
283 CGF.EmitBlock(FreeBB);
Gor Nishanov63b6df42017-04-01 00:22:47 +0000284 CGF.EmitStmt(Deallocate);
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000285
286 auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free");
287 CGF.EmitBlock(AfterFreeBB);
288
289 // We should have captured coro.free from the emission of deallocate.
290 auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;
291 if (!CoroFree) {
292 CGF.CGM.Error(Deallocate->getLocStart(),
293 "Deallocation expressoin does not refer to coro.free");
294 return;
295 }
296
297 // Get back to the block we were originally and move coro.free there.
298 auto *InsertPt = SaveInsertBlock->getTerminator();
299 CoroFree->moveBefore(InsertPt);
300 CGF.Builder.SetInsertPoint(InsertPt);
301
302 // Add if (auto *mem = coro.free) Deallocate;
303 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
304 auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr);
305 CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB);
306
307 // No longer need old terminator.
308 InsertPt->eraseFromParent();
309 CGF.Builder.SetInsertPoint(AfterFreeBB);
Gor Nishanov63b6df42017-04-01 00:22:47 +0000310 }
311 explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}
312};
313}
314
Gor Nishanov5b050e42017-05-22 22:33:17 +0000315static void emitBodyAndFallthrough(CodeGenFunction &CGF,
316 const CoroutineBodyStmt &S, Stmt *Body) {
317 CGF.EmitStmt(Body);
318 const bool CanFallthrough = CGF.Builder.GetInsertBlock();
319 if (CanFallthrough)
320 if (Stmt *OnFallthrough = S.getFallthroughHandler())
321 CGF.EmitStmt(OnFallthrough);
322}
323
Gor Nishanov8df64e92016-10-27 16:28:31 +0000324void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt &S) {
325 auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
326 auto &TI = CGM.getContext().getTargetInfo();
327 unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
328
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000329 auto *EntryBB = Builder.GetInsertBlock();
330 auto *AllocBB = createBasicBlock("coro.alloc");
331 auto *InitBB = createBasicBlock("coro.init");
Gor Nishanov90be1212017-03-06 21:12:54 +0000332 auto *FinalBB = createBasicBlock("coro.final");
Gor Nishanov5eb58582017-03-26 02:18:05 +0000333 auto *RetBB = createBasicBlock("coro.ret");
Gor Nishanov90be1212017-03-06 21:12:54 +0000334
Gor Nishanov8df64e92016-10-27 16:28:31 +0000335 auto *CoroId = Builder.CreateCall(
336 CGM.getIntrinsic(llvm::Intrinsic::coro_id),
337 {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
338 createCoroData(*this, CurCoro, CoroId);
Gor Nishanov5eb58582017-03-26 02:18:05 +0000339 CurCoro.Data->SuspendBB = RetBB;
Gor Nishanov8df64e92016-10-27 16:28:31 +0000340
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000341 // Backend is allowed to elide memory allocations, to help it, emit
342 // auto mem = coro.alloc() ? 0 : ... allocation code ...;
343 auto *CoroAlloc = Builder.CreateCall(
344 CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});
345
346 Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);
347
348 EmitBlock(AllocBB);
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000349 auto *AllocateCall = EmitScalarExpr(S.getAllocate());
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000350 auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000351
352 // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
353 if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
354 auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000355
356 // See if allocation was successful.
357 auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);
358 auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);
359 Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);
360
361 // If not, return OnAllocFailure object.
362 EmitBlock(RetOnFailureBB);
363 EmitStmt(RetOnAllocFailure);
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000364 }
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000365 else {
366 Builder.CreateBr(InitBB);
367 }
368
369 EmitBlock(InitBB);
370
371 // Pass the result of the allocation to coro.begin.
372 auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);
373 Phi->addIncoming(NullPtr, EntryBB);
374 Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000375 auto *CoroBegin = Builder.CreateCall(
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000376 CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000377 CurCoro.Data->CoroBegin = CoroBegin;
Gor Nishanov90be1212017-03-06 21:12:54 +0000378
Gor Nishanov5eb58582017-03-26 02:18:05 +0000379 CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
Gor Nishanov63b6df42017-04-01 00:22:47 +0000380 {
381 CodeGenFunction::RunCleanupsScope ResumeScope(*this);
382 EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
Gor Nishanov90be1212017-03-06 21:12:54 +0000383
Gor Nishanov63b6df42017-04-01 00:22:47 +0000384 EmitStmt(S.getPromiseDeclStmt());
Gor Nishanov6a470682017-05-22 20:22:23 +0000385 EmitStmt(S.getResultDecl()); // FIXME: Gro lifetime is wrong.
Gor Nishanov90be1212017-03-06 21:12:54 +0000386
Gor Nishanov818a7762017-04-05 04:55:03 +0000387 EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
388
Gor Nishanov63b6df42017-04-01 00:22:47 +0000389 CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
Gor Nishanov90be1212017-03-06 21:12:54 +0000390
Gor Nishanov5efc6182017-05-23 05:04:01 +0000391 // FIXME: Emit param moves.
392
393 CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
394 EmitStmt(S.getInitSuspendStmt());
Gor Nishanov63b6df42017-04-01 00:22:47 +0000395
396 CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
Gor Nishanov5b050e42017-05-22 22:33:17 +0000397
398 if (auto *OnException = S.getExceptionHandler()) {
399 auto Loc = S.getLocStart();
400 CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr, OnException);
401 auto *TryStmt = CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);
402
403 EnterCXXTryStmt(*TryStmt);
404 emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());
405 ExitCXXTryStmt(*TryStmt);
406 }
407 else {
408 emitBodyAndFallthrough(*this, S, S.getBody());
409 }
Gor Nishanov63b6df42017-04-01 00:22:47 +0000410
411 // See if we need to generate final suspend.
412 const bool CanFallthrough = Builder.GetInsertBlock();
413 const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
414 if (CanFallthrough || HasCoreturns) {
415 EmitBlock(FinalBB);
Gor Nishanov5efc6182017-05-23 05:04:01 +0000416 CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
417 EmitStmt(S.getFinalSuspendStmt());
Gor Nishanov63b6df42017-04-01 00:22:47 +0000418 }
Gor Nishanov90be1212017-03-06 21:12:54 +0000419 }
Gor Nishanov90be1212017-03-06 21:12:54 +0000420
Gor Nishanov5eb58582017-03-26 02:18:05 +0000421 EmitBlock(RetBB);
Gor Nishanov6a470682017-05-22 20:22:23 +0000422 // Emit coro.end before getReturnStmt (and parameter destructors), since
423 // resume and destroy parts of the coroutine should not include them.
Gor Nishanov818a7762017-04-05 04:55:03 +0000424 llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
425 Builder.CreateCall(CoroEnd, {NullPtr, Builder.getFalse()});
Gor Nishanov5eb58582017-03-26 02:18:05 +0000426
Gor Nishanov6a470682017-05-22 20:22:23 +0000427 if (Stmt *Ret = S.getReturnStmt())
428 EmitStmt(Ret);
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000429}
430
431// Emit coroutine intrinsic and patch up arguments of the token type.
432RValue CodeGenFunction::EmitCoroutineIntrinsic(const CallExpr *E,
433 unsigned int IID) {
434 SmallVector<llvm::Value *, 8> Args;
435 switch (IID) {
436 default:
437 break;
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000438 // The coro.frame builtin is replaced with an SSA value of the coro.begin
439 // intrinsic.
440 case llvm::Intrinsic::coro_frame: {
441 if (CurCoro.Data && CurCoro.Data->CoroBegin) {
442 return RValue::get(CurCoro.Data->CoroBegin);
443 }
444 CGM.Error(E->getLocStart(), "this builtin expect that __builtin_coro_begin "
445 "has been used earlier in this function");
446 auto NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
447 return RValue::get(NullPtr);
448 }
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000449 // The following three intrinsics take a token parameter referring to a token
450 // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
451 // builtins, we patch it up here.
452 case llvm::Intrinsic::coro_alloc:
453 case llvm::Intrinsic::coro_begin:
454 case llvm::Intrinsic::coro_free: {
455 if (CurCoro.Data && CurCoro.Data->CoroId) {
456 Args.push_back(CurCoro.Data->CoroId);
457 break;
458 }
459 CGM.Error(E->getLocStart(), "this builtin expect that __builtin_coro_id has"
460 " been used earlier in this function");
461 // Fallthrough to the next case to add TokenNone as the first argument.
462 }
463 // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
464 // argument.
465 case llvm::Intrinsic::coro_suspend:
466 Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
467 break;
468 }
469 for (auto &Arg : E->arguments())
470 Args.push_back(EmitScalarExpr(Arg));
471
472 llvm::Value *F = CGM.getIntrinsic(IID);
473 llvm::CallInst *Call = Builder.CreateCall(F, Args);
474
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000475 // Note: The following code is to enable to emit coro.id and coro.begin by
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000476 // hand to experiment with coroutines in C.
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000477 // If we see @llvm.coro.id remember it in the CoroData. We will update
478 // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
479 if (IID == llvm::Intrinsic::coro_id) {
480 createCoroData(*this, CurCoro, Call, E);
481 }
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000482 else if (IID == llvm::Intrinsic::coro_begin) {
483 if (CurCoro.Data)
484 CurCoro.Data->CoroBegin = Call;
485 }
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000486 else if (IID == llvm::Intrinsic::coro_free) {
487 // Remember the last coro_free as we need it to build the conditional
488 // deletion of the coroutine frame.
489 if (CurCoro.Data)
490 CurCoro.Data->LastCoroFree = Call;
491 } return RValue::get(Call);
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000492}