blob: f65fb5b9232ab08c699a0fe90dd51edf0140eddc [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
Gor Nishanov4c2f68f2017-05-24 02:38:26 +000014#include "CGCleanup.h"
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000015#include "CodeGenFunction.h"
Gor Nishanov5eb58582017-03-26 02:18:05 +000016#include "llvm/ADT/ScopeExit.h"
Gor Nishanov8df64e92016-10-27 16:28:31 +000017#include "clang/AST/StmtCXX.h"
Gor Nishanov33d5fd22017-05-24 20:09:14 +000018#include "clang/AST/StmtVisitor.h"
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000019
20using namespace clang;
21using namespace CodeGen;
22
Gor Nishanov5eb58582017-03-26 02:18:05 +000023using llvm::Value;
24using llvm::BasicBlock;
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000025
Gor Nishanov5eb58582017-03-26 02:18:05 +000026namespace {
27enum class AwaitKind { Init, Normal, Yield, Final };
28static constexpr llvm::StringLiteral AwaitKindStr[] = {"init", "await", "yield",
29 "final"};
30}
Gor Nishanov90be1212017-03-06 21:12:54 +000031
Gor Nishanov5eb58582017-03-26 02:18:05 +000032struct clang::CodeGen::CGCoroData {
33 // What is the current await expression kind and how many
34 // await/yield expressions were encountered so far.
35 // These are used to generate pretty labels for await expressions in LLVM IR.
36 AwaitKind CurrentAwaitKind = AwaitKind::Init;
37 unsigned AwaitNum = 0;
38 unsigned YieldNum = 0;
39
40 // How many co_return statements are in the coroutine. Used to decide whether
41 // we need to add co_return; equivalent at the end of the user authored body.
42 unsigned CoreturnCount = 0;
43
44 // A branch to this block is emitted when coroutine needs to suspend.
45 llvm::BasicBlock *SuspendBB = nullptr;
46
47 // Stores the jump destination just before the coroutine memory is freed.
48 // This is the destination that every suspend point jumps to for the cleanup
49 // branch.
50 CodeGenFunction::JumpDest CleanupJD;
51
52 // Stores the jump destination just before the final suspend. The co_return
Gor Nishanov90be1212017-03-06 21:12:54 +000053 // statements jumps to this point after calling return_xxx promise member.
54 CodeGenFunction::JumpDest FinalJD;
55
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000056 // Stores the llvm.coro.id emitted in the function so that we can supply it
57 // as the first argument to coro.begin, coro.alloc and coro.free intrinsics.
58 // Note: llvm.coro.id returns a token that cannot be directly expressed in a
59 // builtin.
60 llvm::CallInst *CoroId = nullptr;
Gor Nishanov5eb58582017-03-26 02:18:05 +000061
Gor Nishanov68fe6ee2017-05-23 03:46:59 +000062 // Stores the llvm.coro.begin emitted in the function so that we can replace
63 // all coro.frame intrinsics with direct SSA value of coro.begin that returns
64 // the address of the coroutine frame of the current coroutine.
65 llvm::CallInst *CoroBegin = nullptr;
66
Gor Nishanov6c4530c2017-05-23 04:21:27 +000067 // Stores the last emitted coro.free for the deallocate expressions, we use it
68 // to wrap dealloc code with if(auto mem = coro.free) dealloc(mem).
69 llvm::CallInst *LastCoroFree = nullptr;
70
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000071 // If coro.id came from the builtin, remember the expression to give better
72 // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by
73 // EmitCoroutineBody.
74 CallExpr const *CoroIdExpr = nullptr;
75};
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000076
Gor Nishanov5eb58582017-03-26 02:18:05 +000077// Defining these here allows to keep CGCoroData private to this file.
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000078clang::CodeGen::CodeGenFunction::CGCoroInfo::CGCoroInfo() {}
79CodeGenFunction::CGCoroInfo::~CGCoroInfo() {}
80
Gor Nishanov8df64e92016-10-27 16:28:31 +000081static void createCoroData(CodeGenFunction &CGF,
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000082 CodeGenFunction::CGCoroInfo &CurCoro,
Gor Nishanov8df64e92016-10-27 16:28:31 +000083 llvm::CallInst *CoroId,
84 CallExpr const *CoroIdExpr = nullptr) {
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000085 if (CurCoro.Data) {
86 if (CurCoro.Data->CoroIdExpr)
87 CGF.CGM.Error(CoroIdExpr->getLocStart(),
88 "only one __builtin_coro_id can be used in a function");
89 else if (CoroIdExpr)
90 CGF.CGM.Error(CoroIdExpr->getLocStart(),
91 "__builtin_coro_id shall not be used in a C++ coroutine");
92 else
93 llvm_unreachable("EmitCoroutineBodyStatement called twice?");
94
Gor Nishanov8df64e92016-10-27 16:28:31 +000095 return;
Gor Nishanov97e3b6d2016-10-03 22:44:48 +000096 }
97
98 CurCoro.Data = std::unique_ptr<CGCoroData>(new CGCoroData);
99 CurCoro.Data->CoroId = CoroId;
100 CurCoro.Data->CoroIdExpr = CoroIdExpr;
Gor Nishanov8df64e92016-10-27 16:28:31 +0000101}
102
Gor Nishanov5eb58582017-03-26 02:18:05 +0000103// Synthesize a pretty name for a suspend point.
104static SmallString<32> buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind) {
105 unsigned No = 0;
106 switch (Kind) {
107 case AwaitKind::Init:
108 case AwaitKind::Final:
109 break;
110 case AwaitKind::Normal:
111 No = ++Coro.AwaitNum;
112 break;
113 case AwaitKind::Yield:
114 No = ++Coro.YieldNum;
115 break;
116 }
117 SmallString<32> Prefix(AwaitKindStr[static_cast<unsigned>(Kind)]);
118 if (No > 1) {
119 Twine(No).toVector(Prefix);
120 }
121 return Prefix;
122}
123
124// Emit suspend expression which roughly looks like:
125//
126// auto && x = CommonExpr();
127// if (!x.await_ready()) {
128// llvm_coro_save();
129// x.await_suspend(...); (*)
130// llvm_coro_suspend(); (**)
131// }
132// x.await_resume();
133//
134// where the result of the entire expression is the result of x.await_resume()
135//
136// (*) If x.await_suspend return type is bool, it allows to veto a suspend:
137// if (x.await_suspend(...))
138// llvm_coro_suspend();
139//
140// (**) llvm_coro_suspend() encodes three possible continuations as
141// a switch instruction:
142//
143// %where-to = call i8 @llvm.coro.suspend(...)
144// switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend
145// i8 0, label %yield.ready ; go here when resumed
146// i8 1, label %yield.cleanup ; go here when destroyed
147// ]
148//
149// See llvm's docs/Coroutines.rst for more details.
150//
151static RValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,
152 CoroutineSuspendExpr const &S,
153 AwaitKind Kind, AggValueSlot aggSlot,
154 bool ignoreResult) {
155 auto *E = S.getCommonExpr();
Gor Nishanove4f15a22017-05-23 05:25:31 +0000156
157 // FIXME: rsmith 5/22/2017. Does it still make sense for us to have a
158 // UO_Coawait at all? As I recall, the only purpose it ever had was to
159 // represent a dependent co_await expression that couldn't yet be resolved to
160 // a CoawaitExpr. But now we have (and need!) a separate DependentCoawaitExpr
161 // node to store unqualified lookup results, it seems that the UnaryOperator
162 // portion of the representation serves no purpose (and as seen in this patch,
163 // it's getting in the way). Can we remove it?
164
165 // Skip passthrough operator co_await (present when awaiting on an LValue).
166 if (auto *UO = dyn_cast<UnaryOperator>(E))
167 if (UO->getOpcode() == UO_Coawait)
168 E = UO->getSubExpr();
169
Gor Nishanov5eb58582017-03-26 02:18:05 +0000170 auto Binder =
171 CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E);
172 auto UnbindOnExit = llvm::make_scope_exit([&] { Binder.unbind(CGF); });
173
174 auto Prefix = buildSuspendPrefixStr(Coro, Kind);
175 BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
176 BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
177 BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));
178
179 // If expression is ready, no need to suspend.
180 CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);
181
182 // Otherwise, emit suspend logic.
183 CGF.EmitBlock(SuspendBlock);
184
185 auto &Builder = CGF.Builder;
186 llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
187 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
188 auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
189
190 auto *SuspendRet = CGF.EmitScalarExpr(S.getSuspendExpr());
191 if (SuspendRet != nullptr) {
192 // Veto suspension if requested by bool returning await_suspend.
193 assert(SuspendRet->getType()->isIntegerTy(1) &&
194 "Sema should have already checked that it is void or bool");
195 BasicBlock *RealSuspendBlock =
196 CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
197 CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
198 SuspendBlock = RealSuspendBlock;
199 CGF.EmitBlock(RealSuspendBlock);
200 }
201
202 // Emit the suspend point.
203 const bool IsFinalSuspend = (Kind == AwaitKind::Final);
204 llvm::Function *CoroSuspend =
205 CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);
206 auto *SuspendResult = Builder.CreateCall(
207 CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});
208
209 // Create a switch capturing three possible continuations.
210 auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);
211 Switch->addCase(Builder.getInt8(0), ReadyBlock);
212 Switch->addCase(Builder.getInt8(1), CleanupBlock);
213
214 // Emit cleanup for this suspend point.
215 CGF.EmitBlock(CleanupBlock);
216 CGF.EmitBranchThroughCleanup(Coro.CleanupJD);
217
218 // Emit await_resume expression.
219 CGF.EmitBlock(ReadyBlock);
220 return CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
221}
222
223RValue CodeGenFunction::EmitCoawaitExpr(const CoawaitExpr &E,
224 AggValueSlot aggSlot,
225 bool ignoreResult) {
226 return emitSuspendExpression(*this, *CurCoro.Data, E,
227 CurCoro.Data->CurrentAwaitKind, aggSlot,
228 ignoreResult);
229}
230RValue CodeGenFunction::EmitCoyieldExpr(const CoyieldExpr &E,
231 AggValueSlot aggSlot,
232 bool ignoreResult) {
233 return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,
234 aggSlot, ignoreResult);
235}
236
Gor Nishanov90be1212017-03-06 21:12:54 +0000237void CodeGenFunction::EmitCoreturnStmt(CoreturnStmt const &S) {
238 ++CurCoro.Data->CoreturnCount;
239 EmitStmt(S.getPromiseCall());
240 EmitBranchThroughCleanup(CurCoro.Data->FinalJD);
241}
242
Gor Nishanov33d5fd22017-05-24 20:09:14 +0000243// Hunts for the parameter reference in the parameter copy/move declaration.
244namespace {
245struct GetParamRef : public StmtVisitor<GetParamRef> {
246public:
247 DeclRefExpr *Expr = nullptr;
248 GetParamRef() {}
249 void VisitDeclRefExpr(DeclRefExpr *E) {
250 assert(Expr == nullptr && "multilple declref in param move");
251 Expr = E;
252 }
253 void VisitStmt(Stmt *S) {
254 for (auto *C : S->children()) {
255 if (C)
256 Visit(C);
257 }
258 }
259};
260}
261
262// This class replaces references to parameters to their copies by changing
263// the addresses in CGF.LocalDeclMap and restoring back the original values in
264// its destructor.
265
266namespace {
267 struct ParamReferenceReplacerRAII {
268 CodeGenFunction::DeclMapTy SavedLocals;
269 CodeGenFunction::DeclMapTy& LocalDeclMap;
270
271 ParamReferenceReplacerRAII(CodeGenFunction::DeclMapTy &LocalDeclMap)
272 : LocalDeclMap(LocalDeclMap) {}
273
274 void addCopy(DeclStmt const *PM) {
275 // Figure out what param it refers to.
276
277 assert(PM->isSingleDecl());
278 VarDecl const*VD = static_cast<VarDecl const*>(PM->getSingleDecl());
279 Expr const *InitExpr = VD->getInit();
280 GetParamRef Visitor;
281 Visitor.Visit(const_cast<Expr*>(InitExpr));
282 assert(Visitor.Expr);
283 auto *DREOrig = cast<DeclRefExpr>(Visitor.Expr);
284 auto *PD = DREOrig->getDecl();
285
286 auto it = LocalDeclMap.find(PD);
287 assert(it != LocalDeclMap.end() && "parameter is not found");
288 SavedLocals.insert({ PD, it->second });
289
290 auto copyIt = LocalDeclMap.find(VD);
291 assert(copyIt != LocalDeclMap.end() && "parameter copy is not found");
292 it->second = copyIt->getSecond();
293 }
294
295 ~ParamReferenceReplacerRAII() {
296 for (auto&& SavedLocal : SavedLocals) {
297 LocalDeclMap.insert({SavedLocal.first, SavedLocal.second});
298 }
299 }
300 };
301}
302
303// For WinEH exception representation backend needs to know what funclet coro.end
Gor Nishanov818a7762017-04-05 04:55:03 +0000304// belongs to. That information is passed in a funclet bundle.
305static SmallVector<llvm::OperandBundleDef, 1>
306getBundlesForCoroEnd(CodeGenFunction &CGF) {
307 SmallVector<llvm::OperandBundleDef, 1> BundleList;
308
309 if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
310 BundleList.emplace_back("funclet", EHPad);
311
312 return BundleList;
313}
314
315namespace {
316// We will insert coro.end to cut any of the destructors for objects that
317// do not need to be destroyed once the coroutine is resumed.
318// See llvm/docs/Coroutines.rst for more details about coro.end.
319struct CallCoroEnd final : public EHScopeStack::Cleanup {
320 void Emit(CodeGenFunction &CGF, Flags flags) override {
321 auto &CGM = CGF.CGM;
322 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
323 llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
324 // See if we have a funclet bundle to associate coro.end with. (WinEH)
325 auto Bundles = getBundlesForCoroEnd(CGF);
326 auto *CoroEnd = CGF.Builder.CreateCall(
327 CoroEndFn, {NullPtr, CGF.Builder.getTrue()}, Bundles);
328 if (Bundles.empty()) {
329 // Otherwise, (landingpad model), create a conditional branch that leads
330 // either to a cleanup block or a block with EH resume instruction.
331 auto *ResumeBB = CGF.getEHResumeBlock(/*cleanup=*/true);
332 auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont");
333 CGF.Builder.CreateCondBr(CoroEnd, ResumeBB, CleanupContBB);
334 CGF.EmitBlock(CleanupContBB);
335 }
336 }
337};
338}
339
Gor Nishanov63b6df42017-04-01 00:22:47 +0000340namespace {
341// Make sure to call coro.delete on scope exit.
342struct CallCoroDelete final : public EHScopeStack::Cleanup {
343 Stmt *Deallocate;
344
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000345 // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
346
347 // Note: That deallocation will be emitted twice: once for a normal exit and
348 // once for exceptional exit. This usage is safe because Deallocate does not
349 // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
350 // builds a single call to a deallocation function which is safe to emit
351 // multiple times.
Gor Nishanov63b6df42017-04-01 00:22:47 +0000352 void Emit(CodeGenFunction &CGF, Flags) override {
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000353 // Remember the current point, as we are going to emit deallocation code
354 // first to get to coro.free instruction that is an argument to a delete
355 // call.
356 BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();
357
358 auto *FreeBB = CGF.createBasicBlock("coro.free");
359 CGF.EmitBlock(FreeBB);
Gor Nishanov63b6df42017-04-01 00:22:47 +0000360 CGF.EmitStmt(Deallocate);
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000361
362 auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free");
363 CGF.EmitBlock(AfterFreeBB);
364
365 // We should have captured coro.free from the emission of deallocate.
366 auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;
367 if (!CoroFree) {
368 CGF.CGM.Error(Deallocate->getLocStart(),
369 "Deallocation expressoin does not refer to coro.free");
370 return;
371 }
372
373 // Get back to the block we were originally and move coro.free there.
374 auto *InsertPt = SaveInsertBlock->getTerminator();
375 CoroFree->moveBefore(InsertPt);
376 CGF.Builder.SetInsertPoint(InsertPt);
377
378 // Add if (auto *mem = coro.free) Deallocate;
379 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
380 auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr);
381 CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB);
382
383 // No longer need old terminator.
384 InsertPt->eraseFromParent();
385 CGF.Builder.SetInsertPoint(AfterFreeBB);
Gor Nishanov63b6df42017-04-01 00:22:47 +0000386 }
387 explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}
388};
389}
390
Gor Nishanov4c2f68f2017-05-24 02:38:26 +0000391namespace {
392struct GetReturnObjectManager {
393 CodeGenFunction &CGF;
394 CGBuilderTy &Builder;
395 const CoroutineBodyStmt &S;
396
397 Address GroActiveFlag;
398 CodeGenFunction::AutoVarEmission GroEmission;
399
400 GetReturnObjectManager(CodeGenFunction &CGF, const CoroutineBodyStmt &S)
401 : CGF(CGF), Builder(CGF.Builder), S(S), GroActiveFlag(Address::invalid()),
402 GroEmission(CodeGenFunction::AutoVarEmission::invalid()) {}
403
404 // The gro variable has to outlive coroutine frame and coroutine promise, but,
405 // it can only be initialized after coroutine promise was created, thus, we
406 // split its emission in two parts. EmitGroAlloca emits an alloca and sets up
407 // cleanups. Later when coroutine promise is available we initialize the gro
408 // and sets the flag that the cleanup is now active.
409
410 void EmitGroAlloca() {
411 auto *GroDeclStmt = dyn_cast<DeclStmt>(S.getResultDecl());
412 if (!GroDeclStmt) {
413 // If get_return_object returns void, no need to do an alloca.
414 return;
415 }
416
417 auto *GroVarDecl = cast<VarDecl>(GroDeclStmt->getSingleDecl());
418
419 // Set GRO flag that it is not initialized yet
420 GroActiveFlag =
421 CGF.CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(), "gro.active");
422 Builder.CreateStore(Builder.getFalse(), GroActiveFlag);
423
424 GroEmission = CGF.EmitAutoVarAlloca(*GroVarDecl);
425
426 // Remember the top of EHStack before emitting the cleanup.
427 auto old_top = CGF.EHStack.stable_begin();
428 CGF.EmitAutoVarCleanups(GroEmission);
429 auto top = CGF.EHStack.stable_begin();
430
431 // Make the cleanup conditional on gro.active
432 for (auto b = CGF.EHStack.find(top), e = CGF.EHStack.find(old_top);
433 b != e; b++) {
434 if (auto *Cleanup = dyn_cast<EHCleanupScope>(&*b)) {
435 assert(!Cleanup->hasActiveFlag() && "cleanup already has active flag?");
436 Cleanup->setActiveFlag(GroActiveFlag);
437 Cleanup->setTestFlagInEHCleanup();
438 Cleanup->setTestFlagInNormalCleanup();
439 }
440 }
441 }
442
443 void EmitGroInit() {
444 if (!GroActiveFlag.isValid()) {
445 // No Gro variable was allocated. Simply emit the call to
446 // get_return_object.
447 CGF.EmitStmt(S.getResultDecl());
448 return;
449 }
450
451 CGF.EmitAutoVarInit(GroEmission);
452 Builder.CreateStore(Builder.getTrue(), GroActiveFlag);
453 }
454};
455}
456
Gor Nishanov5b050e42017-05-22 22:33:17 +0000457static void emitBodyAndFallthrough(CodeGenFunction &CGF,
458 const CoroutineBodyStmt &S, Stmt *Body) {
459 CGF.EmitStmt(Body);
460 const bool CanFallthrough = CGF.Builder.GetInsertBlock();
461 if (CanFallthrough)
462 if (Stmt *OnFallthrough = S.getFallthroughHandler())
463 CGF.EmitStmt(OnFallthrough);
464}
465
Gor Nishanov8df64e92016-10-27 16:28:31 +0000466void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt &S) {
467 auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
468 auto &TI = CGM.getContext().getTargetInfo();
469 unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
470
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000471 auto *EntryBB = Builder.GetInsertBlock();
472 auto *AllocBB = createBasicBlock("coro.alloc");
473 auto *InitBB = createBasicBlock("coro.init");
Gor Nishanov90be1212017-03-06 21:12:54 +0000474 auto *FinalBB = createBasicBlock("coro.final");
Gor Nishanov5eb58582017-03-26 02:18:05 +0000475 auto *RetBB = createBasicBlock("coro.ret");
Gor Nishanov90be1212017-03-06 21:12:54 +0000476
Gor Nishanov8df64e92016-10-27 16:28:31 +0000477 auto *CoroId = Builder.CreateCall(
478 CGM.getIntrinsic(llvm::Intrinsic::coro_id),
479 {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
480 createCoroData(*this, CurCoro, CoroId);
Gor Nishanov5eb58582017-03-26 02:18:05 +0000481 CurCoro.Data->SuspendBB = RetBB;
Gor Nishanov8df64e92016-10-27 16:28:31 +0000482
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000483 // Backend is allowed to elide memory allocations, to help it, emit
484 // auto mem = coro.alloc() ? 0 : ... allocation code ...;
485 auto *CoroAlloc = Builder.CreateCall(
486 CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});
487
488 Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);
489
490 EmitBlock(AllocBB);
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000491 auto *AllocateCall = EmitScalarExpr(S.getAllocate());
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000492 auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000493
494 // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
495 if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
496 auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000497
498 // See if allocation was successful.
499 auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);
500 auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);
501 Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);
502
503 // If not, return OnAllocFailure object.
504 EmitBlock(RetOnFailureBB);
505 EmitStmt(RetOnAllocFailure);
Gor Nishanov3aa9eb32017-03-27 23:36:59 +0000506 }
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000507 else {
508 Builder.CreateBr(InitBB);
509 }
510
511 EmitBlock(InitBB);
512
513 // Pass the result of the allocation to coro.begin.
514 auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);
515 Phi->addIncoming(NullPtr, EntryBB);
516 Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000517 auto *CoroBegin = Builder.CreateCall(
Gor Nishanovaa6e9a92017-05-23 01:13:17 +0000518 CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000519 CurCoro.Data->CoroBegin = CoroBegin;
Gor Nishanov90be1212017-03-06 21:12:54 +0000520
Gor Nishanov4c2f68f2017-05-24 02:38:26 +0000521 GetReturnObjectManager GroManager(*this, S);
522 GroManager.EmitGroAlloca();
523
Gor Nishanov5eb58582017-03-26 02:18:05 +0000524 CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
Gor Nishanov63b6df42017-04-01 00:22:47 +0000525 {
Gor Nishanov33d5fd22017-05-24 20:09:14 +0000526 ParamReferenceReplacerRAII ParamReplacer(LocalDeclMap);
Gor Nishanov63b6df42017-04-01 00:22:47 +0000527 CodeGenFunction::RunCleanupsScope ResumeScope(*this);
528 EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
Gor Nishanov90be1212017-03-06 21:12:54 +0000529
Gor Nishanov33d5fd22017-05-24 20:09:14 +0000530 // Create parameter copies. We do it before creating a promise, since an
531 // evolution of coroutine TS may allow promise constructor to observe
532 // parameter copies.
533 for (auto *PM : S.getParamMoves()) {
534 EmitStmt(PM);
535 ParamReplacer.addCopy(cast<DeclStmt>(PM));
536 // TODO: if(CoroParam(...)) need to surround ctor and dtor
537 // for the copy, so that llvm can elide it if the copy is
538 // not needed.
539 }
540
Gor Nishanov63b6df42017-04-01 00:22:47 +0000541 EmitStmt(S.getPromiseDeclStmt());
Gor Nishanov90be1212017-03-06 21:12:54 +0000542
Gor Nishanov33d5fd22017-05-24 20:09:14 +0000543 Address PromiseAddr = GetAddrOfLocalVar(S.getPromiseDecl());
544 auto *PromiseAddrVoidPtr =
545 new llvm::BitCastInst(PromiseAddr.getPointer(), VoidPtrTy, "", CoroId);
546 // Update CoroId to refer to the promise. We could not do it earlier because
547 // promise local variable was not emitted yet.
548 CoroId->setArgOperand(1, PromiseAddrVoidPtr);
549
Gor Nishanov4c2f68f2017-05-24 02:38:26 +0000550 // Now we have the promise, initialize the GRO
551 GroManager.EmitGroInit();
Gor Nishanov33d5fd22017-05-24 20:09:14 +0000552
Gor Nishanov818a7762017-04-05 04:55:03 +0000553 EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
554
Gor Nishanov5efc6182017-05-23 05:04:01 +0000555 CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
556 EmitStmt(S.getInitSuspendStmt());
Gor Nishanov33d5fd22017-05-24 20:09:14 +0000557 CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
Gor Nishanov63b6df42017-04-01 00:22:47 +0000558
559 CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
Gor Nishanov5b050e42017-05-22 22:33:17 +0000560
561 if (auto *OnException = S.getExceptionHandler()) {
562 auto Loc = S.getLocStart();
563 CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr, OnException);
564 auto *TryStmt = CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);
565
566 EnterCXXTryStmt(*TryStmt);
567 emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());
568 ExitCXXTryStmt(*TryStmt);
569 }
570 else {
571 emitBodyAndFallthrough(*this, S, S.getBody());
572 }
Gor Nishanov63b6df42017-04-01 00:22:47 +0000573
574 // See if we need to generate final suspend.
575 const bool CanFallthrough = Builder.GetInsertBlock();
576 const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
577 if (CanFallthrough || HasCoreturns) {
578 EmitBlock(FinalBB);
Gor Nishanov5efc6182017-05-23 05:04:01 +0000579 CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
580 EmitStmt(S.getFinalSuspendStmt());
Gor Nishanov75a8ea52017-05-29 21:15:31 +0000581 } else {
Gor Nishanovdb615dd2017-05-24 01:54:37 +0000582 // We don't need FinalBB. Emit it to make sure the block is deleted.
583 EmitBlock(FinalBB, /*IsFinished=*/true);
584 }
Gor Nishanov90be1212017-03-06 21:12:54 +0000585 }
Gor Nishanov90be1212017-03-06 21:12:54 +0000586
Gor Nishanov5eb58582017-03-26 02:18:05 +0000587 EmitBlock(RetBB);
Gor Nishanov6a470682017-05-22 20:22:23 +0000588 // Emit coro.end before getReturnStmt (and parameter destructors), since
589 // resume and destroy parts of the coroutine should not include them.
Gor Nishanov818a7762017-04-05 04:55:03 +0000590 llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
591 Builder.CreateCall(CoroEnd, {NullPtr, Builder.getFalse()});
Gor Nishanov5eb58582017-03-26 02:18:05 +0000592
Gor Nishanov6a470682017-05-22 20:22:23 +0000593 if (Stmt *Ret = S.getReturnStmt())
594 EmitStmt(Ret);
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000595}
596
597// Emit coroutine intrinsic and patch up arguments of the token type.
598RValue CodeGenFunction::EmitCoroutineIntrinsic(const CallExpr *E,
599 unsigned int IID) {
600 SmallVector<llvm::Value *, 8> Args;
601 switch (IID) {
602 default:
603 break;
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000604 // The coro.frame builtin is replaced with an SSA value of the coro.begin
605 // intrinsic.
606 case llvm::Intrinsic::coro_frame: {
607 if (CurCoro.Data && CurCoro.Data->CoroBegin) {
608 return RValue::get(CurCoro.Data->CoroBegin);
609 }
610 CGM.Error(E->getLocStart(), "this builtin expect that __builtin_coro_begin "
611 "has been used earlier in this function");
612 auto NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
613 return RValue::get(NullPtr);
614 }
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000615 // The following three intrinsics take a token parameter referring to a token
616 // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
617 // builtins, we patch it up here.
618 case llvm::Intrinsic::coro_alloc:
619 case llvm::Intrinsic::coro_begin:
620 case llvm::Intrinsic::coro_free: {
621 if (CurCoro.Data && CurCoro.Data->CoroId) {
622 Args.push_back(CurCoro.Data->CoroId);
623 break;
624 }
625 CGM.Error(E->getLocStart(), "this builtin expect that __builtin_coro_id has"
626 " been used earlier in this function");
627 // Fallthrough to the next case to add TokenNone as the first argument.
628 }
629 // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
630 // argument.
631 case llvm::Intrinsic::coro_suspend:
632 Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
633 break;
634 }
635 for (auto &Arg : E->arguments())
636 Args.push_back(EmitScalarExpr(Arg));
637
638 llvm::Value *F = CGM.getIntrinsic(IID);
639 llvm::CallInst *Call = Builder.CreateCall(F, Args);
640
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000641 // Note: The following code is to enable to emit coro.id and coro.begin by
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000642 // hand to experiment with coroutines in C.
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000643 // If we see @llvm.coro.id remember it in the CoroData. We will update
644 // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
645 if (IID == llvm::Intrinsic::coro_id) {
646 createCoroData(*this, CurCoro, Call, E);
647 }
Gor Nishanov68fe6ee2017-05-23 03:46:59 +0000648 else if (IID == llvm::Intrinsic::coro_begin) {
649 if (CurCoro.Data)
650 CurCoro.Data->CoroBegin = Call;
651 }
Gor Nishanov6c4530c2017-05-23 04:21:27 +0000652 else if (IID == llvm::Intrinsic::coro_free) {
653 // Remember the last coro_free as we need it to build the conditional
654 // deletion of the coroutine frame.
655 if (CurCoro.Data)
656 CurCoro.Data->LastCoroFree = Call;
Gor Nishanov33d5fd22017-05-24 20:09:14 +0000657 }
658 return RValue::get(Call);
Gor Nishanov97e3b6d2016-10-03 22:44:48 +0000659}