clang 24.0.0git
CGCoroutine.cpp
Go to the documentation of this file.
1//===----- CGCoroutine.cpp - Emit LLVM Code for C++ coroutines ------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This contains code dealing with C++ code generation of coroutines.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGCleanup.h"
14#include "CGDebugInfo.h"
15#include "CodeGenFunction.h"
16#include "clang/AST/StmtCXX.h"
18#include "llvm/ADT/ScopeExit.h"
19
20using namespace clang;
21using namespace CodeGen;
22
23using llvm::Value;
24using llvm::BasicBlock;
25
26namespace {
27enum class AwaitKind { Init, Normal, Yield, Final };
28static constexpr llvm::StringLiteral AwaitKindStr[] = {"init", "await", "yield",
29 "final"};
30}
31
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 // A branch to this block after final.cleanup or final.ready
47 llvm::BasicBlock *FinalExit = nullptr;
48
49 // The promise type's 'unhandled_exception' handler, if it defines one.
51
52 // A temporary i1 alloca that stores whether 'await_resume' threw an
53 // exception. If it did, 'true' is stored in this variable, and the coroutine
54 // body must be skipped. If the promise type does not define an exception
55 // handler, this is null.
56 llvm::Value *ResumeEHVar = nullptr;
57
58 // Stores the jump destination just before the coroutine memory is freed.
59 // This is the destination that every suspend point jumps to for the cleanup
60 // branch.
62
63 // Stores the jump destination just before the final suspend. The co_return
64 // statements jumps to this point after calling return_xxx promise member.
66
67 // Stores the llvm.coro.id emitted in the function so that we can supply it
68 // as the first argument to coro.begin, coro.alloc and coro.free intrinsics.
69 // Note: llvm.coro.id returns a token that cannot be directly expressed in a
70 // builtin.
71 llvm::CallInst *CoroId = nullptr;
72
73 // Stores the llvm.coro.begin emitted in the function so that we can replace
74 // all coro.frame intrinsics with direct SSA value of coro.begin that returns
75 // the address of the coroutine frame of the current coroutine.
76 llvm::CallInst *CoroBegin = nullptr;
77
78 // Stores the last emitted coro.free for the deallocate expressions, we use it
79 // to wrap dealloc code with if(auto mem = coro.free) dealloc(mem).
80 llvm::CallInst *LastCoroFree = nullptr;
81
82 // If coro.id came from the builtin, remember the expression to give better
83 // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by
84 // EmitCoroutineBody.
85 CallExpr const *CoroIdExpr = nullptr;
86};
87
88// Defining these here allows to keep CGCoroData private to this file.
91
94 llvm::CallInst *CoroId,
95 CallExpr const *CoroIdExpr = nullptr) {
96 if (CurCoro.Data) {
97 if (CurCoro.Data->CoroIdExpr)
98 CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
99 "only one __builtin_coro_id can be used in a function");
100 else if (CoroIdExpr)
101 CGF.CGM.Error(CoroIdExpr->getBeginLoc(),
102 "__builtin_coro_id shall not be used in a C++ coroutine");
103 else
104 llvm_unreachable("EmitCoroutineBodyStatement called twice?");
105
106 return;
107 }
108
109 CurCoro.Data = std::make_unique<CGCoroData>();
110 CurCoro.Data->CoroId = CoroId;
111 CurCoro.Data->CoroIdExpr = CoroIdExpr;
112}
113
114// Synthesize a pretty name for a suspend point.
115static SmallString<32> buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind) {
116 unsigned No = 0;
117 switch (Kind) {
118 case AwaitKind::Init:
119 case AwaitKind::Final:
120 break;
121 case AwaitKind::Normal:
122 No = ++Coro.AwaitNum;
123 break;
124 case AwaitKind::Yield:
125 No = ++Coro.YieldNum;
126 break;
127 }
128 SmallString<32> Prefix(AwaitKindStr[static_cast<unsigned>(Kind)]);
129 if (No > 1) {
130 Twine(No).toVector(Prefix);
131 }
132 return Prefix;
133}
134
135// Check if function can throw based on prototype noexcept, also works for
136// destructors which are implicitly noexcept but can be marked noexcept(false).
137static bool FunctionCanThrow(const FunctionDecl *D) {
138 const auto *Proto = D->getType()->getAs<FunctionProtoType>();
139 if (!Proto) {
140 // Function proto is not found, we conservatively assume throwing.
141 return true;
142 }
143 return !isNoexceptExceptionSpec(Proto->getExceptionSpecType()) ||
144 Proto->canThrow() != CT_Cannot;
145}
146
147static bool StmtCanThrow(const Stmt *S) {
148 if (const auto *CE = dyn_cast<CallExpr>(S)) {
149 const auto *Callee = CE->getDirectCallee();
150 if (!Callee)
151 // We don't have direct callee. Conservatively assume throwing.
152 return true;
153
154 if (FunctionCanThrow(Callee))
155 return true;
156
157 // Fall through to visit the children.
158 }
159
160 if (const auto *TE = dyn_cast<CXXBindTemporaryExpr>(S)) {
161 // Special handling of CXXBindTemporaryExpr here as calling of Dtor of the
162 // temporary is not part of `children()` as covered in the fall through.
163 // We need to mark entire statement as throwing if the destructor of the
164 // temporary throws.
165 const auto *Dtor = TE->getTemporary()->getDestructor();
166 if (FunctionCanThrow(Dtor))
167 return true;
168
169 // Fall through to visit the children.
170 }
171
172 for (const auto *child : S->children())
173 if (StmtCanThrow(child))
174 return true;
175
176 return false;
177}
178
179// Emit suspend expression which roughly looks like:
180//
181// auto && x = CommonExpr();
182// if (!x.await_ready()) {
183// llvm_coro_save();
184// llvm_coro_await_suspend(&x, frame, wrapper) (*) (**)
185// llvm_coro_suspend(); (***)
186// }
187// x.await_resume();
188//
189// where the result of the entire expression is the result of x.await_resume()
190//
191// (*) llvm_coro_await_suspend_{void, bool, handle} is lowered to
192// wrapper(&x, frame) when it's certain not to interfere with
193// coroutine transform. await_suspend expression is
194// asynchronous to the coroutine body and not all analyses
195// and transformations can handle it correctly at the moment.
196//
197// Wrapper function encapsulates x.await_suspend(...) call and looks like:
198//
199// auto __await_suspend_wrapper(auto& awaiter, void* frame) {
200// std::coroutine_handle<> handle(frame);
201// return awaiter.await_suspend(handle);
202// }
203//
204// (**) If x.await_suspend return type is bool, it allows to veto a suspend:
205// if (x.await_suspend(...))
206// llvm_coro_suspend();
207//
208// (***) llvm_coro_suspend() encodes three possible continuations as
209// a switch instruction:
210//
211// %where-to = call i8 @llvm.coro.suspend(...)
212// switch i8 %where-to, label %coro.ret [ ; jump to epilogue to suspend
213// i8 0, label %yield.ready ; go here when resumed
214// i8 1, label %yield.cleanup ; go here when destroyed
215// ]
216//
217// See llvm's docs/Coroutines.md for more details.
218//
219namespace {
220 struct LValueOrRValue {
221 LValue LV;
222 RValue RV;
223 };
224}
225static LValueOrRValue emitSuspendExpression(CodeGenFunction &CGF, CGCoroData &Coro,
226 CoroutineSuspendExpr const &S,
227 AwaitKind Kind, AggValueSlot aggSlot,
228 bool ignoreResult, bool forLValue) {
229 auto *E = S.getCommonExpr();
230
231 auto CommonBinder =
233 llvm::scope_exit UnbindCommonOnExit([&] { CommonBinder.unbind(CGF); });
234
235 auto Prefix = buildSuspendPrefixStr(Coro, Kind);
236 BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
237 BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
238 BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));
239
240 // If expression is ready, no need to suspend.
241 CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);
242
243 // Otherwise, emit suspend logic.
244 CGF.EmitBlock(SuspendBlock);
245
246 auto &Builder = CGF.Builder;
247 llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
248 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
249 auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
250
251 auto SuspendWrapper = CodeGenFunction(CGF.CGM).generateAwaitSuspendWrapper(
252 CGF.CurFn->getName(), Prefix, S);
253
254 CGF.CurCoro.InSuspendBlock = true;
255
256 assert(CGF.CurCoro.Data && CGF.CurCoro.Data->CoroBegin &&
257 "expected to be called in coroutine context");
258
259 SmallVector<llvm::Value *, 3> SuspendIntrinsicCallArgs;
260 SuspendIntrinsicCallArgs.push_back(
262
263 SuspendIntrinsicCallArgs.push_back(CGF.CurCoro.Data->CoroBegin);
264 SuspendIntrinsicCallArgs.push_back(SuspendWrapper);
265
266 const auto SuspendReturnType = S.getSuspendReturnType();
267 llvm::Intrinsic::ID AwaitSuspendIID;
268
269 switch (SuspendReturnType) {
271 AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_void;
272 break;
274 AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_bool;
275 break;
277 AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_handle;
278 break;
279 }
280
281 llvm::Function *AwaitSuspendIntrinsic = CGF.CGM.getIntrinsic(AwaitSuspendIID);
282
283 // SuspendHandle might throw since it also resumes the returned handle.
284 const bool AwaitSuspendCanThrow =
285 SuspendReturnType ==
288
289 llvm::CallBase *SuspendRet = nullptr;
290 // FIXME: add call attributes?
291 if (AwaitSuspendCanThrow)
292 SuspendRet =
293 CGF.EmitCallOrInvoke(AwaitSuspendIntrinsic, SuspendIntrinsicCallArgs);
294 else
295 SuspendRet = CGF.EmitNounwindRuntimeCall(AwaitSuspendIntrinsic,
296 SuspendIntrinsicCallArgs);
297
298 assert(SuspendRet);
299 CGF.CurCoro.InSuspendBlock = false;
300
301 switch (SuspendReturnType) {
303 assert(SuspendRet->getType()->isVoidTy());
304 break;
306 assert(SuspendRet->getType()->isIntegerTy());
307
308 // Veto suspension if requested by bool returning await_suspend.
309 BasicBlock *RealSuspendBlock =
310 CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
311 CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
312 CGF.EmitBlock(RealSuspendBlock);
313 break;
314 }
316 assert(SuspendRet->getType()->isVoidTy());
317 break;
318 }
319 }
320
321 // Emit the suspend point.
322 const bool IsFinalSuspend = (Kind == AwaitKind::Final);
323 llvm::Function *CoroSuspend =
324 CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);
325 auto *SuspendResult = Builder.CreateCall(
326 CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});
327
328 // Create a switch capturing three possible continuations.
329 auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);
330 Switch->addCase(Builder.getInt8(0), ReadyBlock);
331 Switch->addCase(Builder.getInt8(1), CleanupBlock);
332
333 // Emit cleanup for this suspend point.
334 CGF.EmitBlock(CleanupBlock);
336 if (IsFinalSuspend)
337 Coro.FinalExit = CleanupBlock->getSingleSuccessor();
338
339 // Emit await_resume expression.
340 CGF.EmitBlock(ReadyBlock);
341
342 // Exception handling requires additional IR. If the 'await_resume' function
343 // is marked as 'noexcept', we avoid generating this additional IR.
344 CXXTryStmt *TryStmt = nullptr;
345 if (Coro.ExceptionHandler && Kind == AwaitKind::Init &&
347 Coro.ResumeEHVar =
348 CGF.CreateTempAlloca(Builder.getInt1Ty(), Prefix + Twine("resume.eh"));
349 Builder.CreateFlagStore(true, Coro.ResumeEHVar);
350
351 auto Loc = S.getResumeExpr()->getExprLoc();
352 auto *Catch = new (CGF.getContext())
353 CXXCatchStmt(Loc, /*exDecl=*/nullptr, Coro.ExceptionHandler);
354 auto *TryBody = CompoundStmt::Create(CGF.getContext(), S.getResumeExpr(),
355 FPOptionsOverride(), Loc, Loc);
356 TryStmt = CXXTryStmt::Create(CGF.getContext(), Loc, TryBody, Catch);
357 CGF.EnterCXXTryStmt(*TryStmt);
358 CGF.EmitStmt(TryBody);
359 // We don't use EmitCXXTryStmt here. We need to store to ResumeEHVar that
360 // doesn't exist in the body.
361 Builder.CreateFlagStore(false, Coro.ResumeEHVar);
362 CGF.ExitCXXTryStmt(*TryStmt);
363 LValueOrRValue Res;
364 // We are not supposed to obtain the value from init suspend await_resume().
365 Res.RV = RValue::getIgnored();
366 return Res;
367 }
368
369 LValueOrRValue Res;
370 if (forLValue)
371 Res.LV = CGF.EmitLValue(S.getResumeExpr());
372 else
373 Res.RV = CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
374
375 return Res;
376}
377
379 AggValueSlot aggSlot,
380 bool ignoreResult) {
381 return emitSuspendExpression(*this, *CurCoro.Data, E,
382 CurCoro.Data->CurrentAwaitKind, aggSlot,
383 ignoreResult, /*forLValue*/false).RV;
384}
386 AggValueSlot aggSlot,
387 bool ignoreResult) {
388 return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,
389 aggSlot, ignoreResult, /*forLValue*/false).RV;
390}
391
393 ++CurCoro.Data->CoreturnCount;
394 const Expr *RV = S.getOperand();
395 if (RV && RV->getType()->isVoidType() && !isa<InitListExpr>(RV)) {
396 // Make sure to evaluate the non initlist expression of a co_return
397 // with a void expression for side effects.
398 RunCleanupsScope cleanupScope(*this);
399 EmitIgnoredExpr(RV);
400 }
402 EmitBranchThroughCleanup(CurCoro.Data->FinalJD);
403}
404
405
406#ifndef NDEBUG
408 const CoroutineSuspendExpr *E) {
409 const auto *RE = E->getResumeExpr();
410 // Is it possible for RE to be a CXXBindTemporaryExpr wrapping
411 // a MemberCallExpr?
412 assert(isa<CallExpr>(RE) && "unexpected suspend expression type");
413 return cast<CallExpr>(RE)->getCallReturnType(Ctx);
414}
415#endif
416
417llvm::Function *
419 Twine const &SuspendPointName,
420 CoroutineSuspendExpr const &S) {
421 std::string FuncName =
422 (CoroName + ".__await_suspend_wrapper__" + SuspendPointName).str();
423
425
426 auto *AwaiterDecl =
428 auto *FrameDecl =
430 QualType ReturnTy = S.getSuspendExpr()->getType();
431
432 FunctionArgList args{AwaiterDecl, FrameDecl};
433 const CGFunctionInfo &FI =
434 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
435
436 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
437
438 llvm::Function *Fn = llvm::Function::Create(
439 LTy, llvm::GlobalValue::InternalLinkage, FuncName, &CGM.getModule());
440 CGM.SetInternalFunctionAttributes(GlobalDecl(), Fn, FI);
441
442 Fn->addParamAttr(0, llvm::Attribute::AttrKind::NonNull);
443 Fn->addParamAttr(0, llvm::Attribute::AttrKind::NoUndef);
444
445 Fn->addParamAttr(1, llvm::Attribute::AttrKind::NoUndef);
446
447 Fn->setMustProgress();
448 Fn->removeFnAttr(llvm::Attribute::AttrKind::NoInline);
449 Fn->addFnAttr(llvm::Attribute::AttrKind::AlwaysInline);
450 Fn->addFnAttr("sample-profile-suffix-elision-policy", "selected");
451
452 StartFunction(GlobalDecl(), ReturnTy, Fn, FI, args);
453
454 // FIXME: add TBAA metadata to the loads
455 llvm::Value *AwaiterPtr = Builder.CreateLoad(GetAddrOfLocalVar(AwaiterDecl));
456 auto AwaiterLValue =
457 MakeNaturalAlignAddrLValue(AwaiterPtr, AwaiterDecl->getType());
458
459 CurAwaitSuspendWrapper.FramePtr =
460 Builder.CreateLoad(GetAddrOfLocalVar(FrameDecl));
461
463 *this, S.getOpaqueValue(), AwaiterLValue);
464
465 auto *SuspendRet = EmitScalarExpr(S.getSuspendExpr());
466
467 llvm::scope_exit UnbindCommonOnExit([&] { AwaiterBinder.unbind(*this); });
468 if (SuspendRet != nullptr) {
469 Fn->addRetAttr(llvm::Attribute::AttrKind::NoUndef);
470 Builder.CreateStore(SuspendRet, ReturnValue);
471 }
472
473 CurAwaitSuspendWrapper.FramePtr = nullptr;
475 return Fn;
476}
477
478LValue
480 assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
481 "Can't have a scalar return unless the return type is a "
482 "reference type!");
483 return emitSuspendExpression(*this, *CurCoro.Data, *E,
484 CurCoro.Data->CurrentAwaitKind, AggValueSlot::ignored(),
485 /*ignoreResult*/false, /*forLValue*/true).LV;
486}
487
488LValue
490 assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
491 "Can't have a scalar return unless the return type is a "
492 "reference type!");
493 return emitSuspendExpression(*this, *CurCoro.Data, *E,
494 AwaitKind::Yield, AggValueSlot::ignored(),
495 /*ignoreResult*/false, /*forLValue*/true).LV;
496}
497
498// Hunts for the parameter reference in the parameter copy/move declaration.
499namespace {
500struct GetParamRef : public StmtVisitor<GetParamRef> {
501public:
502 DeclRefExpr *Expr = nullptr;
503 GetParamRef() {}
504 void VisitDeclRefExpr(DeclRefExpr *E) {
505 assert(Expr == nullptr && "multilple declref in param move");
506 Expr = E;
507 }
508 void VisitStmt(Stmt *S) {
509 for (auto *C : S->children()) {
510 if (C)
511 Visit(C);
512 }
513 }
514};
515}
516
517// This class replaces references to parameters to their copies by changing
518// the addresses in CGF.LocalDeclMap and restoring back the original values in
519// its destructor.
520
521namespace {
522 struct ParamReferenceReplacerRAII {
523 CodeGenFunction::DeclMapTy SavedLocals;
524 CodeGenFunction::DeclMapTy& LocalDeclMap;
525
526 ParamReferenceReplacerRAII(CodeGenFunction::DeclMapTy &LocalDeclMap)
527 : LocalDeclMap(LocalDeclMap) {}
528
529 void addCopy(DeclStmt const *PM) {
530 // Figure out what param it refers to.
531
532 assert(PM->isSingleDecl());
533 VarDecl const*VD = static_cast<VarDecl const*>(PM->getSingleDecl());
534 Expr const *InitExpr = VD->getInit();
535 GetParamRef Visitor;
536 Visitor.Visit(const_cast<Expr*>(InitExpr));
537 assert(Visitor.Expr);
538 DeclRefExpr *DREOrig = Visitor.Expr;
539 auto *PD = DREOrig->getDecl();
540
541 auto it = LocalDeclMap.find(PD);
542 assert(it != LocalDeclMap.end() && "parameter is not found");
543 SavedLocals.insert({ PD, it->second });
544
545 auto copyIt = LocalDeclMap.find(VD);
546 assert(copyIt != LocalDeclMap.end() && "parameter copy is not found");
547 it->second = copyIt->getSecond();
548 }
549
550 ~ParamReferenceReplacerRAII() {
551 for (auto&& SavedLocal : SavedLocals) {
552 LocalDeclMap.insert({SavedLocal.first, SavedLocal.second});
553 }
554 }
555 };
556}
557
558// For WinEH exception representation backend needs to know what funclet coro.end
559// belongs to. That information is passed in a funclet bundle.
560static SmallVector<llvm::OperandBundleDef, 1>
563
564 if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
565 BundleList.emplace_back("funclet", EHPad);
566
567 return BundleList;
568}
569
570namespace {
571// We will insert coro.end to cut any of the destructors for objects that
572// do not need to be destroyed once the coroutine is resumed.
573// See llvm/docs/Coroutines.md for more details about coro.end.
574struct CallCoroEnd final : public EHScopeStack::Cleanup {
575 void Emit(CodeGenFunction &CGF, Flags flags) override {
576 auto &CGM = CGF.CGM;
577 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
578 llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
579 // See if we have a funclet bundle to associate coro.end with. (WinEH)
580 auto Bundles = getBundlesForCoroEnd(CGF);
581 CGF.Builder.CreateCall(
582 CoroEndFn,
583 {NullPtr, CGF.Builder.getTrue(),
584 llvm::ConstantTokenNone::get(CoroEndFn->getContext())},
585 Bundles);
586 if (Bundles.empty()) {
587 // Otherwise, (landingpad model), create a conditional branch that leads
588 // either to a cleanup block or a block with EH resume instruction.
589 auto *ResumeBB = CGF.getEHResumeBlock(/*isCleanup=*/true);
590 auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont");
591 auto *CoroIsInRampFn = CGM.getIntrinsic(llvm::Intrinsic::coro_is_in_ramp);
592 auto *CoroIsInRamp = CGF.Builder.CreateCall(CoroIsInRampFn);
593 CGF.Builder.CreateCondBr(CoroIsInRamp, CleanupContBB, ResumeBB);
594 CGF.EmitBlock(CleanupContBB);
595 }
596 }
597};
598}
599
600namespace {
601// Make sure to call coro.delete on scope exit.
602struct CallCoroDelete final : public EHScopeStack::Cleanup {
603 Stmt *Deallocate;
604
605 // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
606
607 // Note: That deallocation will be emitted twice: once for a normal exit and
608 // once for exceptional exit. This usage is safe because Deallocate does not
609 // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
610 // builds a single call to a deallocation function which is safe to emit
611 // multiple times.
612 void Emit(CodeGenFunction &CGF, Flags) override {
613 // Remember the current point, as we are going to emit deallocation code
614 // first to get to coro.free instruction that is an argument to a delete
615 // call.
616 BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();
617
618 auto *FreeBB = CGF.createBasicBlock("coro.free");
619 CGF.EmitBlock(FreeBB);
620 CGF.EmitStmt(Deallocate);
621
622 auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free");
623 CGF.EmitBlock(AfterFreeBB);
624
625 // We should have captured coro.free from the emission of deallocate.
626 auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;
627 if (!CoroFree) {
628 CGF.CGM.Error(Deallocate->getBeginLoc(),
629 "Deallocation expressoin does not refer to coro.free");
630 return;
631 }
632
633 // Get back to the block we were originally and move coro.free there.
634 auto *InsertPt = SaveInsertBlock->getTerminator();
635 CoroFree->moveBefore(InsertPt->getIterator());
636 CGF.Builder.SetInsertPoint(InsertPt);
637
638 // Add if (auto *mem = coro.free) Deallocate;
639 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
640 auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr);
641 CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB);
642
643 // No longer need old terminator.
644 InsertPt->eraseFromParent();
645 CGF.Builder.SetInsertPoint(AfterFreeBB);
646
647 auto *CoroDeadFn = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_dead);
648 CGF.Builder.CreateCall(CoroDeadFn, {CGF.CurCoro.Data->CoroBegin});
649 }
650 explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}
651};
652}
653
654namespace {
655struct GetReturnObjectManager {
656 CodeGenFunction &CGF;
657 CGBuilderTy &Builder;
658 const CoroutineBodyStmt &S;
659 // When true, performs RVO for the return object.
660 bool DirectEmit = false;
661
662 Address GroActiveFlag;
663 CodeGenFunction::AutoVarEmission GroEmission;
664 std::unique_ptr<CodeGenFunction::RunCleanupsScope> GroScope;
665
666 GetReturnObjectManager(CodeGenFunction &CGF, const CoroutineBodyStmt &S)
667 : CGF(CGF), Builder(CGF.Builder), S(S), GroActiveFlag(Address::invalid()),
668 GroEmission(CodeGenFunction::AutoVarEmission::invalid()) {
669 // The call to get_­return_­object is sequenced before the call to
670 // initial_­suspend and is invoked at most once, but there are caveats
671 // regarding on whether the prvalue result object may be initialized
672 // directly/eager or delayed, depending on the types involved.
673 //
674 // More info at https://github.com/cplusplus/papers/issues/1414
675 //
676 // The general cases:
677 // 1. Same type of get_return_object and coroutine return type (direct
678 // emission):
679 // - Constructed in the return slot.
680 // 2. Different types (delayed emission):
681 // - Constructed temporary object prior to initial suspend initialized with
682 // a call to get_return_object()
683 // - When coroutine needs to to return to the caller and needs to construct
684 // return value for the coroutine it is initialized with expiring value of
685 // the temporary obtained above.
686 //
687 // Direct emission for void returning coroutines or GROs.
688 DirectEmit = [&]() {
689 auto *RVI = S.getReturnValueInit();
690 assert(RVI && "expected RVI");
691 auto GroType = RVI->getType();
692 return CGF.getContext().hasSameType(GroType, CGF.FnRetTy);
693 }();
694 }
695
696 // The gro variable has to outlive coroutine frame and coroutine promise, but,
697 // it can only be initialized after coroutine promise was created. Thus,
698 // EmitGroActive emits a flag and sets it to false. Later when coroutine
699 // promise is available we initialize the gro and set the flag indicating that
700 // the cleanup is now active.
701 void EmitGroActive() {
702 if (DirectEmit)
703 return;
704
705 auto *GroDeclStmt = dyn_cast_or_null<DeclStmt>(S.getResultDecl());
706 if (!GroDeclStmt) {
707 // If get_return_object returns void, no need to do an alloca.
708 return;
709 }
710
711 // Set GRO flag that it is not initialized yet
712 GroActiveFlag = CGF.CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(),
713 "gro.active");
714 Builder.CreateStore(Builder.getFalse(), GroActiveFlag);
715 }
716
717 void EmitGroAlloca() {
718 if (DirectEmit)
719 return;
720
721 auto *GroDeclStmt = dyn_cast_or_null<DeclStmt>(S.getResultDecl());
722 if (!GroDeclStmt) {
723 // If get_return_object returns void, no need to do an alloca.
724 return;
725 }
726
727 auto *GroVarDecl = cast<VarDecl>(GroDeclStmt->getSingleDecl());
728
729 GroEmission = CGF.EmitAutoVarAlloca(*GroVarDecl);
730
731 if (!GroVarDecl->isNRVOVariable()) {
732 // NRVO variables don't have allocas and won't have the same issue.
733 auto *GroAlloca = dyn_cast_or_null<llvm::AllocaInst>(
735 assert(GroAlloca && "expected alloca to be emitted");
736 GroAlloca->setMetadata(llvm::LLVMContext::MD_coro_outside_frame,
737 llvm::MDNode::get(CGF.CGM.getLLVMContext(), {}));
738 }
739
740 GroScope = std::make_unique<CodeGenFunction::RunCleanupsScope>(CGF);
741 // Remember the top of EHStack before emitting the cleanup.
742 auto old_top = CGF.EHStack.stable_begin();
743 CGF.EmitAutoVarCleanups(GroEmission);
744 auto top = CGF.EHStack.stable_begin();
745
746 // Make the cleanup conditional on gro.active
747 for (auto b = CGF.EHStack.find(top), e = CGF.EHStack.find(old_top); b != e;
748 b++) {
749 if (auto *Cleanup = dyn_cast<EHCleanupScope>(&*b)) {
750 assert(!Cleanup->hasActiveFlag() && "cleanup already has active flag?");
751 Cleanup->setActiveFlag(GroActiveFlag);
752 Cleanup->setTestFlagInEHCleanup();
753 Cleanup->setTestFlagInNormalCleanup();
754 }
755 }
756 }
757
758 Address EmitDirectReturnObjectCleanup() {
759 if (!DirectEmit || !CGF.ReturnValue.isValid())
760 return Address::invalid();
761
762 QualType RetTy = CGF.FnRetTy;
764 if (DtorKind == QualType::DK_none || !CGF.needsEHCleanup(DtorKind))
765 return Address::invalid();
766
767 Address ActiveFlag = CGF.CreateTempAlloca(
768 Builder.getInt1Ty(), CharUnits::One(), "coro.result.active");
769 Builder.CreateStore(Builder.getFalse(), ActiveFlag);
770
771 auto OldTop = CGF.EHStack.stable_begin();
772 CGF.pushDestroy(EHCleanup, CGF.ReturnValue, RetTy,
773 CGF.getDestroyer(DtorKind),
774 /*useEHCleanupForArray*/ true);
775 auto Top = CGF.EHStack.stable_begin();
776
777 for (auto B = CGF.EHStack.find(Top), E = CGF.EHStack.find(OldTop); B != E;
778 ++B) {
779 if (auto *Cleanup = dyn_cast<EHCleanupScope>(&*B)) {
780 assert(!Cleanup->hasActiveFlag() && "cleanup already has active flag?");
781 Cleanup->setActiveFlag(ActiveFlag);
782 Cleanup->setTestFlagInEHCleanup();
783 }
784 }
785 return ActiveFlag;
786 }
787
788 void EmitGroInit() {
789 if (DirectEmit) {
790 // ReturnValue should be valid as long as the coroutine's return type
791 // is not void. The assertion could help us to reduce the check later.
792 assert(CGF.ReturnValue.isValid() == (bool)S.getReturnStmt());
793 // Now we have the promise, initialize the GRO.
794 // We need to emit `get_return_object` first. According to:
795 // [dcl.fct.def.coroutine]p7
796 // The call to get_return_­object is sequenced before the call to
797 // initial_suspend and is invoked at most once.
798 //
799 // So we couldn't emit return value when we emit return statment,
800 // otherwise the call to get_return_object wouldn't be in front
801 // of initial_suspend.
802 if (CGF.ReturnValue.isValid()) {
803 auto ActiveFlag = EmitDirectReturnObjectCleanup();
806 /*IsInit*/ true);
807 if (ActiveFlag.isValid())
808 Builder.CreateStore(Builder.getTrue(), ActiveFlag);
809 }
810 return;
811 }
812
813 if (!GroActiveFlag.isValid()) {
814 // No Gro variable was allocated. Simply emit the call to
815 // get_return_object.
816 CGF.EmitStmt(S.getResultDecl());
817 return;
818 }
819
820 CGF.EmitAutoVarInit(GroEmission);
821 Builder.CreateStore(Builder.getTrue(), GroActiveFlag);
822 }
823 // The GRO returns either when it is first suspended or when it completes
824 // without ever being suspended. The EmitGroConv function evaluates these
825 // conditions and perform the conversion if needed.
826 //
827 // Before EmitGroConv():
828 // final.exit:
829 // switch i32 %cleanup.dest, label %destroy [
830 // i32 0, label %after.ready
831 // ]
832 //
833 // after.ready:
834 // ; (empty)
835 //
836 // After EmitGroConv():
837 // final.exit:
838 // switch i32 %cleanup.dest, label %destroy [
839 // i32 0, label %pre.gro.conv
840 // ]
841 //
842 // pre.gro.conv:
843 // %IsFinalExit = phi i1 [ false, %any.suspend ], [ true, %final.exit ]
844 // %InRamp = call i1 @llvm.coro.is_in_ramp()
845 // br i1 %InRamp, label %gro.conv, label %after.gro.conv
846 //
847 // gro.conv:
848 // ; GRO conversion
849 // br label %after.gro.conv
850 //
851 // after.gro.conv:
852 // br i1 %IsFinalExit, label %after.ready, label %coro.ret
853 void EmitGroConv(BasicBlock *RetBB) {
854 auto *AfterReadyBB = Builder.GetInsertBlock();
855 Builder.ClearInsertionPoint();
856
857 auto *PreConvBB = CGF.CurCoro.Data->SuspendBB;
858 CGF.EmitBlock(PreConvBB);
859 // If final.exit exists, redirect it to PreConvBB
860 llvm::PHINode *IsFinalExit = nullptr;
861 if (BasicBlock *FinalExit = CGF.CurCoro.Data->FinalExit) {
862 assert(AfterReadyBB &&
863 AfterReadyBB->getSinglePredecessor() == FinalExit &&
864 "Expect fallthrough from final.exit block");
865 AfterReadyBB->replaceAllUsesWith(PreConvBB);
866 PreConvBB->moveBefore(AfterReadyBB);
867
868 // If true, coroutine completes and should be destroyed after conversion
869 IsFinalExit =
870 Builder.CreatePHI(Builder.getInt1Ty(), llvm::pred_size(PreConvBB));
871 for (auto *Pred : llvm::predecessors(PreConvBB)) {
872 auto *V = (Pred == FinalExit) ? Builder.getTrue() : Builder.getFalse();
873 IsFinalExit->addIncoming(V, Pred);
874 }
875 }
876 auto *InRampFn = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_is_in_ramp);
877 auto *InRamp = Builder.CreateCall(InRampFn, {}, "InRamp");
878 auto *ConvBB = CGF.createBasicBlock("gro.conv");
879 auto *AfterConvBB = CGF.createBasicBlock("after.gro.conv");
880 Builder.CreateCondBr(InRamp, ConvBB, AfterConvBB);
881
882 CGF.EmitBlock(ConvBB);
885 /*IsInit*/ true);
886 GroScope->ForceCleanup();
887 Builder.CreateBr(AfterConvBB);
888
889 CGF.EmitBlock(AfterConvBB);
890 if (IsFinalExit)
891 Builder.CreateCondBr(IsFinalExit, AfterReadyBB, RetBB);
892 else
893 Builder.CreateBr(RetBB);
894 Builder.SetInsertPoint(AfterReadyBB);
895 }
896};
897} // namespace
898
900 const CoroutineBodyStmt &S, Stmt *Body) {
901 CGF.EmitStmt(Body);
902 const bool CanFallthrough = CGF.Builder.GetInsertBlock();
903 if (CanFallthrough)
904 if (Stmt *OnFallthrough = S.getFallthroughHandler())
905 CGF.EmitStmt(OnFallthrough);
906}
907
909 auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getPtrTy());
910 auto &TI = CGM.getContext().getTargetInfo();
911 unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
912
913 auto *EntryBB = Builder.GetInsertBlock();
914 auto *AllocBB = createBasicBlock("coro.alloc");
915 auto *InitBB = createBasicBlock("coro.init");
916 auto *FinalBB = createBasicBlock("coro.final");
917 auto *CleanupBB = createBasicBlock("coro.cleanup");
918 auto *RetBB = createBasicBlock("coro.ret");
919
920 auto *CoroId = Builder.CreateCall(
921 CGM.getIntrinsic(llvm::Intrinsic::coro_id),
922 {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
923 createCoroData(*this, CurCoro, CoroId);
924
925 GetReturnObjectManager GroManager(*this, S);
926 CurCoro.Data->SuspendBB =
927 GroManager.DirectEmit ? RetBB : createBasicBlock("pre.gvo.conv");
928 assert(ShouldEmitLifetimeMarkers &&
929 "Must emit lifetime intrinsics for coroutines");
930
931 // Backend is allowed to elide memory allocations, to help it, emit
932 // auto mem = coro.alloc() ? 0 : ... allocation code ...;
933 auto *CoroAlloc = Builder.CreateCall(
934 CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});
935
936 Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);
937
938 EmitBlock(AllocBB);
939 auto *AllocateCall = EmitScalarExpr(S.getAllocate());
940 auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
941
942 // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
943 if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
944 auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");
945
946 // See if allocation was successful.
947 auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);
948 auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);
949 // Expect the allocation to be successful.
950 emitCondLikelihoodViaExpectIntrinsic(Cond, Stmt::LH_Likely);
951 Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);
952
953 // If not, return OnAllocFailure object.
954 EmitBlock(RetOnFailureBB);
955 EmitStmt(RetOnAllocFailure);
956 }
957 else {
958 Builder.CreateBr(InitBB);
959 }
960
961 EmitBlock(InitBB);
962
963 // Pass the result of the allocation to coro.begin.
964 auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);
965 Phi->addIncoming(NullPtr, EntryBB);
966 Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);
967 auto *CoroBegin = Builder.CreateCall(
968 CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});
969 CurCoro.Data->CoroBegin = CoroBegin;
970 {
972 ParamReferenceReplacerRAII ParamReplacer(LocalDeclMap);
973 CodeGenFunction::RunCleanupsScope ResumeScope(*this);
974 EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
975
976 // Create mapping between parameters and copy-params for coroutine function.
978 assert(
979 (ParamMoves.size() == 0 || (ParamMoves.size() == FnArgs.size())) &&
980 "ParamMoves and FnArgs should be the same size for coroutine function");
981 if (ParamMoves.size() == FnArgs.size() && DI)
982 for (const auto Pair : llvm::zip(FnArgs, ParamMoves))
984 {std::get<0>(Pair), std::get<1>(Pair)});
985
986 // Create parameter copies. We do it before creating a promise, since an
987 // evolution of coroutine TS may allow promise constructor to observe
988 // parameter copies.
989 for (const ParmVarDecl *Parm : FnArgs) {
990 // If the original param is in an alloca, exclude it from the coroutine
991 // frame. The parameter copy will be part of the frame, but the original
992 // parameter memory should remain on the stack. This is necessary to
993 // ensure that parameters destroyed in callees, as with `trivial_abi` or
994 // in the MSVC C++ ABI, are appropriately destroyed after setting up the
995 // coroutine.
996 Address ParmAddr = GetAddrOfLocalVar(Parm);
997 if (auto *ParmAlloca =
998 dyn_cast<llvm::AllocaInst>(ParmAddr.getBasePointer())) {
999 ParmAlloca->setMetadata(llvm::LLVMContext::MD_coro_outside_frame,
1000 llvm::MDNode::get(CGM.getLLVMContext(), {}));
1001 }
1002 }
1003 for (auto *PM : S.getParamMoves()) {
1004 EmitStmt(PM);
1005 ParamReplacer.addCopy(cast<DeclStmt>(PM));
1006 // TODO: if(CoroParam(...)) need to surround ctor and dtor
1007 // for the copy, so that llvm can elide it if the copy is
1008 // not needed.
1009 }
1010
1011 GroManager.EmitGroActive();
1013
1014 Address PromiseAddr = GetAddrOfLocalVar(S.getPromiseDecl());
1015 // Update CoroId to refer to the promise. We could not do it earlier because
1016 // promise local variable was not emitted yet.
1017 CoroId->setArgOperand(1, PromiseAddr.emitRawPointer(*this));
1018
1019 // Now we have the promise, initialize the GRO
1020 GroManager.EmitGroAlloca();
1021 GroManager.EmitGroInit();
1022
1023 EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
1024
1025 CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(CleanupBB);
1026 CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
1027 CurCoro.Data->ExceptionHandler = S.getExceptionHandler();
1029 CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
1030
1031 CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
1032
1033 if (CurCoro.Data->ExceptionHandler) {
1034 // If we generated IR to record whether an exception was thrown from
1035 // 'await_resume', then use that IR to determine whether the coroutine
1036 // body should be skipped.
1037 // If we didn't generate the IR (perhaps because 'await_resume' was marked
1038 // as 'noexcept'), then we skip this check.
1039 BasicBlock *ContBB = nullptr;
1040 if (CurCoro.Data->ResumeEHVar) {
1041 BasicBlock *BodyBB = createBasicBlock("coro.resumed.body");
1042 ContBB = createBasicBlock("coro.resumed.cont");
1043 Value *SkipBody = Builder.CreateFlagLoad(CurCoro.Data->ResumeEHVar,
1044 "coro.resumed.eh");
1045 Builder.CreateCondBr(SkipBody, ContBB, BodyBB);
1046 EmitBlock(BodyBB);
1047 }
1048
1049 auto Loc = S.getBeginLoc();
1050 CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr,
1051 CurCoro.Data->ExceptionHandler);
1052 auto *TryStmt =
1053 CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);
1054
1055 EnterCXXTryStmt(*TryStmt);
1056 emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());
1057 ExitCXXTryStmt(*TryStmt);
1058
1059 if (ContBB)
1060 EmitBlock(ContBB);
1061 }
1062 else {
1063 emitBodyAndFallthrough(*this, S, S.getBody());
1064 }
1065
1066 // See if we need to generate final suspend.
1067 const bool CanFallthrough = Builder.GetInsertBlock();
1068 const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
1069 if (CanFallthrough || HasCoreturns) {
1070 EmitBlock(FinalBB);
1071 CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
1073 } else {
1074 // We don't need FinalBB. Emit it to make sure the block is deleted.
1075 EmitBlock(FinalBB, /*IsFinished=*/true);
1076 }
1077
1078 // We need conversion if get_return_object's type doesn't matches the
1079 // coroutine return type.
1080 if (!GroManager.DirectEmit)
1081 GroManager.EmitGroConv(RetBB);
1082 EmitBlock(CleanupBB);
1083 }
1084
1085 EmitBlock(RetBB);
1086 // Emit coro.end before ret instruction, since resume and destroy parts of the
1087 // coroutine should return void.
1088 llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
1089 Builder.CreateCall(CoroEnd,
1090 {NullPtr, Builder.getFalse(),
1091 llvm::ConstantTokenNone::get(CoroEnd->getContext())});
1092
1093 if (auto *Ret = cast_or_null<ReturnStmt>(S.getReturnStmt())) {
1094 // Since we already emitted the return value above, so we shouldn't
1095 // emit it again here.
1096 Expr *PreviousRetValue = Ret->getRetValue();
1097 Ret->setRetValue(nullptr);
1098 EmitStmt(Ret);
1099 // Set the return value back. The code generator, as the AST **Consumer**,
1100 // shouldn't change the AST.
1101 Ret->setRetValue(PreviousRetValue);
1102 }
1103 // LLVM require the frontend to mark the coroutine.
1104 CurFn->setPresplitCoroutine();
1105
1106 if (CXXRecordDecl *RD = FnRetTy->getAsCXXRecordDecl();
1107 RD && RD->hasAttr<CoroOnlyDestroyWhenCompleteAttr>())
1108 CurFn->setCoroDestroyOnlyWhenComplete();
1109}
1110
1111// Emit coroutine intrinsic and patch up arguments of the token type.
1113 unsigned int IID) {
1115 switch (IID) {
1116 default:
1117 break;
1118 // The coro.frame builtin is replaced with an SSA value of the coro.begin
1119 // intrinsic.
1120 case llvm::Intrinsic::coro_frame: {
1121 if (CurCoro.Data && CurCoro.Data->CoroBegin) {
1122 return RValue::get(CurCoro.Data->CoroBegin);
1123 }
1124
1125 if (CurAwaitSuspendWrapper.FramePtr) {
1126 return RValue::get(CurAwaitSuspendWrapper.FramePtr);
1127 }
1128
1129 CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_begin "
1130 "has been used earlier in this function");
1131 auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getPtrTy());
1132 return RValue::get(NullPtr);
1133 }
1134 case llvm::Intrinsic::coro_size: {
1135 auto &Context = getContext();
1136 llvm::IntegerType *T =
1137 Builder.getIntNTy(Context.getTypeSize(Context.getSizeType()));
1138 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_size, T);
1139 return RValue::get(Builder.CreateCall(F));
1140 }
1141 case llvm::Intrinsic::coro_align: {
1142 auto &Context = getContext();
1143 llvm::IntegerType *T =
1144 Builder.getIntNTy(Context.getTypeSize(Context.getSizeType()));
1145 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_align, T);
1146 return RValue::get(Builder.CreateCall(F));
1147 }
1148 // The following three intrinsics take a token parameter referring to a token
1149 // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
1150 // builtins, we patch it up here.
1151 case llvm::Intrinsic::coro_alloc:
1152 case llvm::Intrinsic::coro_begin:
1153 case llvm::Intrinsic::coro_free: {
1154 if (CurCoro.Data && CurCoro.Data->CoroId) {
1155 Args.push_back(CurCoro.Data->CoroId);
1156 break;
1157 }
1158 CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
1159 " been used earlier in this function");
1160 // Fallthrough to the next case to add TokenNone as the first argument.
1161 [[fallthrough]];
1162 }
1163 // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
1164 // argument.
1165 case llvm::Intrinsic::coro_suspend:
1166 Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
1167 break;
1168 }
1169 for (const Expr *Arg : E->arguments())
1170 Args.push_back(EmitScalarExpr(Arg));
1171 // @llvm.coro.end takes a token parameter. Add token 'none' as the last
1172 // argument.
1173 if (IID == llvm::Intrinsic::coro_end)
1174 Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
1175
1176 llvm::Function *F = CGM.getIntrinsic(IID);
1177 llvm::CallInst *Call = Builder.CreateCall(F, Args);
1178
1179 // Note: The following code is to enable to emit coro.id and coro.begin by
1180 // hand to experiment with coroutines in C.
1181 // If we see @llvm.coro.id remember it in the CoroData. We will update
1182 // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
1183 if (IID == llvm::Intrinsic::coro_id) {
1184 createCoroData(*this, CurCoro, Call, E);
1185 }
1186 else if (IID == llvm::Intrinsic::coro_begin) {
1187 if (CurCoro.Data)
1188 CurCoro.Data->CoroBegin = Call;
1189 }
1190 else if (IID == llvm::Intrinsic::coro_free) {
1191 // Remember the last coro_free as we need it to build the conditional
1192 // deletion of the coroutine frame.
1193 if (CurCoro.Data)
1194 CurCoro.Data->LastCoroFree = Call;
1195 }
1196 return RValue::get(Call);
1197}
#define V(N, I)
static SmallString< 32 > buildSuspendPrefixStr(CGCoroData &Coro, AwaitKind Kind)
static QualType getCoroutineSuspendExprReturnType(const ASTContext &Ctx, const CoroutineSuspendExpr *E)
static bool StmtCanThrow(const Stmt *S)
static bool FunctionCanThrow(const FunctionDecl *D)
static SmallVector< llvm::OperandBundleDef, 1 > getBundlesForCoroEnd(CodeGenFunction &CGF)
static LValueOrRValue emitSuspendExpression(CIRGenFunction &cgf, CGCoroData &coro, CoroutineSuspendExpr const &s, cir::AwaitKind kind, AggValueSlot aggSlot, bool ignoreResult, mlir::Block *scopeParentBlock, mlir::Value &tmpResumeRValAddr, bool forLValue)
static mlir::LogicalResult emitBodyAndFallthrough(CIRGenFunction &cgf, const CoroutineBodyStmt &s, Stmt *body, const CIRGenFunction::LexicalScope *currLexScope)
static void createCoroData(CIRGenFunction &cgf, CIRGenFunction::CGCoroInfo &curCoro, cir::CallOp coroId)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:29
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:70
static CXXTryStmt * Create(const ASTContext &C, SourceLocation tryLoc, CompoundStmt *tryBlock, ArrayRef< Stmt * > handlers)
Definition StmtCXX.cpp:26
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2949
SourceLocation getBeginLoc() const
Definition Expr.h:3283
arg_range arguments()
Definition Expr.h:3201
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
Represents a 'co_await' expression.
Definition ExprCXX.h:5365
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition Address.h:128
llvm::Value * getBasePointer() const
Definition Address.h:198
static Address invalid()
Definition Address.h:176
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition Address.h:253
bool isValid() const
Definition Address.h:177
An aggregate value slot.
Definition CGValue.h:551
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored.
Definition CGValue.h:619
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
Definition CGDebugInfo.h:59
ParamDecl2StmtTy & getCoroutineParameterMappings()
CGFunctionInfo - Class to encapsulate the information about a function definition.
RawAddress getOriginalAllocatedAddress() const
Returns the address for the original alloca instruction.
static OpaqueValueMappingData bind(CodeGenFunction &CGF, const OpaqueValueExpr *ov, const Expr *e)
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
LValue EmitCoawaitLValue(const CoawaitExpr *E)
void EmitBranchOnBoolExpr(const Expr *Cond, llvm::BasicBlock *TrueBlock, llvm::BasicBlock *FalseBlock, uint64_t TrueCount, Stmt::Likelihood LH=Stmt::LH_None, const Expr *ConditionalOp=nullptr, const VarDecl *ConditionalDecl=nullptr)
EmitBranchOnBoolExpr - Emit a branch on a boolean condition (e.g.
RValue EmitCoroutineIntrinsic(const CallExpr *E, unsigned int IID)
JumpDest getJumpDestInCurrentScope(llvm::BasicBlock *Target)
The given basic block lies in the current EH scope, but may be a target of a potentially scope-crossi...
AwaitSuspendWrapperInfo CurAwaitSuspendWrapper
llvm::CallBase * EmitCallOrInvoke(llvm::FunctionCallee Callee, ArrayRef< llvm::Value * > Args, const Twine &Name="")
Emits a call or invoke instruction to the given function, depending on the current state of the EH st...
Definition CGCall.cpp:5424
void EmitCoreturnStmt(const CoreturnStmt &S)
void EmitAutoVarInit(const AutoVarEmission &emission)
Definition CGDecl.cpp:1952
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
AutoVarEmission EmitAutoVarAlloca(const VarDecl &var)
EmitAutoVarAlloca - Emit the alloca and debug information for a local variable.
Definition CGDecl.cpp:1490
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
pushDestroy - Push the standard destructor for the given type as at least a normal cleanup.
Definition CGDecl.cpp:2306
void EmitBranchThroughCleanup(JumpDest Dest)
EmitBranchThroughCleanup - Emit a branch from the current insert block through the normal cleanup han...
Destroyer * getDestroyer(QualType::DestructionKind destructionKind)
Definition CGDecl.cpp:2279
llvm::BasicBlock * getEHResumeBlock(bool isCleanup)
llvm::DenseMap< const Decl *, Address > DeclMapTy
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition CGExpr.cpp:259
void StartFunction(GlobalDecl GD, QualType RetTy, llvm::Function *Fn, const CGFunctionInfo &FnInfo, const FunctionArgList &Args, SourceLocation Loc=SourceLocation(), SourceLocation StartLoc=SourceLocation())
Emit code for the start of a function.
RValue EmitCoyieldExpr(const CoyieldExpr &E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
Definition CGExpr.cpp:160
LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its LValue mapping if it exists, otherwise create one.
Definition CGExpr.cpp:6421
llvm::Function * generateAwaitSuspendWrapper(Twine const &CoroName, Twine const &SuspendPointName, CoroutineSuspendExpr const &S)
void EmitCoroutineBody(const CoroutineBodyStmt &S)
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
void EmitAutoVarCleanups(const AutoVarEmission &emission)
Definition CGDecl.cpp:2225
void EmitAnyExprToMem(const Expr *E, Address Location, Qualifiers Quals, bool IsInitializer)
EmitAnyExprToMem - Emits the code necessary to evaluate an arbitrary expression into the given memory...
Definition CGExpr.cpp:310
RValue EmitAnyExpr(const Expr *E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
EmitAnyExpr - Emit code to compute the specified expression which can have any type.
Definition CGExpr.cpp:281
bool needsEHCleanup(QualType::DestructionKind kind)
Determines whether an EH cleanup is required to destroy a type with the given destruction kind.
void EmitStmt(const Stmt *S, ArrayRef< const Attr * > Attrs={})
EmitStmt - Emit the code for the statement.
Definition CGStmt.cpp:58
void ExitCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock=false)
LValue EmitCoyieldLValue(const CoyieldExpr *E)
RValue EmitCoawaitExpr(const CoawaitExpr &E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
llvm::SmallVector< const ParmVarDecl *, 4 > FnArgs
Save Parameter Decl for coroutine.
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
void FinishFunction(SourceLocation EndLoc=SourceLocation())
FinishFunction - Complete IR generation of the current function.
void EnterCXXTryStmt(const CXXTryStmt &S, bool IsFnTryBlock=false)
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
Definition CGExpr.cpp:1737
llvm::Instruction * CurrentFuncletPad
llvm::LLVMContext & getLLVMContext()
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:648
void Error(SourceLocation loc, StringRef error)
Emit a general error that something can't be done.
llvm::LLVMContext & getLLVMContext()
llvm::Function * getIntrinsic(unsigned IID, ArrayRef< llvm::Type * > Tys={})
stable_iterator stable_begin() const
Create a stable reference to the top of the EH stack.
iterator find(stable_iterator save) const
Turn a stable reference to a scope depth into a unstable pointer to the EH stack.
Definition CGCleanup.h:654
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition CGCall.h:377
LValue - This represents an lvalue references.
Definition CGValue.h:183
llvm::Value * getPointer(CodeGenFunction &CGF) const
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition CGValue.h:42
static RValue getIgnored()
Definition CGValue.h:94
static RValue get(llvm::Value *V)
Definition CGValue.h:99
llvm::Value * getPointer() const
Definition Address.h:66
static CompoundStmt * Create(const ASTContext &C, ArrayRef< Stmt * > Stmts, FPOptionsOverride FPFeatures, SourceLocation LB, SourceLocation RB)
Definition Stmt.cpp:399
Represents a 'co_return' statement in the C++ Coroutines TS.
Definition StmtCXX.h:474
Expr * getOperand() const
Retrieve the operand of the 'co_return' statement.
Definition StmtCXX.h:498
Expr * getPromiseCall() const
Retrieve the promise call that results from this 'co_return' statement.
Definition StmtCXX.h:503
Represents the body of a coroutine.
Definition StmtCXX.h:321
CompoundStmt * getBody() const
Retrieve the body of the coroutine as written.
Definition StmtCXX.h:381
Stmt * getReturnStmtOnAllocFailure() const
Definition StmtCXX.h:421
Expr * getReturnValueInit() const
Definition StmtCXX.h:413
Stmt * getReturnStmt() const
Definition StmtCXX.h:420
Stmt * getResultDecl() const
Definition StmtCXX.h:412
Stmt * getInitSuspendStmt() const
Definition StmtCXX.h:392
Expr * getAllocate() const
Definition StmtCXX.h:406
Stmt * getPromiseDeclStmt() const
Definition StmtCXX.h:385
VarDecl * getPromiseDecl() const
Definition StmtCXX.h:388
Expr * getDeallocate() const
Definition StmtCXX.h:409
Stmt * getFallthroughHandler() const
Definition StmtCXX.h:402
Stmt * getExceptionHandler() const
Definition StmtCXX.h:399
SourceLocation getBeginLoc() const LLVM_READONLY
Definition StmtCXX.h:428
Expr * getReturnValue() const
Definition StmtCXX.h:416
Stmt * getFinalSuspendStmt() const
Definition StmtCXX.h:395
ArrayRef< Stmt const * > getParamMoves() const
Definition StmtCXX.h:424
Represents an expression that might suspend coroutine execution; either a co_await or co_yield expres...
Definition ExprCXX.h:5251
SuspendReturnType getSuspendReturnType() const
Definition ExprCXX.h:5324
Expr * getReadyExpr() const
Definition ExprCXX.h:5307
Expr * getResumeExpr() const
Definition ExprCXX.h:5315
Expr * getSuspendExpr() const
Definition ExprCXX.h:5311
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition ExprCXX.h:5305
Expr * getCommonExpr() const
Definition ExprCXX.h:5300
Represents a 'co_yield' expression.
Definition ExprCXX.h:5446
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
ValueDecl * getDecl()
Definition Expr.h:1344
bool isSingleDecl() const
isSingleDecl - This method returns true if this DeclStmt refers to a single Decl.
Definition Stmt.h:1654
const Decl * getSingleDecl() const
Definition Stmt.h:1656
This represents one expression.
Definition Expr.h:112
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:144
Represents difference between two FPOptions values.
Represents a function declaration or definition.
Definition Decl.h:2029
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5371
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
static ImplicitParamDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, ImplicitParamKind ParamKind)
Create implicit parameter.
Definition Decl.cpp:5600
Represents a parameter to a function.
Definition Decl.h:1819
A (possibly-)qualified type.
Definition TypeBase.h:937
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8487
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1560
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Stmt - This represents one statement.
Definition Stmt.h:86
child_range children()
Definition Stmt.cpp:304
@ LH_Likely
Branch has the [[likely]] attribute.
Definition Stmt.h:1450
bool isVoidType() const
Definition TypeBase.h:9050
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
QualType getType() const
Definition Decl.h:723
const Expr * getInit() const
Definition Decl.h:1391
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
@ Address
A pointer to a ValueDecl.
Definition Primitives.h:28
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
Expr * Cond
};
bool isNoexceptExceptionSpec(ExceptionSpecificationType ESpecType)
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Other
Other implicit parameter.
Definition Decl.h:1774
CodeGenFunction::JumpDest FinalJD
CallExpr const * CoroIdExpr
llvm::BasicBlock * FinalExit
CodeGenFunction::JumpDest CleanupJD
llvm::BasicBlock * SuspendBB
llvm::CallInst * CoroBegin
llvm::CallInst * LastCoroFree
A jump destination is an abstract label, branching to which may require a jump out through normal cle...