]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CGCoroutine.cpp
Merge llvm, clang, compiler-rt, libc++, libunwind, lld, lldb and openmp
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / CodeGen / CGCoroutine.cpp
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
14 #include "CGCleanup.h"
15 #include "CodeGenFunction.h"
16 #include "llvm/ADT/ScopeExit.h"
17 #include "clang/AST/StmtCXX.h"
18 #include "clang/AST/StmtVisitor.h"
19
20 using namespace clang;
21 using namespace CodeGen;
22
23 using llvm::Value;
24 using llvm::BasicBlock;
25
26 namespace {
27 enum class AwaitKind { Init, Normal, Yield, Final };
28 static constexpr llvm::StringLiteral AwaitKindStr[] = {"init", "await", "yield",
29                                                        "final"};
30 }
31
32 struct 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   // The promise type's 'unhandled_exception' handler, if it defines one.
48   Stmt *ExceptionHandler = nullptr;
49
50   // A temporary i1 alloca that stores whether 'await_resume' threw an
51   // exception. If it did, 'true' is stored in this variable, and the coroutine
52   // body must be skipped. If the promise type does not define an exception
53   // handler, this is null.
54   llvm::Value *ResumeEHVar = nullptr;
55
56   // Stores the jump destination just before the coroutine memory is freed.
57   // This is the destination that every suspend point jumps to for the cleanup
58   // branch.
59   CodeGenFunction::JumpDest CleanupJD;
60
61   // Stores the jump destination just before the final suspend. The co_return
62   // statements jumps to this point after calling return_xxx promise member.
63   CodeGenFunction::JumpDest FinalJD;
64
65   // Stores the llvm.coro.id emitted in the function so that we can supply it
66   // as the first argument to coro.begin, coro.alloc and coro.free intrinsics.
67   // Note: llvm.coro.id returns a token that cannot be directly expressed in a
68   // builtin.
69   llvm::CallInst *CoroId = nullptr;
70
71   // Stores the llvm.coro.begin emitted in the function so that we can replace
72   // all coro.frame intrinsics with direct SSA value of coro.begin that returns
73   // the address of the coroutine frame of the current coroutine.
74   llvm::CallInst *CoroBegin = nullptr;
75
76   // Stores the last emitted coro.free for the deallocate expressions, we use it
77   // to wrap dealloc code with if(auto mem = coro.free) dealloc(mem).
78   llvm::CallInst *LastCoroFree = nullptr;
79
80   // If coro.id came from the builtin, remember the expression to give better
81   // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by
82   // EmitCoroutineBody.
83   CallExpr const *CoroIdExpr = nullptr;
84 };
85
86 // Defining these here allows to keep CGCoroData private to this file.
87 clang::CodeGen::CodeGenFunction::CGCoroInfo::CGCoroInfo() {}
88 CodeGenFunction::CGCoroInfo::~CGCoroInfo() {}
89
90 static void createCoroData(CodeGenFunction &CGF,
91                            CodeGenFunction::CGCoroInfo &CurCoro,
92                            llvm::CallInst *CoroId,
93                            CallExpr const *CoroIdExpr = nullptr) {
94   if (CurCoro.Data) {
95     if (CurCoro.Data->CoroIdExpr)
96       CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
97                     "only one __builtin_coro_id can be used in a function");
98     else if (CoroIdExpr)
99       CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
100                     "__builtin_coro_id shall not be used in a C++ coroutine");
101     else
102       llvm_unreachable("EmitCoroutineBodyStatement called twice?");
103
104     return;
105   }
106
107   CurCoro.Data = std::unique_ptr<CGCoroData>(new CGCoroData);
108   CurCoro.Data->CoroId = CoroId;
109   CurCoro.Data->CoroIdExpr = CoroIdExpr;
110 }
111
112 // Synthesize a pretty name for a suspend point.
113 static SmallString<32> buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind) {
114   unsigned No = 0;
115   switch (Kind) {
116   case AwaitKind::Init:
117   case AwaitKind::Final:
118     break;
119   case AwaitKind::Normal:
120     No = ++Coro.AwaitNum;
121     break;
122   case AwaitKind::Yield:
123     No = ++Coro.YieldNum;
124     break;
125   }
126   SmallString<32> Prefix(AwaitKindStr[static_cast<unsigned>(Kind)]);
127   if (No > 1) {
128     Twine(No).toVector(Prefix);
129   }
130   return Prefix;
131 }
132
133 static bool memberCallExpressionCanThrow(const Expr *E) {
134   if (const auto *CE = dyn_cast<CXXMemberCallExpr>(E))
135     if (const auto *Proto =
136             CE->getMethodDecl()->getType()->getAs<FunctionProtoType>())
137       if (isNoexceptExceptionSpec(Proto->getExceptionSpecType()) &&
138           Proto->canThrow() == CT_Cannot)
139         return false;
140   return true;
141 }
142
143 // Emit suspend expression which roughly looks like:
144 //
145 //   auto && x = CommonExpr();
146 //   if (!x.await_ready()) {
147 //      llvm_coro_save();
148 //      x.await_suspend(...);     (*)
149 //      llvm_coro_suspend(); (**)
150 //   }
151 //   x.await_resume();
152 //
153 // where the result of the entire expression is the result of x.await_resume()
154 //
155 //   (*) If x.await_suspend return type is bool, it allows to veto a suspend:
156 //      if (x.await_suspend(...))
157 //        llvm_coro_suspend();
158 //
159 //  (**) llvm_coro_suspend() encodes three possible continuations as
160 //       a switch instruction:
161 //
162 //  %where-to = call i8 @llvm.coro.suspend(...)
163 //  switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend
164 //    i8 0, label %yield.ready   ; go here when resumed
165 //    i8 1, label %yield.cleanup ; go here when destroyed
166 //  ]
167 //
168 //  See llvm's docs/Coroutines.rst for more details.
169 //
170 namespace {
171   struct LValueOrRValue {
172     LValue LV;
173     RValue RV;
174   };
175 }
176 static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,
177                                     CoroutineSuspendExpr const &S,
178                                     AwaitKind Kind, AggValueSlot aggSlot,
179                                     bool ignoreResult, bool forLValue) {
180   auto *E = S.getCommonExpr();
181
182   auto Binder =
183       CodeGenFunction::OpaqueValueMappingData::bind(CGF, S.getOpaqueValue(), E);
184   auto UnbindOnExit = llvm::make_scope_exit([&] { Binder.unbind(CGF); });
185
186   auto Prefix = buildSuspendPrefixStr(Coro, Kind);
187   BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
188   BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
189   BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));
190
191   // If expression is ready, no need to suspend.
192   CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);
193
194   // Otherwise, emit suspend logic.
195   CGF.EmitBlock(SuspendBlock);
196
197   auto &Builder = CGF.Builder;
198   llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
199   auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
200   auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
201
202   auto *SuspendRet = CGF.EmitScalarExpr(S.getSuspendExpr());
203   if (SuspendRet != nullptr && SuspendRet->getType()->isIntegerTy(1)) {
204     // Veto suspension if requested by bool returning await_suspend.
205     BasicBlock *RealSuspendBlock =
206         CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
207     CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
208     SuspendBlock = RealSuspendBlock;
209     CGF.EmitBlock(RealSuspendBlock);
210   }
211
212   // Emit the suspend point.
213   const bool IsFinalSuspend = (Kind == AwaitKind::Final);
214   llvm::Function *CoroSuspend =
215       CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);
216   auto *SuspendResult = Builder.CreateCall(
217       CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});
218
219   // Create a switch capturing three possible continuations.
220   auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);
221   Switch->addCase(Builder.getInt8(0), ReadyBlock);
222   Switch->addCase(Builder.getInt8(1), CleanupBlock);
223
224   // Emit cleanup for this suspend point.
225   CGF.EmitBlock(CleanupBlock);
226   CGF.EmitBranchThroughCleanup(Coro.CleanupJD);
227
228   // Emit await_resume expression.
229   CGF.EmitBlock(ReadyBlock);
230
231   // Exception handling requires additional IR. If the 'await_resume' function
232   // is marked as 'noexcept', we avoid generating this additional IR.
233   CXXTryStmt *TryStmt = nullptr;
234   if (Coro.ExceptionHandler && Kind == AwaitKind::Init &&
235       memberCallExpressionCanThrow(S.getResumeExpr())) {
236     Coro.ResumeEHVar =
237         CGF.CreateTempAlloca(Builder.getInt1Ty(), Prefix + Twine("resume.eh"));
238     Builder.CreateFlagStore(true, Coro.ResumeEHVar);
239
240     auto Loc = S.getResumeExpr()->getExprLoc();
241     auto *Catch = new (CGF.getContext())
242         CXXCatchStmt(Loc, /*exDecl=*/nullptr, Coro.ExceptionHandler);
243     auto *TryBody =
244         CompoundStmt::Create(CGF.getContext(), S.getResumeExpr(), Loc, Loc);
245     TryStmt = CXXTryStmt::Create(CGF.getContext(), Loc, TryBody, Catch);
246     CGF.EnterCXXTryStmt(*TryStmt);
247   }
248
249   LValueOrRValue Res;
250   if (forLValue)
251     Res.LV = CGF.EmitLValue(S.getResumeExpr());
252   else
253     Res.RV = CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
254
255   if (TryStmt) {
256     Builder.CreateFlagStore(false, Coro.ResumeEHVar);
257     CGF.ExitCXXTryStmt(*TryStmt);
258   }
259
260   return Res;
261 }
262
263 RValue CodeGenFunction::EmitCoawaitExpr(const CoawaitExpr &E,
264                                         AggValueSlot aggSlot,
265                                         bool ignoreResult) {
266   return emitSuspendExpression(*this, *CurCoro.Data, E,
267                                CurCoro.Data->CurrentAwaitKind, aggSlot,
268                                ignoreResult, /*forLValue*/false).RV;
269 }
270 RValue CodeGenFunction::EmitCoyieldExpr(const CoyieldExpr &E,
271                                         AggValueSlot aggSlot,
272                                         bool ignoreResult) {
273   return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,
274                                aggSlot, ignoreResult, /*forLValue*/false).RV;
275 }
276
277 void CodeGenFunction::EmitCoreturnStmt(CoreturnStmt const &S) {
278   ++CurCoro.Data->CoreturnCount;
279   const Expr *RV = S.getOperand();
280   if (RV && RV->getType()->isVoidType()) {
281     // Make sure to evaluate the expression of a co_return with a void
282     // expression for side effects.
283     RunCleanupsScope cleanupScope(*this);
284     EmitIgnoredExpr(RV);
285   }
286   EmitStmt(S.getPromiseCall());
287   EmitBranchThroughCleanup(CurCoro.Data->FinalJD);
288 }
289
290
291 #ifndef NDEBUG
292 static QualType getCoroutineSuspendExprReturnType(const ASTContext &Ctx,
293   const CoroutineSuspendExpr *E) {
294   const auto *RE = E->getResumeExpr();
295   // Is it possible for RE to be a CXXBindTemporaryExpr wrapping
296   // a MemberCallExpr?
297   assert(isa<CallExpr>(RE) && "unexpected suspend expression type");
298   return cast<CallExpr>(RE)->getCallReturnType(Ctx);
299 }
300 #endif
301
302 LValue
303 CodeGenFunction::EmitCoawaitLValue(const CoawaitExpr *E) {
304   assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
305          "Can't have a scalar return unless the return type is a "
306          "reference type!");
307   return emitSuspendExpression(*this, *CurCoro.Data, *E,
308                                CurCoro.Data->CurrentAwaitKind, AggValueSlot::ignored(),
309                                /*ignoreResult*/false, /*forLValue*/true).LV;
310 }
311
312 LValue
313 CodeGenFunction::EmitCoyieldLValue(const CoyieldExpr *E) {
314   assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
315          "Can't have a scalar return unless the return type is a "
316          "reference type!");
317   return emitSuspendExpression(*this, *CurCoro.Data, *E,
318                                AwaitKind::Yield, AggValueSlot::ignored(),
319                                /*ignoreResult*/false, /*forLValue*/true).LV;
320 }
321
322 // Hunts for the parameter reference in the parameter copy/move declaration.
323 namespace {
324 struct GetParamRef : public StmtVisitor<GetParamRef> {
325 public:
326   DeclRefExpr *Expr = nullptr;
327   GetParamRef() {}
328   void VisitDeclRefExpr(DeclRefExpr *E) {
329     assert(Expr == nullptr && "multilple declref in param move");
330     Expr = E;
331   }
332   void VisitStmt(Stmt *S) {
333     for (auto *C : S->children()) {
334       if (C)
335         Visit(C);
336     }
337   }
338 };
339 }
340
341 // This class replaces references to parameters to their copies by changing
342 // the addresses in CGF.LocalDeclMap and restoring back the original values in
343 // its destructor.
344
345 namespace {
346   struct ParamReferenceReplacerRAII {
347     CodeGenFunction::DeclMapTy SavedLocals;
348     CodeGenFunction::DeclMapTy& LocalDeclMap;
349
350     ParamReferenceReplacerRAII(CodeGenFunction::DeclMapTy &LocalDeclMap)
351         : LocalDeclMap(LocalDeclMap) {}
352
353     void addCopy(DeclStmt const *PM) {
354       // Figure out what param it refers to.
355
356       assert(PM->isSingleDecl());
357       VarDecl const*VD = static_cast<VarDecl const*>(PM->getSingleDecl());
358       Expr const *InitExpr = VD->getInit();
359       GetParamRef Visitor;
360       Visitor.Visit(const_cast<Expr*>(InitExpr));
361       assert(Visitor.Expr);
362       DeclRefExpr *DREOrig = Visitor.Expr;
363       auto *PD = DREOrig->getDecl();
364
365       auto it = LocalDeclMap.find(PD);
366       assert(it != LocalDeclMap.end() && "parameter is not found");
367       SavedLocals.insert({ PD, it->second });
368
369       auto copyIt = LocalDeclMap.find(VD);
370       assert(copyIt != LocalDeclMap.end() && "parameter copy is not found");
371       it->second = copyIt->getSecond();
372     }
373
374     ~ParamReferenceReplacerRAII() {
375       for (auto&& SavedLocal : SavedLocals) {
376         LocalDeclMap.insert({SavedLocal.first, SavedLocal.second});
377       }
378     }
379   };
380 }
381
382 // For WinEH exception representation backend needs to know what funclet coro.end
383 // belongs to. That information is passed in a funclet bundle.
384 static SmallVector<llvm::OperandBundleDef, 1>
385 getBundlesForCoroEnd(CodeGenFunction &CGF) {
386   SmallVector<llvm::OperandBundleDef, 1> BundleList;
387
388   if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
389     BundleList.emplace_back("funclet", EHPad);
390
391   return BundleList;
392 }
393
394 namespace {
395 // We will insert coro.end to cut any of the destructors for objects that
396 // do not need to be destroyed once the coroutine is resumed.
397 // See llvm/docs/Coroutines.rst for more details about coro.end.
398 struct CallCoroEnd final : public EHScopeStack::Cleanup {
399   void Emit(CodeGenFunction &CGF, Flags flags) override {
400     auto &CGM = CGF.CGM;
401     auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
402     llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
403     // See if we have a funclet bundle to associate coro.end with. (WinEH)
404     auto Bundles = getBundlesForCoroEnd(CGF);
405     auto *CoroEnd = CGF.Builder.CreateCall(
406         CoroEndFn, {NullPtr, CGF.Builder.getTrue()}, Bundles);
407     if (Bundles.empty()) {
408       // Otherwise, (landingpad model), create a conditional branch that leads
409       // either to a cleanup block or a block with EH resume instruction.
410       auto *ResumeBB = CGF.getEHResumeBlock(/*cleanup=*/true);
411       auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont");
412       CGF.Builder.CreateCondBr(CoroEnd, ResumeBB, CleanupContBB);
413       CGF.EmitBlock(CleanupContBB);
414     }
415   }
416 };
417 }
418
419 namespace {
420 // Make sure to call coro.delete on scope exit.
421 struct CallCoroDelete final : public EHScopeStack::Cleanup {
422   Stmt *Deallocate;
423
424   // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
425
426   // Note: That deallocation will be emitted twice: once for a normal exit and
427   // once for exceptional exit. This usage is safe because Deallocate does not
428   // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
429   // builds a single call to a deallocation function which is safe to emit
430   // multiple times.
431   void Emit(CodeGenFunction &CGF, Flags) override {
432     // Remember the current point, as we are going to emit deallocation code
433     // first to get to coro.free instruction that is an argument to a delete
434     // call.
435     BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();
436
437     auto *FreeBB = CGF.createBasicBlock("coro.free");
438     CGF.EmitBlock(FreeBB);
439     CGF.EmitStmt(Deallocate);
440
441     auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free");
442     CGF.EmitBlock(AfterFreeBB);
443
444     // We should have captured coro.free from the emission of deallocate.
445     auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;
446     if (!CoroFree) {
447       CGF.CGM.Error(Deallocate->getBeginLoc(),
448                     "Deallocation expressoin does not refer to coro.free");
449       return;
450     }
451
452     // Get back to the block we were originally and move coro.free there.
453     auto *InsertPt = SaveInsertBlock->getTerminator();
454     CoroFree->moveBefore(InsertPt);
455     CGF.Builder.SetInsertPoint(InsertPt);
456
457     // Add if (auto *mem = coro.free) Deallocate;
458     auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
459     auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr);
460     CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB);
461
462     // No longer need old terminator.
463     InsertPt->eraseFromParent();
464     CGF.Builder.SetInsertPoint(AfterFreeBB);
465   }
466   explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}
467 };
468 }
469
470 namespace {
471 struct GetReturnObjectManager {
472   CodeGenFunction &CGF;
473   CGBuilderTy &Builder;
474   const CoroutineBodyStmt &S;
475
476   Address GroActiveFlag;
477   CodeGenFunction::AutoVarEmission GroEmission;
478
479   GetReturnObjectManager(CodeGenFunction &CGF, const CoroutineBodyStmt &S)
480       : CGF(CGF), Builder(CGF.Builder), S(S), GroActiveFlag(Address::invalid()),
481         GroEmission(CodeGenFunction::AutoVarEmission::invalid()) {}
482
483   // The gro variable has to outlive coroutine frame and coroutine promise, but,
484   // it can only be initialized after coroutine promise was created, thus, we
485   // split its emission in two parts. EmitGroAlloca emits an alloca and sets up
486   // cleanups. Later when coroutine promise is available we initialize the gro
487   // and sets the flag that the cleanup is now active.
488
489   void EmitGroAlloca() {
490     auto *GroDeclStmt = dyn_cast<DeclStmt>(S.getResultDecl());
491     if (!GroDeclStmt) {
492       // If get_return_object returns void, no need to do an alloca.
493       return;
494     }
495
496     auto *GroVarDecl = cast<VarDecl>(GroDeclStmt->getSingleDecl());
497
498     // Set GRO flag that it is not initialized yet
499     GroActiveFlag =
500       CGF.CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(), "gro.active");
501     Builder.CreateStore(Builder.getFalse(), GroActiveFlag);
502
503     GroEmission = CGF.EmitAutoVarAlloca(*GroVarDecl);
504
505     // Remember the top of EHStack before emitting the cleanup.
506     auto old_top = CGF.EHStack.stable_begin();
507     CGF.EmitAutoVarCleanups(GroEmission);
508     auto top = CGF.EHStack.stable_begin();
509
510     // Make the cleanup conditional on gro.active
511     for (auto b = CGF.EHStack.find(top), e = CGF.EHStack.find(old_top);
512       b != e; b++) {
513       if (auto *Cleanup = dyn_cast<EHCleanupScope>(&*b)) {
514         assert(!Cleanup->hasActiveFlag() && "cleanup already has active flag?");
515         Cleanup->setActiveFlag(GroActiveFlag);
516         Cleanup->setTestFlagInEHCleanup();
517         Cleanup->setTestFlagInNormalCleanup();
518       }
519     }
520   }
521
522   void EmitGroInit() {
523     if (!GroActiveFlag.isValid()) {
524       // No Gro variable was allocated. Simply emit the call to
525       // get_return_object.
526       CGF.EmitStmt(S.getResultDecl());
527       return;
528     }
529
530     CGF.EmitAutoVarInit(GroEmission);
531     Builder.CreateStore(Builder.getTrue(), GroActiveFlag);
532   }
533 };
534 }
535
536 static void emitBodyAndFallthrough(CodeGenFunction &CGF,
537                                    const CoroutineBodyStmt &S, Stmt *Body) {
538   CGF.EmitStmt(Body);
539   const bool CanFallthrough = CGF.Builder.GetInsertBlock();
540   if (CanFallthrough)
541     if (Stmt *OnFallthrough = S.getFallthroughHandler())
542       CGF.EmitStmt(OnFallthrough);
543 }
544
545 void CodeGenFunction::EmitCoroutineBody(const CoroutineBodyStmt &S) {
546   auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
547   auto &TI = CGM.getContext().getTargetInfo();
548   unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
549
550   auto *EntryBB = Builder.GetInsertBlock();
551   auto *AllocBB = createBasicBlock("coro.alloc");
552   auto *InitBB = createBasicBlock("coro.init");
553   auto *FinalBB = createBasicBlock("coro.final");
554   auto *RetBB = createBasicBlock("coro.ret");
555
556   auto *CoroId = Builder.CreateCall(
557       CGM.getIntrinsic(llvm::Intrinsic::coro_id),
558       {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
559   createCoroData(*this, CurCoro, CoroId);
560   CurCoro.Data->SuspendBB = RetBB;
561
562   // Backend is allowed to elide memory allocations, to help it, emit
563   // auto mem = coro.alloc() ? 0 : ... allocation code ...;
564   auto *CoroAlloc = Builder.CreateCall(
565       CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});
566
567   Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);
568
569   EmitBlock(AllocBB);
570   auto *AllocateCall = EmitScalarExpr(S.getAllocate());
571   auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
572
573   // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
574   if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
575     auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");
576
577     // See if allocation was successful.
578     auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);
579     auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);
580     Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);
581
582     // If not, return OnAllocFailure object.
583     EmitBlock(RetOnFailureBB);
584     EmitStmt(RetOnAllocFailure);
585   }
586   else {
587     Builder.CreateBr(InitBB);
588   }
589
590   EmitBlock(InitBB);
591
592   // Pass the result of the allocation to coro.begin.
593   auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);
594   Phi->addIncoming(NullPtr, EntryBB);
595   Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);
596   auto *CoroBegin = Builder.CreateCall(
597       CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});
598   CurCoro.Data->CoroBegin = CoroBegin;
599
600   GetReturnObjectManager GroManager(*this, S);
601   GroManager.EmitGroAlloca();
602
603   CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
604   {
605     ParamReferenceReplacerRAII ParamReplacer(LocalDeclMap);
606     CodeGenFunction::RunCleanupsScope ResumeScope(*this);
607     EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
608
609     // Create parameter copies. We do it before creating a promise, since an
610     // evolution of coroutine TS may allow promise constructor to observe
611     // parameter copies.
612     for (auto *PM : S.getParamMoves()) {
613       EmitStmt(PM);
614       ParamReplacer.addCopy(cast<DeclStmt>(PM));
615       // TODO: if(CoroParam(...)) need to surround ctor and dtor
616       // for the copy, so that llvm can elide it if the copy is
617       // not needed.
618     }
619
620     EmitStmt(S.getPromiseDeclStmt());
621
622     Address PromiseAddr = GetAddrOfLocalVar(S.getPromiseDecl());
623     auto *PromiseAddrVoidPtr =
624         new llvm::BitCastInst(PromiseAddr.getPointer(), VoidPtrTy, "", CoroId);
625     // Update CoroId to refer to the promise. We could not do it earlier because
626     // promise local variable was not emitted yet.
627     CoroId->setArgOperand(1, PromiseAddrVoidPtr);
628
629     // Now we have the promise, initialize the GRO
630     GroManager.EmitGroInit();
631
632     EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
633
634     CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
635     CurCoro.Data->ExceptionHandler = S.getExceptionHandler();
636     EmitStmt(S.getInitSuspendStmt());
637     CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
638
639     CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
640
641     if (CurCoro.Data->ExceptionHandler) {
642       // If we generated IR to record whether an exception was thrown from
643       // 'await_resume', then use that IR to determine whether the coroutine
644       // body should be skipped.
645       // If we didn't generate the IR (perhaps because 'await_resume' was marked
646       // as 'noexcept'), then we skip this check.
647       BasicBlock *ContBB = nullptr;
648       if (CurCoro.Data->ResumeEHVar) {
649         BasicBlock *BodyBB = createBasicBlock("coro.resumed.body");
650         ContBB = createBasicBlock("coro.resumed.cont");
651         Value *SkipBody = Builder.CreateFlagLoad(CurCoro.Data->ResumeEHVar,
652                                                  "coro.resumed.eh");
653         Builder.CreateCondBr(SkipBody, ContBB, BodyBB);
654         EmitBlock(BodyBB);
655       }
656
657       auto Loc = S.getBeginLoc();
658       CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr,
659                          CurCoro.Data->ExceptionHandler);
660       auto *TryStmt =
661           CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);
662
663       EnterCXXTryStmt(*TryStmt);
664       emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());
665       ExitCXXTryStmt(*TryStmt);
666
667       if (ContBB)
668         EmitBlock(ContBB);
669     }
670     else {
671       emitBodyAndFallthrough(*this, S, S.getBody());
672     }
673
674     // See if we need to generate final suspend.
675     const bool CanFallthrough = Builder.GetInsertBlock();
676     const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
677     if (CanFallthrough || HasCoreturns) {
678       EmitBlock(FinalBB);
679       CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
680       EmitStmt(S.getFinalSuspendStmt());
681     } else {
682       // We don't need FinalBB. Emit it to make sure the block is deleted.
683       EmitBlock(FinalBB, /*IsFinished=*/true);
684     }
685   }
686
687   EmitBlock(RetBB);
688   // Emit coro.end before getReturnStmt (and parameter destructors), since
689   // resume and destroy parts of the coroutine should not include them.
690   llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
691   Builder.CreateCall(CoroEnd, {NullPtr, Builder.getFalse()});
692
693   if (Stmt *Ret = S.getReturnStmt())
694     EmitStmt(Ret);
695 }
696
697 // Emit coroutine intrinsic and patch up arguments of the token type.
698 RValue CodeGenFunction::EmitCoroutineIntrinsic(const CallExpr *E,
699                                                unsigned int IID) {
700   SmallVector<llvm::Value *, 8> Args;
701   switch (IID) {
702   default:
703     break;
704   // The coro.frame builtin is replaced with an SSA value of the coro.begin
705   // intrinsic.
706   case llvm::Intrinsic::coro_frame: {
707     if (CurCoro.Data && CurCoro.Data->CoroBegin) {
708       return RValue::get(CurCoro.Data->CoroBegin);
709     }
710     CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_begin "
711                                 "has been used earlier in this function");
712     auto NullPtr = llvm::ConstantPointerNull::get(Builder.getInt8PtrTy());
713     return RValue::get(NullPtr);
714   }
715   // The following three intrinsics take a token parameter referring to a token
716   // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
717   // builtins, we patch it up here.
718   case llvm::Intrinsic::coro_alloc:
719   case llvm::Intrinsic::coro_begin:
720   case llvm::Intrinsic::coro_free: {
721     if (CurCoro.Data && CurCoro.Data->CoroId) {
722       Args.push_back(CurCoro.Data->CoroId);
723       break;
724     }
725     CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
726                                 " been used earlier in this function");
727     // Fallthrough to the next case to add TokenNone as the first argument.
728     LLVM_FALLTHROUGH;
729   }
730   // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
731   // argument.
732   case llvm::Intrinsic::coro_suspend:
733     Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
734     break;
735   }
736   for (auto &Arg : E->arguments())
737     Args.push_back(EmitScalarExpr(Arg));
738
739   llvm::Value *F = CGM.getIntrinsic(IID);
740   llvm::CallInst *Call = Builder.CreateCall(F, Args);
741
742   // Note: The following code is to enable to emit coro.id and coro.begin by
743   // hand to experiment with coroutines in C.
744   // If we see @llvm.coro.id remember it in the CoroData. We will update
745   // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
746   if (IID == llvm::Intrinsic::coro_id) {
747     createCoroData(*this, CurCoro, Call, E);
748   }
749   else if (IID == llvm::Intrinsic::coro_begin) {
750     if (CurCoro.Data)
751       CurCoro.Data->CoroBegin = Call;
752   }
753   else if (IID == llvm::Intrinsic::coro_free) {
754     // Remember the last coro_free as we need it to build the conditional
755     // deletion of the coroutine frame.
756     if (CurCoro.Data)
757       CurCoro.Data->LastCoroFree = Call;
758   }
759   return RValue::get(Call);
760 }