blob: 7dd8e0508c034b0717f496cb90c6972e5a815fb6 [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 Nishanov97e3b6d2016-10-03 22:44:48 +000060 // If coro.id came from the builtin, remember the expression to give better
61 // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by
62 // EmitCoroutineBody.
63 CallExpr const *CoroIdExpr = nullptr;
64};
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000065
Gor Nishanov5eb58582017-03-26 02:18:05 +000066// Defining these here allows to keep CGCoroData private to this file.
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000067clang::CodeGen::CodeGenFunction::CGCoroInfo::CGCoroInfo() {}
68CodeGenFunction::CGCoroInfo::~CGCoroInfo() {}
69
Gor Nishanov8df64e92016-10-27 16:28:31 +000070static void createCoroData(CodeGenFunction &CGF,
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000071 CodeGenFunction::CGCoroInfo &CurCoro,
Gor Nishanov8df64e92016-10-27 16:28:31 +000072 llvm::CallInst *CoroId,
73 CallExpr const *CoroIdExpr = nullptr) {
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000074 if (CurCoro.Data) {
75 if (CurCoro.Data->CoroIdExpr)
76 CGF.CGM.Error(CoroIdExpr->getLocStart(),
77 "only one __builtin_coro_id can be used in a function");
78 else if (CoroIdExpr)
79 CGF.CGM.Error(CoroIdExpr->getLocStart(),
80 "__builtin_coro_id shall not be used in a C++ coroutine");
81 else
82 llvm_unreachable("EmitCoroutineBodyStatement called twice?");
83
Gor Nishanov8df64e92016-10-27 16:28:31 +000084 return;
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000085 }
86
87 CurCoro.Data = std::unique_ptr<CGCoroData>(new CGCoroData);
88 CurCoro.Data->CoroId = CoroId;
89 CurCoro.Data->CoroIdExpr = CoroIdExpr;
Gor Nishanov8df64e92016-10-27 16:28:31 +000090}
91
Gor Nishanov5eb58582017-03-26 02:18:05 +000092// Synthesize a pretty name for a suspend point.
93static SmallString<32> buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind) {
94 unsigned No = 0;
95 switch (Kind) {
96 case AwaitKind::Init:
97 case AwaitKind::Final:
98 break;
99 case AwaitKind::Normal:
100 No = ++Coro.AwaitNum;
101 break;
102 case AwaitKind::Yield:
103 No = ++Coro.YieldNum;
104 break;
105 }
106 SmallString<32> Prefix(AwaitKindStr[static_cast<unsigned>(Kind)]);
107 if (No > 1) {
108 Twine(No).toVector(Prefix);
109 }
110 return Prefix;
111}
112
113// Emit suspend expression which roughly looks like:
114//
115// auto && x = CommonExpr();
116// if (!x.await_ready()) {
117// llvm_coro_save();
118// x.await_suspend(...); (*)
119// llvm_coro_suspend(); (**)
120// }
121// x.await_resume();
122//
123// where the result of the entire expression is the result of x.await_resume()
124//
125// (*) If x.await_suspend return type is bool, it allows to veto a suspend:
126// if (x.await_suspend(...))
127// llvm_coro_suspend();
128//
129// (**) llvm_coro_suspend() encodes three possible continuations as
130// a switch instruction:
131//
132// %where-to = call i8 @llvm.coro.suspend(...)
133// switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend
134// i8 0, label %yield.ready ; go here when resumed
135// i8 1, label %yield.cleanup ; go here when destroyed
136// ]
137//
138// See llvm's docs/Coroutines.rst for more details.
139//
140static RValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,
141 CoroutineSuspendExpr const &S,
142 AwaitKind Kind, AggValueSlot aggSlot,
143 bool ignoreResult) {
144 auto *E = S.getCommonExpr();
145 auto Binder =
146 CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E);
147 auto UnbindOnExit = llvm::make_scope_exit([&] { Binder.unbind(CGF); });
148
149 auto Prefix = buildSuspendPrefixStr(Coro, Kind);
150 BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
151 BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
152 BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));
153
154 // If expression is ready, no need to suspend.
155 CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);
156
157 // Otherwise, emit suspend logic.
158 CGF.EmitBlock(SuspendBlock);
159
160 auto &Builder = CGF.Builder;
161 llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
162 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
163 auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
164
165 auto *SuspendRet = CGF.EmitScalarExpr(S.getSuspendExpr());
166 if (SuspendRet != nullptr) {
167 // Veto suspension if requested by bool returning await_suspend.
168 assert(SuspendRet->getType()->isIntegerTy(1) &&
169 "Sema should have already checked that it is void or bool");
170 BasicBlock *RealSuspendBlock =
171 CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
172 CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
173 SuspendBlock = RealSuspendBlock;
174 CGF.EmitBlock(RealSuspendBlock);
175 }
176
177 // Emit the suspend point.
178 const bool IsFinalSuspend = (Kind == AwaitKind::Final);
179 llvm::Function *CoroSuspend =
180 CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);
181 auto *SuspendResult = Builder.CreateCall(
182 CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});
183
184 // Create a switch capturing three possible continuations.
185 auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);
186 Switch->addCase(Builder.getInt8(0), ReadyBlock);
187 Switch->addCase(Builder.getInt8(1), CleanupBlock);
188
189 // Emit cleanup for this suspend point.
190 CGF.EmitBlock(CleanupBlock);
191 CGF.EmitBranchThroughCleanup(Coro.CleanupJD);
192
193 // Emit await_resume expression.
194 CGF.EmitBlock(ReadyBlock);
195 return CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
196}
197
198RValue CodeGenFunction::EmitCoawaitExpr(const CoawaitExpr &E,
199 AggValueSlot aggSlot,
200 bool ignoreResult) {
201 return emitSuspendExpression(*this, *CurCoro.Data, E,
202 CurCoro.Data->CurrentAwaitKind, aggSlot,
203 ignoreResult);
204}
205RValue CodeGenFunction::EmitCoyieldExpr(const CoyieldExpr &E,
206 AggValueSlot aggSlot,
207 bool ignoreResult) {
208 return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,
209 aggSlot, ignoreResult);
210}
211
Gor Nishanov90be1212017-03-06 21:12:54 +0000212void CodeGenFunction::EmitCoreturnStmt(CoreturnStmt const &S) {
213 ++CurCoro.Data->CoreturnCount;
214 EmitStmt(S.getPromiseCall());
215 EmitBranchThroughCleanup(CurCoro.Data->FinalJD);
216}
217
Gor Nishanov8df64e92016-10-27 16:28:31 +0000218void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt &S) {
219 auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
220 auto &TI = CGM.getContext().getTargetInfo();
221 unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
222
Gor Nishanov90be1212017-03-06 21:12:54 +0000223 auto *FinalBB = createBasicBlock("coro.final");
Gor Nishanov5eb58582017-03-26 02:18:05 +0000224 auto *RetBB = createBasicBlock("coro.ret");
Gor Nishanov90be1212017-03-06 21:12:54 +0000225
Gor Nishanov8df64e92016-10-27 16:28:31 +0000226 auto *CoroId = Builder.CreateCall(
227 CGM.getIntrinsic(llvm::Intrinsic::coro_id),
228 {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
229 createCoroData(*this, CurCoro, CoroId);
Gor Nishanov5eb58582017-03-26 02:18:05 +0000230 CurCoro.Data->SuspendBB = RetBB;
Gor Nishanov8df64e92016-10-27 16:28:31 +0000231
232 EmitScalarExpr(S.getAllocate());
Gor Nishanov90be1212017-03-06 21:12:54 +0000233
234 // FIXME: Setup cleanup scopes.
235
236 EmitStmt(S.getPromiseDeclStmt());
237
Gor Nishanov5eb58582017-03-26 02:18:05 +0000238 CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
Gor Nishanov90be1212017-03-06 21:12:54 +0000239 CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
240
241 // FIXME: Emit initial suspend and more before the body.
242
Gor Nishanov5eb58582017-03-26 02:18:05 +0000243 CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
Gor Nishanov90be1212017-03-06 21:12:54 +0000244 EmitStmt(S.getBody());
245
246 // See if we need to generate final suspend.
247 const bool CanFallthrough = Builder.GetInsertBlock();
248 const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
249 if (CanFallthrough || HasCoreturns) {
250 EmitBlock(FinalBB);
251 // FIXME: Emit final suspend.
252 }
Gor Nishanov8df64e92016-10-27 16:28:31 +0000253 EmitStmt(S.getDeallocate());
Gor Nishanov90be1212017-03-06 21:12:54 +0000254
Gor Nishanov5eb58582017-03-26 02:18:05 +0000255 EmitBlock(RetBB);
256
Gor Nishanov90be1212017-03-06 21:12:54 +0000257 // FIXME: Emit return for the coroutine return object.
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000258}
259
260// Emit coroutine intrinsic and patch up arguments of the token type.
261RValue CodeGenFunction::EmitCoroutineIntrinsic(const CallExpr *E,
262 unsigned int IID) {
263 SmallVector<llvm::Value *, 8> Args;
264 switch (IID) {
265 default:
266 break;
267 // The following three intrinsics take a token parameter referring to a token
268 // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
269 // builtins, we patch it up here.
270 case llvm::Intrinsic::coro_alloc:
271 case llvm::Intrinsic::coro_begin:
272 case llvm::Intrinsic::coro_free: {
273 if (CurCoro.Data && CurCoro.Data->CoroId) {
274 Args.push_back(CurCoro.Data->CoroId);
275 break;
276 }
277 CGM.Error(E->getLocStart(), "this builtin expect that __builtin_coro_id has"
278 " been used earlier in this function");
279 // Fallthrough to the next case to add TokenNone as the first argument.
280 }
281 // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
282 // argument.
283 case llvm::Intrinsic::coro_suspend:
284 Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
285 break;
286 }
287 for (auto &Arg : E->arguments())
288 Args.push_back(EmitScalarExpr(Arg));
289
290 llvm::Value *F = CGM.getIntrinsic(IID);
291 llvm::CallInst *Call = Builder.CreateCall(F, Args);
292
293 // If we see @llvm.coro.id remember it in the CoroData. We will update
294 // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
295 if (IID == llvm::Intrinsic::coro_id) {
296 createCoroData(*this, CurCoro, Call, E);
297 }
298 return RValue::get(Call);
299}