clang 22.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.rst 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 auto UnbindCommonOnExit =
234 llvm::make_scope_exit([&] { CommonBinder.unbind(CGF); });
235
236 auto Prefix = buildSuspendPrefixStr(Coro, Kind);
237 BasicBlock *ReadyBlock = CGF.createBasicBlock(Prefix + Twine(".ready"));
238 BasicBlock *SuspendBlock = CGF.createBasicBlock(Prefix + Twine(".suspend"));
239 BasicBlock *CleanupBlock = CGF.createBasicBlock(Prefix + Twine(".cleanup"));
240
241 // If expression is ready, no need to suspend.
242 CGF.EmitBranchOnBoolExpr(S.getReadyExpr(), ReadyBlock, SuspendBlock, 0);
243
244 // Otherwise, emit suspend logic.
245 CGF.EmitBlock(SuspendBlock);
246
247 auto &Builder = CGF.Builder;
248 llvm::Function *CoroSave = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_save);
249 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.CGM.Int8PtrTy);
250 auto *SaveCall = Builder.CreateCall(CoroSave, {NullPtr});
251
252 auto SuspendWrapper = CodeGenFunction(CGF.CGM).generateAwaitSuspendWrapper(
253 CGF.CurFn->getName(), Prefix, S);
254
255 CGF.CurCoro.InSuspendBlock = true;
256
257 assert(CGF.CurCoro.Data && CGF.CurCoro.Data->CoroBegin &&
258 "expected to be called in coroutine context");
259
260 SmallVector<llvm::Value *, 3> SuspendIntrinsicCallArgs;
261 SuspendIntrinsicCallArgs.push_back(
263
264 SuspendIntrinsicCallArgs.push_back(CGF.CurCoro.Data->CoroBegin);
265 SuspendIntrinsicCallArgs.push_back(SuspendWrapper);
266
267 const auto SuspendReturnType = S.getSuspendReturnType();
268 llvm::Intrinsic::ID AwaitSuspendIID;
269
270 switch (SuspendReturnType) {
272 AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_void;
273 break;
275 AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_bool;
276 break;
278 AwaitSuspendIID = llvm::Intrinsic::coro_await_suspend_handle;
279 break;
280 }
281
282 llvm::Function *AwaitSuspendIntrinsic = CGF.CGM.getIntrinsic(AwaitSuspendIID);
283
284 // SuspendHandle might throw since it also resumes the returned handle.
285 const bool AwaitSuspendCanThrow =
286 SuspendReturnType ==
289
290 llvm::CallBase *SuspendRet = nullptr;
291 // FIXME: add call attributes?
292 if (AwaitSuspendCanThrow)
293 SuspendRet =
294 CGF.EmitCallOrInvoke(AwaitSuspendIntrinsic, SuspendIntrinsicCallArgs);
295 else
296 SuspendRet = CGF.EmitNounwindRuntimeCall(AwaitSuspendIntrinsic,
297 SuspendIntrinsicCallArgs);
298
299 assert(SuspendRet);
300 CGF.CurCoro.InSuspendBlock = false;
301
302 switch (SuspendReturnType) {
304 assert(SuspendRet->getType()->isVoidTy());
305 break;
307 assert(SuspendRet->getType()->isIntegerTy());
308
309 // Veto suspension if requested by bool returning await_suspend.
310 BasicBlock *RealSuspendBlock =
311 CGF.createBasicBlock(Prefix + Twine(".suspend.bool"));
312 CGF.Builder.CreateCondBr(SuspendRet, RealSuspendBlock, ReadyBlock);
313 CGF.EmitBlock(RealSuspendBlock);
314 break;
315 }
317 assert(SuspendRet->getType()->isVoidTy());
318 break;
319 }
320 }
321
322 // Emit the suspend point.
323 const bool IsFinalSuspend = (Kind == AwaitKind::Final);
324 llvm::Function *CoroSuspend =
325 CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_suspend);
326 auto *SuspendResult = Builder.CreateCall(
327 CoroSuspend, {SaveCall, Builder.getInt1(IsFinalSuspend)});
328
329 // Create a switch capturing three possible continuations.
330 auto *Switch = Builder.CreateSwitch(SuspendResult, Coro.SuspendBB, 2);
331 Switch->addCase(Builder.getInt8(0), ReadyBlock);
332 Switch->addCase(Builder.getInt8(1), CleanupBlock);
333
334 // Emit cleanup for this suspend point.
335 CGF.EmitBlock(CleanupBlock);
337 if (IsFinalSuspend)
338 Coro.FinalExit = CleanupBlock->getSingleSuccessor();
339
340 // Emit await_resume expression.
341 CGF.EmitBlock(ReadyBlock);
342
343 // Exception handling requires additional IR. If the 'await_resume' function
344 // is marked as 'noexcept', we avoid generating this additional IR.
345 CXXTryStmt *TryStmt = nullptr;
346 if (Coro.ExceptionHandler && Kind == AwaitKind::Init &&
348 Coro.ResumeEHVar =
349 CGF.CreateTempAlloca(Builder.getInt1Ty(), Prefix + Twine("resume.eh"));
350 Builder.CreateFlagStore(true, Coro.ResumeEHVar);
351
352 auto Loc = S.getResumeExpr()->getExprLoc();
353 auto *Catch = new (CGF.getContext())
354 CXXCatchStmt(Loc, /*exDecl=*/nullptr, Coro.ExceptionHandler);
355 auto *TryBody = CompoundStmt::Create(CGF.getContext(), S.getResumeExpr(),
356 FPOptionsOverride(), Loc, Loc);
357 TryStmt = CXXTryStmt::Create(CGF.getContext(), Loc, TryBody, Catch);
358 CGF.EnterCXXTryStmt(*TryStmt);
359 CGF.EmitStmt(TryBody);
360 // We don't use EmitCXXTryStmt here. We need to store to ResumeEHVar that
361 // doesn't exist in the body.
362 Builder.CreateFlagStore(false, Coro.ResumeEHVar);
363 CGF.ExitCXXTryStmt(*TryStmt);
364 LValueOrRValue Res;
365 // We are not supposed to obtain the value from init suspend await_resume().
366 Res.RV = RValue::getIgnored();
367 return Res;
368 }
369
370 LValueOrRValue Res;
371 if (forLValue)
372 Res.LV = CGF.EmitLValue(S.getResumeExpr());
373 else
374 Res.RV = CGF.EmitAnyExpr(S.getResumeExpr(), aggSlot, ignoreResult);
375
376 return Res;
377}
378
380 AggValueSlot aggSlot,
381 bool ignoreResult) {
382 return emitSuspendExpression(*this, *CurCoro.Data, E,
383 CurCoro.Data->CurrentAwaitKind, aggSlot,
384 ignoreResult, /*forLValue*/false).RV;
385}
387 AggValueSlot aggSlot,
388 bool ignoreResult) {
389 return emitSuspendExpression(*this, *CurCoro.Data, E, AwaitKind::Yield,
390 aggSlot, ignoreResult, /*forLValue*/false).RV;
391}
392
394 ++CurCoro.Data->CoreturnCount;
395 const Expr *RV = S.getOperand();
396 if (RV && RV->getType()->isVoidType() && !isa<InitListExpr>(RV)) {
397 // Make sure to evaluate the non initlist expression of a co_return
398 // with a void expression for side effects.
399 RunCleanupsScope cleanupScope(*this);
400 EmitIgnoredExpr(RV);
401 }
403 EmitBranchThroughCleanup(CurCoro.Data->FinalJD);
404}
405
406
407#ifndef NDEBUG
409 const CoroutineSuspendExpr *E) {
410 const auto *RE = E->getResumeExpr();
411 // Is it possible for RE to be a CXXBindTemporaryExpr wrapping
412 // a MemberCallExpr?
413 assert(isa<CallExpr>(RE) && "unexpected suspend expression type");
414 return cast<CallExpr>(RE)->getCallReturnType(Ctx);
415}
416#endif
417
418llvm::Function *
420 Twine const &SuspendPointName,
421 CoroutineSuspendExpr const &S) {
422 std::string FuncName =
423 (CoroName + ".__await_suspend_wrapper__" + SuspendPointName).str();
424
426
427 FunctionArgList args;
428
429 ImplicitParamDecl AwaiterDecl(C, C.VoidPtrTy, ImplicitParamKind::Other);
430 ImplicitParamDecl FrameDecl(C, C.VoidPtrTy, ImplicitParamKind::Other);
431 QualType ReturnTy = S.getSuspendExpr()->getType();
432
433 args.push_back(&AwaiterDecl);
434 args.push_back(&FrameDecl);
435
436 const CGFunctionInfo &FI =
437 CGM.getTypes().arrangeBuiltinFunctionDeclaration(ReturnTy, args);
438
439 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
440
441 llvm::Function *Fn = llvm::Function::Create(
442 LTy, llvm::GlobalValue::InternalLinkage, FuncName, &CGM.getModule());
443
444 Fn->addParamAttr(0, llvm::Attribute::AttrKind::NonNull);
445 Fn->addParamAttr(0, llvm::Attribute::AttrKind::NoUndef);
446
447 Fn->addParamAttr(1, llvm::Attribute::AttrKind::NoUndef);
448
449 Fn->setMustProgress();
450 Fn->addFnAttr(llvm::Attribute::AttrKind::AlwaysInline);
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 auto UnbindCommonOnExit =
468 llvm::make_scope_exit([&] { AwaiterBinder.unbind(*this); });
469 if (SuspendRet != nullptr) {
470 Fn->addRetAttr(llvm::Attribute::AttrKind::NoUndef);
471 Builder.CreateStore(SuspendRet, ReturnValue);
472 }
473
474 CurAwaitSuspendWrapper.FramePtr = nullptr;
476 return Fn;
477}
478
479LValue
481 assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
482 "Can't have a scalar return unless the return type is a "
483 "reference type!");
484 return emitSuspendExpression(*this, *CurCoro.Data, *E,
485 CurCoro.Data->CurrentAwaitKind, AggValueSlot::ignored(),
486 /*ignoreResult*/false, /*forLValue*/true).LV;
487}
488
489LValue
491 assert(getCoroutineSuspendExprReturnType(getContext(), E)->isReferenceType() &&
492 "Can't have a scalar return unless the return type is a "
493 "reference type!");
494 return emitSuspendExpression(*this, *CurCoro.Data, *E,
495 AwaitKind::Yield, AggValueSlot::ignored(),
496 /*ignoreResult*/false, /*forLValue*/true).LV;
497}
498
499// Hunts for the parameter reference in the parameter copy/move declaration.
500namespace {
501struct GetParamRef : public StmtVisitor<GetParamRef> {
502public:
503 DeclRefExpr *Expr = nullptr;
504 GetParamRef() {}
505 void VisitDeclRefExpr(DeclRefExpr *E) {
506 assert(Expr == nullptr && "multilple declref in param move");
507 Expr = E;
508 }
509 void VisitStmt(Stmt *S) {
510 for (auto *C : S->children()) {
511 if (C)
512 Visit(C);
513 }
514 }
515};
516}
517
518// This class replaces references to parameters to their copies by changing
519// the addresses in CGF.LocalDeclMap and restoring back the original values in
520// its destructor.
521
522namespace {
523 struct ParamReferenceReplacerRAII {
524 CodeGenFunction::DeclMapTy SavedLocals;
525 CodeGenFunction::DeclMapTy& LocalDeclMap;
526
527 ParamReferenceReplacerRAII(CodeGenFunction::DeclMapTy &LocalDeclMap)
528 : LocalDeclMap(LocalDeclMap) {}
529
530 void addCopy(DeclStmt const *PM) {
531 // Figure out what param it refers to.
532
533 assert(PM->isSingleDecl());
534 VarDecl const*VD = static_cast<VarDecl const*>(PM->getSingleDecl());
535 Expr const *InitExpr = VD->getInit();
536 GetParamRef Visitor;
537 Visitor.Visit(const_cast<Expr*>(InitExpr));
538 assert(Visitor.Expr);
539 DeclRefExpr *DREOrig = Visitor.Expr;
540 auto *PD = DREOrig->getDecl();
541
542 auto it = LocalDeclMap.find(PD);
543 assert(it != LocalDeclMap.end() && "parameter is not found");
544 SavedLocals.insert({ PD, it->second });
545
546 auto copyIt = LocalDeclMap.find(VD);
547 assert(copyIt != LocalDeclMap.end() && "parameter copy is not found");
548 it->second = copyIt->getSecond();
549 }
550
551 ~ParamReferenceReplacerRAII() {
552 for (auto&& SavedLocal : SavedLocals) {
553 LocalDeclMap.insert({SavedLocal.first, SavedLocal.second});
554 }
555 }
556 };
557}
558
559// For WinEH exception representation backend needs to know what funclet coro.end
560// belongs to. That information is passed in a funclet bundle.
561static SmallVector<llvm::OperandBundleDef, 1>
564
565 if (llvm::Instruction *EHPad = CGF.CurrentFuncletPad)
566 BundleList.emplace_back("funclet", EHPad);
567
568 return BundleList;
569}
570
571namespace {
572// We will insert coro.end to cut any of the destructors for objects that
573// do not need to be destroyed once the coroutine is resumed.
574// See llvm/docs/Coroutines.rst for more details about coro.end.
575struct CallCoroEnd final : public EHScopeStack::Cleanup {
576 void Emit(CodeGenFunction &CGF, Flags flags) override {
577 auto &CGM = CGF.CGM;
578 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
579 llvm::Function *CoroEndFn = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
580 // See if we have a funclet bundle to associate coro.end with. (WinEH)
581 auto Bundles = getBundlesForCoroEnd(CGF);
582 CGF.Builder.CreateCall(
583 CoroEndFn,
584 {NullPtr, CGF.Builder.getTrue(),
585 llvm::ConstantTokenNone::get(CoroEndFn->getContext())},
586 Bundles);
587 if (Bundles.empty()) {
588 // Otherwise, (landingpad model), create a conditional branch that leads
589 // either to a cleanup block or a block with EH resume instruction.
590 auto *ResumeBB = CGF.getEHResumeBlock(/*isCleanup=*/true);
591 auto *CleanupContBB = CGF.createBasicBlock("cleanup.cont");
592 auto *CoroIsInRampFn = CGM.getIntrinsic(llvm::Intrinsic::coro_is_in_ramp);
593 auto *CoroIsInRamp = CGF.Builder.CreateCall(CoroIsInRampFn);
594 CGF.Builder.CreateCondBr(CoroIsInRamp, CleanupContBB, ResumeBB);
595 CGF.EmitBlock(CleanupContBB);
596 }
597 }
598};
599}
600
601namespace {
602// Make sure to call coro.delete on scope exit.
603struct CallCoroDelete final : public EHScopeStack::Cleanup {
604 Stmt *Deallocate;
605
606 // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
607
608 // Note: That deallocation will be emitted twice: once for a normal exit and
609 // once for exceptional exit. This usage is safe because Deallocate does not
610 // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
611 // builds a single call to a deallocation function which is safe to emit
612 // multiple times.
613 void Emit(CodeGenFunction &CGF, Flags) override {
614 // Remember the current point, as we are going to emit deallocation code
615 // first to get to coro.free instruction that is an argument to a delete
616 // call.
617 BasicBlock *SaveInsertBlock = CGF.Builder.GetInsertBlock();
618
619 auto *FreeBB = CGF.createBasicBlock("coro.free");
620 CGF.EmitBlock(FreeBB);
621 CGF.EmitStmt(Deallocate);
622
623 auto *AfterFreeBB = CGF.createBasicBlock("after.coro.free");
624 CGF.EmitBlock(AfterFreeBB);
625
626 // We should have captured coro.free from the emission of deallocate.
627 auto *CoroFree = CGF.CurCoro.Data->LastCoroFree;
628 if (!CoroFree) {
629 CGF.CGM.Error(Deallocate->getBeginLoc(),
630 "Deallocation expressoin does not refer to coro.free");
631 return;
632 }
633
634 // Get back to the block we were originally and move coro.free there.
635 auto *InsertPt = SaveInsertBlock->getTerminator();
636 CoroFree->moveBefore(InsertPt->getIterator());
637 CGF.Builder.SetInsertPoint(InsertPt);
638
639 // Add if (auto *mem = coro.free) Deallocate;
640 auto *NullPtr = llvm::ConstantPointerNull::get(CGF.Int8PtrTy);
641 auto *Cond = CGF.Builder.CreateICmpNE(CoroFree, NullPtr);
642 CGF.Builder.CreateCondBr(Cond, FreeBB, AfterFreeBB);
643
644 // No longer need old terminator.
645 InsertPt->eraseFromParent();
646 CGF.Builder.SetInsertPoint(AfterFreeBB);
647 }
648 explicit CallCoroDelete(Stmt *DeallocStmt) : Deallocate(DeallocStmt) {}
649};
650}
651
652namespace {
653struct GetReturnObjectManager {
654 CodeGenFunction &CGF;
655 CGBuilderTy &Builder;
656 const CoroutineBodyStmt &S;
657 // When true, performs RVO for the return object.
658 bool DirectEmit = false;
659
660 Address GroActiveFlag;
661 CodeGenFunction::AutoVarEmission GroEmission;
662
663 GetReturnObjectManager(CodeGenFunction &CGF, const CoroutineBodyStmt &S)
664 : CGF(CGF), Builder(CGF.Builder), S(S), GroActiveFlag(Address::invalid()),
665 GroEmission(CodeGenFunction::AutoVarEmission::invalid()) {
666 // The call to get_­return_­object is sequenced before the call to
667 // initial_­suspend and is invoked at most once, but there are caveats
668 // regarding on whether the prvalue result object may be initialized
669 // directly/eager or delayed, depending on the types involved.
670 //
671 // More info at https://github.com/cplusplus/papers/issues/1414
672 //
673 // The general cases:
674 // 1. Same type of get_return_object and coroutine return type (direct
675 // emission):
676 // - Constructed in the return slot.
677 // 2. Different types (delayed emission):
678 // - Constructed temporary object prior to initial suspend initialized with
679 // a call to get_return_object()
680 // - When coroutine needs to to return to the caller and needs to construct
681 // return value for the coroutine it is initialized with expiring value of
682 // the temporary obtained above.
683 //
684 // Direct emission for void returning coroutines or GROs.
685 DirectEmit = [&]() {
686 auto *RVI = S.getReturnValueInit();
687 assert(RVI && "expected RVI");
688 auto GroType = RVI->getType();
689 return CGF.getContext().hasSameType(GroType, CGF.FnRetTy);
690 }();
691 }
692
693 // The gro variable has to outlive coroutine frame and coroutine promise, but,
694 // it can only be initialized after coroutine promise was created. Thus,
695 // EmitGroActive emits a flag and sets it to false. Later when coroutine
696 // promise is available we initialize the gro and set the flag indicating that
697 // the cleanup is now active.
698 void EmitGroActive() {
699 if (DirectEmit)
700 return;
701
702 auto *GroDeclStmt = dyn_cast_or_null<DeclStmt>(S.getResultDecl());
703 if (!GroDeclStmt) {
704 // If get_return_object returns void, no need to do an alloca.
705 return;
706 }
707
708 // Set GRO flag that it is not initialized yet
709 GroActiveFlag = CGF.CreateTempAlloca(Builder.getInt1Ty(), CharUnits::One(),
710 "gro.active");
711 Builder.CreateStore(Builder.getFalse(), GroActiveFlag);
712 }
713
714 void EmitGroAlloca() {
715 if (DirectEmit)
716 return;
717
718 auto *GroDeclStmt = dyn_cast_or_null<DeclStmt>(S.getResultDecl());
719 if (!GroDeclStmt) {
720 // If get_return_object returns void, no need to do an alloca.
721 return;
722 }
723
724 auto *GroVarDecl = cast<VarDecl>(GroDeclStmt->getSingleDecl());
725
726 GroEmission = CGF.EmitAutoVarAlloca(*GroVarDecl);
727
728 if (!GroVarDecl->isNRVOVariable()) {
729 // NRVO variables don't have allocas and won't have the same issue.
730 auto *GroAlloca = dyn_cast_or_null<llvm::AllocaInst>(
732 assert(GroAlloca && "expected alloca to be emitted");
733 GroAlloca->setMetadata(llvm::LLVMContext::MD_coro_outside_frame,
734 llvm::MDNode::get(CGF.CGM.getLLVMContext(), {}));
735 }
736
737 // Remember the top of EHStack before emitting the cleanup.
738 auto old_top = CGF.EHStack.stable_begin();
739 CGF.EmitAutoVarCleanups(GroEmission);
740 auto top = CGF.EHStack.stable_begin();
741
742 // Make the cleanup conditional on gro.active
743 for (auto b = CGF.EHStack.find(top), e = CGF.EHStack.find(old_top); b != e;
744 b++) {
745 if (auto *Cleanup = dyn_cast<EHCleanupScope>(&*b)) {
746 assert(!Cleanup->hasActiveFlag() && "cleanup already has active flag?");
747 Cleanup->setActiveFlag(GroActiveFlag);
748 Cleanup->setTestFlagInEHCleanup();
749 Cleanup->setTestFlagInNormalCleanup();
750 }
751 }
752 }
753
754 void EmitGroInit() {
755 if (DirectEmit) {
756 // ReturnValue should be valid as long as the coroutine's return type
757 // is not void. The assertion could help us to reduce the check later.
758 assert(CGF.ReturnValue.isValid() == (bool)S.getReturnStmt());
759 // Now we have the promise, initialize the GRO.
760 // We need to emit `get_return_object` first. According to:
761 // [dcl.fct.def.coroutine]p7
762 // The call to get_return_­object is sequenced before the call to
763 // initial_suspend and is invoked at most once.
764 //
765 // So we couldn't emit return value when we emit return statment,
766 // otherwise the call to get_return_object wouldn't be in front
767 // of initial_suspend.
768 if (CGF.ReturnValue.isValid()) {
771 /*IsInit*/ true);
772 }
773 return;
774 }
775
776 if (!GroActiveFlag.isValid()) {
777 // No Gro variable was allocated. Simply emit the call to
778 // get_return_object.
779 CGF.EmitStmt(S.getResultDecl());
780 return;
781 }
782
783 CGF.EmitAutoVarInit(GroEmission);
784 Builder.CreateStore(Builder.getTrue(), GroActiveFlag);
785 }
786 // The GRO returns either when it is first suspended or when it completes
787 // without ever being suspended. The EmitGroConv function evaluates these
788 // conditions and perform the conversion if needed.
789 //
790 // Before EmitGroConv():
791 // final.exit:
792 // switch i32 %cleanup.dest, label %destroy [
793 // i32 0, label %after.ready
794 // ]
795 //
796 // after.ready:
797 // ; (empty)
798 //
799 // After EmitGroConv():
800 // final.exit:
801 // switch i32 %cleanup.dest, label %destroy [
802 // i32 0, label %pre.gro.conv
803 // ]
804 //
805 // pre.gro.conv:
806 // %IsFinalExit = phi i1 [ false, %any.suspend ], [ true, %final.exit ]
807 // %InRamp = call i1 @llvm.coro.is_in_ramp()
808 // br i1 %InRamp, label %gro.conv, label %after.gro.conv
809 //
810 // gro.conv:
811 // ; GRO conversion
812 // br label %after.gro.conv
813 //
814 // after.gro.conv:
815 // br i1 %IsFinalExit, label %after.ready, label %coro.ret
816 void EmitGroConv(BasicBlock *RetBB) {
817 auto *AfterReadyBB = Builder.GetInsertBlock();
818 Builder.ClearInsertionPoint();
819
820 auto *PreConvBB = CGF.CurCoro.Data->SuspendBB;
821 CGF.EmitBlock(PreConvBB);
822 // If final.exit exists, redirect it to PreConvBB
823 llvm::PHINode *IsFinalExit = nullptr;
824 if (BasicBlock *FinalExit = CGF.CurCoro.Data->FinalExit) {
825 assert(AfterReadyBB &&
826 AfterReadyBB->getSinglePredecessor() == FinalExit &&
827 "Expect fallthrough from final.exit block");
828 AfterReadyBB->replaceAllUsesWith(PreConvBB);
829 PreConvBB->moveBefore(AfterReadyBB);
830
831 // If true, coroutine completes and should be destroyed after conversion
832 IsFinalExit =
833 Builder.CreatePHI(Builder.getInt1Ty(), llvm::pred_size(PreConvBB));
834 for (auto *Pred : llvm::predecessors(PreConvBB)) {
835 auto *V = (Pred == FinalExit) ? Builder.getTrue() : Builder.getFalse();
836 IsFinalExit->addIncoming(V, Pred);
837 }
838 }
839 auto *InRampFn = CGF.CGM.getIntrinsic(llvm::Intrinsic::coro_is_in_ramp);
840 auto *InRamp = Builder.CreateCall(InRampFn, {}, "InRamp");
841 auto *ConvBB = CGF.createBasicBlock("gro.conv");
842 auto *AfterConvBB = CGF.createBasicBlock("after.gro.conv");
843 Builder.CreateCondBr(InRamp, ConvBB, AfterConvBB);
844
845 CGF.EmitBlock(ConvBB);
848 /*IsInit*/ true);
849 Builder.CreateBr(AfterConvBB);
850
851 CGF.EmitBlock(AfterConvBB);
852 if (IsFinalExit)
853 Builder.CreateCondBr(IsFinalExit, AfterReadyBB, RetBB);
854 else
855 Builder.CreateBr(RetBB);
856 Builder.SetInsertPoint(AfterReadyBB);
857 }
858};
859} // namespace
860
862 const CoroutineBodyStmt &S, Stmt *Body) {
863 CGF.EmitStmt(Body);
864 const bool CanFallthrough = CGF.Builder.GetInsertBlock();
865 if (CanFallthrough)
866 if (Stmt *OnFallthrough = S.getFallthroughHandler())
867 CGF.EmitStmt(OnFallthrough);
868}
869
871 auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getPtrTy());
872 auto &TI = CGM.getContext().getTargetInfo();
873 unsigned NewAlign = TI.getNewAlign() / TI.getCharWidth();
874
875 auto *EntryBB = Builder.GetInsertBlock();
876 auto *AllocBB = createBasicBlock("coro.alloc");
877 auto *InitBB = createBasicBlock("coro.init");
878 auto *FinalBB = createBasicBlock("coro.final");
879 auto *RetBB = createBasicBlock("coro.ret");
880
881 auto *CoroId = Builder.CreateCall(
882 CGM.getIntrinsic(llvm::Intrinsic::coro_id),
883 {Builder.getInt32(NewAlign), NullPtr, NullPtr, NullPtr});
884 createCoroData(*this, CurCoro, CoroId);
885
886 GetReturnObjectManager GroManager(*this, S);
887 CurCoro.Data->SuspendBB =
888 GroManager.DirectEmit ? RetBB : createBasicBlock("pre.gvo.conv");
889 assert(ShouldEmitLifetimeMarkers &&
890 "Must emit lifetime intrinsics for coroutines");
891
892 // Backend is allowed to elide memory allocations, to help it, emit
893 // auto mem = coro.alloc() ? 0 : ... allocation code ...;
894 auto *CoroAlloc = Builder.CreateCall(
895 CGM.getIntrinsic(llvm::Intrinsic::coro_alloc), {CoroId});
896
897 Builder.CreateCondBr(CoroAlloc, AllocBB, InitBB);
898
899 EmitBlock(AllocBB);
900 auto *AllocateCall = EmitScalarExpr(S.getAllocate());
901 auto *AllocOrInvokeContBB = Builder.GetInsertBlock();
902
903 // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
904 if (auto *RetOnAllocFailure = S.getReturnStmtOnAllocFailure()) {
905 auto *RetOnFailureBB = createBasicBlock("coro.ret.on.failure");
906
907 // See if allocation was successful.
908 auto *NullPtr = llvm::ConstantPointerNull::get(Int8PtrTy);
909 auto *Cond = Builder.CreateICmpNE(AllocateCall, NullPtr);
910 // Expect the allocation to be successful.
911 emitCondLikelihoodViaExpectIntrinsic(Cond, Stmt::LH_Likely);
912 Builder.CreateCondBr(Cond, InitBB, RetOnFailureBB);
913
914 // If not, return OnAllocFailure object.
915 EmitBlock(RetOnFailureBB);
916 EmitStmt(RetOnAllocFailure);
917 }
918 else {
919 Builder.CreateBr(InitBB);
920 }
921
922 EmitBlock(InitBB);
923
924 // Pass the result of the allocation to coro.begin.
925 auto *Phi = Builder.CreatePHI(VoidPtrTy, 2);
926 Phi->addIncoming(NullPtr, EntryBB);
927 Phi->addIncoming(AllocateCall, AllocOrInvokeContBB);
928 auto *CoroBegin = Builder.CreateCall(
929 CGM.getIntrinsic(llvm::Intrinsic::coro_begin), {CoroId, Phi});
930 CurCoro.Data->CoroBegin = CoroBegin;
931
932 CurCoro.Data->CleanupJD = getJumpDestInCurrentScope(RetBB);
933 {
935 ParamReferenceReplacerRAII ParamReplacer(LocalDeclMap);
936 CodeGenFunction::RunCleanupsScope ResumeScope(*this);
937 EHStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, S.getDeallocate());
938
939 // Create mapping between parameters and copy-params for coroutine function.
941 assert(
942 (ParamMoves.size() == 0 || (ParamMoves.size() == FnArgs.size())) &&
943 "ParamMoves and FnArgs should be the same size for coroutine function");
944 if (ParamMoves.size() == FnArgs.size() && DI)
945 for (const auto Pair : llvm::zip(FnArgs, ParamMoves))
947 {std::get<0>(Pair), std::get<1>(Pair)});
948
949 // Create parameter copies. We do it before creating a promise, since an
950 // evolution of coroutine TS may allow promise constructor to observe
951 // parameter copies.
952 for (const ParmVarDecl *Parm : FnArgs) {
953 // If the original param is in an alloca, exclude it from the coroutine
954 // frame. The parameter copy will be part of the frame, but the original
955 // parameter memory should remain on the stack. This is necessary to
956 // ensure that parameters destroyed in callees, as with `trivial_abi` or
957 // in the MSVC C++ ABI, are appropriately destroyed after setting up the
958 // coroutine.
959 Address ParmAddr = GetAddrOfLocalVar(Parm);
960 if (auto *ParmAlloca =
961 dyn_cast<llvm::AllocaInst>(ParmAddr.getBasePointer())) {
962 ParmAlloca->setMetadata(llvm::LLVMContext::MD_coro_outside_frame,
963 llvm::MDNode::get(CGM.getLLVMContext(), {}));
964 }
965 }
966 for (auto *PM : S.getParamMoves()) {
967 EmitStmt(PM);
968 ParamReplacer.addCopy(cast<DeclStmt>(PM));
969 // TODO: if(CoroParam(...)) need to surround ctor and dtor
970 // for the copy, so that llvm can elide it if the copy is
971 // not needed.
972 }
973
974 GroManager.EmitGroActive();
976
977 Address PromiseAddr = GetAddrOfLocalVar(S.getPromiseDecl());
978 // Update CoroId to refer to the promise. We could not do it earlier because
979 // promise local variable was not emitted yet.
980 CoroId->setArgOperand(1, PromiseAddr.emitRawPointer(*this));
981
982 // Now we have the promise, initialize the GRO
983 GroManager.EmitGroAlloca();
984 GroManager.EmitGroInit();
985
986 EHStack.pushCleanup<CallCoroEnd>(EHCleanup);
987
988 CurCoro.Data->CurrentAwaitKind = AwaitKind::Init;
989 CurCoro.Data->ExceptionHandler = S.getExceptionHandler();
991 CurCoro.Data->FinalJD = getJumpDestInCurrentScope(FinalBB);
992
993 CurCoro.Data->CurrentAwaitKind = AwaitKind::Normal;
994
995 if (CurCoro.Data->ExceptionHandler) {
996 // If we generated IR to record whether an exception was thrown from
997 // 'await_resume', then use that IR to determine whether the coroutine
998 // body should be skipped.
999 // If we didn't generate the IR (perhaps because 'await_resume' was marked
1000 // as 'noexcept'), then we skip this check.
1001 BasicBlock *ContBB = nullptr;
1002 if (CurCoro.Data->ResumeEHVar) {
1003 BasicBlock *BodyBB = createBasicBlock("coro.resumed.body");
1004 ContBB = createBasicBlock("coro.resumed.cont");
1005 Value *SkipBody = Builder.CreateFlagLoad(CurCoro.Data->ResumeEHVar,
1006 "coro.resumed.eh");
1007 Builder.CreateCondBr(SkipBody, ContBB, BodyBB);
1008 EmitBlock(BodyBB);
1009 }
1010
1011 auto Loc = S.getBeginLoc();
1012 CXXCatchStmt Catch(Loc, /*exDecl=*/nullptr,
1013 CurCoro.Data->ExceptionHandler);
1014 auto *TryStmt =
1015 CXXTryStmt::Create(getContext(), Loc, S.getBody(), &Catch);
1016
1017 EnterCXXTryStmt(*TryStmt);
1018 emitBodyAndFallthrough(*this, S, TryStmt->getTryBlock());
1019 ExitCXXTryStmt(*TryStmt);
1020
1021 if (ContBB)
1022 EmitBlock(ContBB);
1023 }
1024 else {
1025 emitBodyAndFallthrough(*this, S, S.getBody());
1026 }
1027
1028 // See if we need to generate final suspend.
1029 const bool CanFallthrough = Builder.GetInsertBlock();
1030 const bool HasCoreturns = CurCoro.Data->CoreturnCount > 0;
1031 if (CanFallthrough || HasCoreturns) {
1032 EmitBlock(FinalBB);
1033 CurCoro.Data->CurrentAwaitKind = AwaitKind::Final;
1035 } else {
1036 // We don't need FinalBB. Emit it to make sure the block is deleted.
1037 EmitBlock(FinalBB, /*IsFinished=*/true);
1038 }
1039
1040 // We need conversion if get_return_object's type doesn't matches the
1041 // coroutine return type.
1042 if (!GroManager.DirectEmit)
1043 GroManager.EmitGroConv(RetBB);
1044 }
1045
1046 EmitBlock(RetBB);
1047 // Emit coro.end before ret instruction, since resume and destroy parts of the
1048 // coroutine should return void.
1049 llvm::Function *CoroEnd = CGM.getIntrinsic(llvm::Intrinsic::coro_end);
1050 Builder.CreateCall(CoroEnd,
1051 {NullPtr, Builder.getFalse(),
1052 llvm::ConstantTokenNone::get(CoroEnd->getContext())});
1053
1054 if (auto *Ret = cast_or_null<ReturnStmt>(S.getReturnStmt())) {
1055 // Since we already emitted the return value above, so we shouldn't
1056 // emit it again here.
1057 Expr *PreviousRetValue = Ret->getRetValue();
1058 Ret->setRetValue(nullptr);
1059 EmitStmt(Ret);
1060 // Set the return value back. The code generator, as the AST **Consumer**,
1061 // shouldn't change the AST.
1062 Ret->setRetValue(PreviousRetValue);
1063 }
1064 // LLVM require the frontend to mark the coroutine.
1065 CurFn->setPresplitCoroutine();
1066
1067 if (CXXRecordDecl *RD = FnRetTy->getAsCXXRecordDecl();
1068 RD && RD->hasAttr<CoroOnlyDestroyWhenCompleteAttr>())
1069 CurFn->setCoroDestroyOnlyWhenComplete();
1070}
1071
1072// Emit coroutine intrinsic and patch up arguments of the token type.
1074 unsigned int IID) {
1076 switch (IID) {
1077 default:
1078 break;
1079 // The coro.frame builtin is replaced with an SSA value of the coro.begin
1080 // intrinsic.
1081 case llvm::Intrinsic::coro_frame: {
1082 if (CurCoro.Data && CurCoro.Data->CoroBegin) {
1083 return RValue::get(CurCoro.Data->CoroBegin);
1084 }
1085
1086 if (CurAwaitSuspendWrapper.FramePtr) {
1087 return RValue::get(CurAwaitSuspendWrapper.FramePtr);
1088 }
1089
1090 CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_begin "
1091 "has been used earlier in this function");
1092 auto *NullPtr = llvm::ConstantPointerNull::get(Builder.getPtrTy());
1093 return RValue::get(NullPtr);
1094 }
1095 case llvm::Intrinsic::coro_size: {
1096 auto &Context = getContext();
1097 llvm::IntegerType *T =
1098 Builder.getIntNTy(Context.getTypeSize(Context.getSizeType()));
1099 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_size, T);
1100 return RValue::get(Builder.CreateCall(F));
1101 }
1102 case llvm::Intrinsic::coro_align: {
1103 auto &Context = getContext();
1104 llvm::IntegerType *T =
1105 Builder.getIntNTy(Context.getTypeSize(Context.getSizeType()));
1106 llvm::Function *F = CGM.getIntrinsic(llvm::Intrinsic::coro_align, T);
1107 return RValue::get(Builder.CreateCall(F));
1108 }
1109 // The following three intrinsics take a token parameter referring to a token
1110 // returned by earlier call to @llvm.coro.id. Since we cannot represent it in
1111 // builtins, we patch it up here.
1112 case llvm::Intrinsic::coro_alloc:
1113 case llvm::Intrinsic::coro_begin:
1114 case llvm::Intrinsic::coro_free: {
1115 if (CurCoro.Data && CurCoro.Data->CoroId) {
1116 Args.push_back(CurCoro.Data->CoroId);
1117 break;
1118 }
1119 CGM.Error(E->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
1120 " been used earlier in this function");
1121 // Fallthrough to the next case to add TokenNone as the first argument.
1122 [[fallthrough]];
1123 }
1124 // @llvm.coro.suspend takes a token parameter. Add token 'none' as the first
1125 // argument.
1126 case llvm::Intrinsic::coro_suspend:
1127 Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
1128 break;
1129 }
1130 for (const Expr *Arg : E->arguments())
1131 Args.push_back(EmitScalarExpr(Arg));
1132 // @llvm.coro.end takes a token parameter. Add token 'none' as the last
1133 // argument.
1134 if (IID == llvm::Intrinsic::coro_end)
1135 Args.push_back(llvm::ConstantTokenNone::get(getLLVMContext()));
1136
1137 llvm::Function *F = CGM.getIntrinsic(IID);
1138 llvm::CallInst *Call = Builder.CreateCall(F, Args);
1139
1140 // Note: The following code is to enable to emit coro.id and coro.begin by
1141 // hand to experiment with coroutines in C.
1142 // If we see @llvm.coro.id remember it in the CoroData. We will update
1143 // coro.alloc, coro.begin and coro.free intrinsics to refer to it.
1144 if (IID == llvm::Intrinsic::coro_id) {
1145 createCoroData(*this, CurCoro, Call, E);
1146 }
1147 else if (IID == llvm::Intrinsic::coro_begin) {
1148 if (CurCoro.Data)
1149 CurCoro.Data->CoroBegin = Call;
1150 }
1151 else if (IID == llvm::Intrinsic::coro_free) {
1152 // Remember the last coro_free as we need it to build the conditional
1153 // deletion of the coroutine frame.
1154 if (CurCoro.Data)
1155 CurCoro.Data->LastCoroFree = Call;
1156 }
1157 return RValue::get(Call);
1158}
#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)
__device__ __2f16 b
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
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:28
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:69
static CXXTryStmt * Create(const ASTContext &C, SourceLocation tryLoc, CompoundStmt *tryBlock, ArrayRef< Stmt * > handlers)
Definition StmtCXX.cpp:25
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2943
SourceLocation getBeginLoc() const
Definition Expr.h:3277
arg_range arguments()
Definition Expr.h:3195
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
Represents a 'co_await' expression.
Definition ExprCXX.h:5369
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
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:541
static AggValueSlot ignored()
ignored - Returns an aggregate value slot indicating that the aggregate value is being ignored.
Definition CGValue.h:609
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:5102
void EmitCoreturnStmt(const CoreturnStmt &S)
void EmitAutoVarInit(const AutoVarEmission &emission)
Definition CGDecl.cpp:1929
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:1482
void EmitBranchThroughCleanup(JumpDest Dest)
EmitBranchThroughCleanup - Emit a branch from the current insert block through the normal cleanup han...
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:245
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:154
LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its LValue mapping if it exists, otherwise create one.
Definition CGExpr.cpp:6106
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:2202
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:296
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:267
void EmitStmt(const Stmt *S, ArrayRef< const Attr * > Attrs={})
EmitStmt - Emit the code for the statement.
Definition CGStmt.cpp:61
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:1691
llvm::Instruction * CurrentFuncletPad
llvm::LLVMContext & getLLVMContext()
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:656
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:647
FunctionArgList - Type for representing both the decl and type of parameters to a function.
Definition CGCall.h:375
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:394
Represents a 'co_return' statement in the C++ Coroutines TS.
Definition StmtCXX.h:473
Expr * getOperand() const
Retrieve the operand of the 'co_return' statement.
Definition StmtCXX.h:497
Expr * getPromiseCall() const
Retrieve the promise call that results from this 'co_return' statement.
Definition StmtCXX.h:502
Represents the body of a coroutine.
Definition StmtCXX.h:320
CompoundStmt * getBody() const
Retrieve the body of the coroutine as written.
Definition StmtCXX.h:380
Stmt * getReturnStmtOnAllocFailure() const
Definition StmtCXX.h:420
Expr * getReturnValueInit() const
Definition StmtCXX.h:412
Stmt * getReturnStmt() const
Definition StmtCXX.h:419
Stmt * getResultDecl() const
Definition StmtCXX.h:411
Stmt * getInitSuspendStmt() const
Definition StmtCXX.h:391
Expr * getAllocate() const
Definition StmtCXX.h:405
Stmt * getPromiseDeclStmt() const
Definition StmtCXX.h:384
VarDecl * getPromiseDecl() const
Definition StmtCXX.h:387
Expr * getDeallocate() const
Definition StmtCXX.h:408
Stmt * getFallthroughHandler() const
Definition StmtCXX.h:401
Stmt * getExceptionHandler() const
Definition StmtCXX.h:398
SourceLocation getBeginLoc() const LLVM_READONLY
Definition StmtCXX.h:427
Expr * getReturnValue() const
Definition StmtCXX.h:415
Stmt * getFinalSuspendStmt() const
Definition StmtCXX.h:394
ArrayRef< Stmt const * > getParamMoves() const
Definition StmtCXX.h:423
Represents an expression that might suspend coroutine execution; either a co_await or co_yield expres...
Definition ExprCXX.h:5255
SuspendReturnType getSuspendReturnType() const
Definition ExprCXX.h:5328
Expr * getReadyExpr() const
Definition ExprCXX.h:5311
Expr * getResumeExpr() const
Definition ExprCXX.h:5319
Expr * getSuspendExpr() const
Definition ExprCXX.h:5315
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition ExprCXX.h:5309
Expr * getCommonExpr() const
Definition ExprCXX.h:5304
Represents a 'co_yield' expression.
Definition ExprCXX.h:5450
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1270
ValueDecl * getDecl()
Definition Expr.h:1338
bool isSingleDecl() const
isSingleDecl - This method returns true if this DeclStmt refers to a single Decl.
Definition Stmt.h:1635
const Decl * getSingleDecl() const
Definition Stmt.h:1637
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:276
QualType getType() const
Definition Expr.h:144
Represents difference between two FPOptions values.
Represents a function declaration or definition.
Definition Decl.h:2000
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5269
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:57
Represents a parameter to a function.
Definition Decl.h:1790
A (possibly-)qualified type.
Definition TypeBase.h:937
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8332
StmtVisitor - This class implements a simple visitor for Stmt subclasses.
Stmt - This represents one statement.
Definition Stmt.h:85
child_range children()
Definition Stmt.cpp:299
@ LH_Likely
Branch has the [[likely]] attribute.
Definition Stmt.h:1431
bool isVoidType() const
Definition TypeBase.h:8891
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9111
QualType getType() const
Definition Decl.h:723
const Expr * getInit() const
Definition Decl.h:1368
@ EHCleanup
Denotes a cleanup that should run when a scope is exited using exceptional control flow (a throw stat...
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
Expr * Cond
};
const FunctionProtoType * T
bool isNoexceptExceptionSpec(ExceptionSpecificationType ESpecType)
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Other
Other implicit parameter.
Definition Decl.h:1746
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...