clang 24.0.0git
CIRGenCoroutine.cpp
Go to the documentation of this file.
1//===----- CGCoroutine.cpp - Emit CIR 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 "CIRGenFunction.h"
14#include "mlir/Support/LLVM.h"
15#include "clang/AST/StmtCXX.h"
20
21using namespace clang;
22using namespace clang::CIRGen;
23
25 // What is the current await expression kind and how many
26 // await/yield expressions were encountered so far.
27 // These are used to generate pretty labels for await expressions in LLVM IR.
28 cir::AwaitKind currentAwaitKind = cir::AwaitKind::Init;
29 // Stores the __builtin_coro_id emitted in the function so that we can supply
30 // it as the first argument to other builtins.
31 cir::CoroIdOp coroId = nullptr;
32
33 // Stores the result of __builtin_coro_begin call.
34 mlir::Value coroBegin = nullptr;
35
36 // How many co_return statements are in the coroutine. Used to decide whether
37 // we need to add co_return; equivalent at the end of the user authored body.
38 unsigned coreturnCount = 0;
39
40 // The promise type's 'unhandled_exception' handler, if it defines one.
42
43 // Stores the last emitted coro.free for the deallocate expressions, we use it
44 // to wrap dealloc code with if(auto mem = coro.free) dealloc(mem).
45 cir::CoroFreeOp lastCoroFree = nullptr;
46
47 // A temporary bool alloca that stores whether 'await_resume' threw an
48 // exception. If it did, 'true' is stored in this variable, and the coroutine
49 // body must be skipped. If the promise type does not define an exception
50 // handler, this is null.
52
53 // If coro.id came from the builtin, remember the expression to give better
54 // diagnostic. If CoroIdExpr is nullptr, the coro.id was created by
55 // EmitCoroutineBody.
56 CallExpr const *coroIdExpr = nullptr;
57};
58
59// Defining these here allows to keep CGCoroData private to this file.
62
63namespace {
64// FIXME: both GetParamRef and ParamReferenceReplacerRAII are good template
65// candidates to be shared among LLVM / CIR codegen.
66
67// Hunts for the parameter reference in the parameter copy/move declaration.
68struct GetParamRef : public StmtVisitor<GetParamRef> {
69public:
70 DeclRefExpr *expr = nullptr;
71 GetParamRef() {}
72 void VisitDeclRefExpr(DeclRefExpr *e) {
73 assert(expr == nullptr && "multilple declref in param move");
74 expr = e;
75 }
76 void VisitStmt(Stmt *s) {
77 for (Stmt *c : s->children()) {
78 if (c)
79 Visit(c);
80 }
81 }
82};
83
84// This class replaces references to parameters to their copies by changing
85// the addresses in CGF.LocalDeclMap and restoring back the original values in
86// its destructor.
87struct ParamReferenceReplacerRAII {
88 CIRGenFunction::DeclMapTy savedLocals;
89 CIRGenFunction::DeclMapTy &localDeclMap;
90
91 ParamReferenceReplacerRAII(CIRGenFunction::DeclMapTy &localDeclMap)
92 : localDeclMap(localDeclMap) {}
93
94 void addCopy(const DeclStmt *pm) {
95 // Figure out what param it refers to.
96
97 assert(pm->isSingleDecl());
98 const VarDecl *vd = static_cast<const VarDecl *>(pm->getSingleDecl());
99 const Expr *initExpr = vd->getInit();
100 GetParamRef visitor;
101 visitor.Visit(const_cast<Expr *>(initExpr));
102 assert(visitor.expr);
103 DeclRefExpr *dreOrig = visitor.expr;
104 auto *pd = dreOrig->getDecl();
105
106 auto it = localDeclMap.find(pd);
107 assert(it != localDeclMap.end() && "parameter is not found");
108 savedLocals.insert({pd, it->second});
109
110 auto copyIt = localDeclMap.find(vd);
111 assert(copyIt != localDeclMap.end() && "parameter copy is not found");
112 it->second = copyIt->getSecond();
113 }
114
115 ~ParamReferenceReplacerRAII() {
116 for (auto &&savedLocal : savedLocals) {
117 localDeclMap.insert({savedLocal.first, savedLocal.second});
118 }
119 }
120};
121} // namespace
122
123namespace {
124// Make sure to call coro.delete on scope exit.
125struct CallCoroDelete final : public EHScopeStack::Cleanup {
126 Stmt *deallocate;
127
128 // Emit "if (coro.free(CoroId, CoroBegin)) Deallocate;"
129
130 // Note: That deallocation will be emitted twice: once for a normal exit and
131 // once for exceptional exit. This usage is safe because Deallocate does not
132 // contain any declarations. The SubStmtBuilder::makeNewAndDeleteExpr()
133 // builds a single call to a deallocation function which is safe to emit
134 // multiple times.
135 void emit(CIRGenFunction &cgf, Flags) override {
136 // Remember the current point, as we are going to emit deallocation code
137 // first to get to coro.free instruction that is an argument to a delete
138 // call.
139
140 if (cgf.emitStmt(deallocate, /*useCurrentScope=*/true).failed()) {
141 cgf.cgm.error(deallocate->getBeginLoc(),
142 "failed to emit coroutine deallocation expression");
143 return;
144 }
145
146 CIRGenBuilderTy &builder = cgf.getBuilder();
147 cir::CoroFreeOp coroFree = cgf.curCoro.data->lastCoroFree;
148
149 if (!coroFree) {
150 cgf.cgm.error(deallocate->getBeginLoc(),
151 "Deallocation expression does not refer to coro.free");
152 return;
153 }
154
155 builder.setInsertionPointAfter(coroFree);
156 mlir::Value isPtrNotNull = builder.createPtrIsNotNull(coroFree.getResult());
157
158 llvm::SmallVector<mlir::Operation *> opsToMove;
159 mlir::Block *block = builder.getInsertionBlock();
160 mlir::Block::iterator it(isPtrNotNull.getDefiningOp());
161
162 for (++it; it != block->end(); ++it)
163 opsToMove.push_back(&*it);
164
165 auto ifOp =
166 cir::IfOp::create(builder, cgf.getLoc(deallocate->getSourceRange()),
167 isPtrNotNull, /*withElseRegion*/ false,
168 [&](mlir::OpBuilder &builder, mlir::Location loc) {
169 cir::YieldOp::create(builder, loc);
170 });
171
172 mlir::Operation *yieldOp = ifOp.getThenRegion().back().getTerminator();
173 for (auto *op : opsToMove)
174 op->moveBefore(yieldOp);
175 }
176 explicit CallCoroDelete(Stmt *deallocStmt) : deallocate(deallocStmt) {}
177};
178} // namespace
179
181 if (curCoro.data && curCoro.data->coroBegin) {
182 return RValue::get(curCoro.data->coroBegin);
183 }
184 cgm.errorNYI("NYI");
185 return RValue();
186}
187
190 cir::CoroIdOp coroId,
191 CallExpr const *coroIdExpr = nullptr) {
192
193 if (curCoro.data) {
194 if (curCoro.data->coroIdExpr)
195 cgf.cgm.error(coroIdExpr->getBeginLoc(),
196 "only one __builtin_coro_id can be used in a function");
197 else if (coroIdExpr)
198 cgf.cgm.error(coroIdExpr->getBeginLoc(),
199 "__builtin_coro_id shall not be used in a C++ coroutine");
200 else
201 llvm_unreachable("EmitCoroutineBodyStatement called twice?");
202
203 return;
204 }
205
206 curCoro.data = std::make_unique<CGCoroData>();
207 curCoro.data->coroId = coroId;
208 curCoro.data->coroIdExpr = coroIdExpr;
209}
210
211static mlir::LogicalResult
213 Stmt *body,
214 const CIRGenFunction::LexicalScope *currLexScope) {
215 if (cgf.emitStmt(body, /*useCurrentScope=*/true).failed())
216 return mlir::failure();
217 // Note that classic codegen checks CanFallthrough by looking into the
218 // availability of the insert block which is kinda brittle and unintuitive,
219 // seems to be related with how landing pads are handled.
220 //
221 // CIRGen handles this by checking pre-existing co_returns in the current
222 // scope instead.
223
224 // From LLVM IR Gen: const bool CanFallthrough = Builder.GetInsertBlock();
225 const bool canFallthrough = !currLexScope->hasCoreturn();
226 if (canFallthrough)
227 if (Stmt *onFallthrough = s.getFallthroughHandler())
228 if (cgf.emitStmt(onFallthrough, /*useCurrentScope=*/true).failed())
229 return mlir::failure();
230
231 return mlir::success();
232}
233
235 mlir::Location loc = getLoc(e->getBeginLoc());
236
238 for (const Expr *arg : e->arguments())
239 args.push_back(emitScalarExpr(arg));
240
241 auto coroId = cir::CoroIdOp::create(cgm.getBuilder(), loc, args);
242 createCoroData(*this, curCoro, coroId, e);
243 return coroId;
244}
245
247 mlir::Location loc = getLoc(e->getBeginLoc());
248 if (!curCoro.data || !curCoro.data->coroId) {
249 cgm.error(e->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
250 " been used earlier in this function");
251 return {};
252 }
253
254 return cir::CoroAllocOp::create(
255 cgm.getBuilder(), loc,
256 mlir::ValueRange{curCoro.data->coroId.getResult()});
257}
258
260
261 mlir::Location loc = getLoc(e->getBeginLoc());
262 if (!curCoro.data || !curCoro.data->coroId) {
263 cgm.error(e->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
264 " been used earlier in this function");
265 return {};
266 }
268 args.push_back(curCoro.data->coroId.getResult());
269 for (const Expr *arg : e->arguments())
270 args.push_back(emitScalarExpr(arg));
271
272 auto coroBegin = cir::CoroBeginOp::create(cgm.getBuilder(), loc, args);
273 curCoro.data->coroBegin = coroBegin;
274 return coroBegin;
275}
276
278
279 mlir::Location loc = getLoc(e->getBeginLoc());
280 CIRGenBuilderTy &builder = cgm.getBuilder();
282 for (const Expr *arg : e->arguments())
283 args.push_back(emitScalarExpr(arg));
284 args.push_back(cir::TokenNoneOp::create(builder, loc));
285 return cir::CoroEndOp::create(builder, loc, {cgm.voidTy}, args);
286}
287
289 mlir::Location loc = getLoc(e->getBeginLoc());
290
291 if (!curCoro.data || !curCoro.data->coroId) {
292 cgm.error(e->getBeginLoc(), "this builtin expect that __builtin_coro_id has"
293 " been used earlier in this function");
294 return {};
295 }
296
297 auto coroFree =
298 cir::CoroFreeOp::create(cgm.getBuilder(), loc,
299 mlir::ValueRange{curCoro.data->coroId.getResult(),
300 curCoro.data->coroBegin});
301
302 curCoro.data->lastCoroFree = coroFree;
303 return coroFree;
304}
305
307 mlir::Location loc = getLoc(e->getBeginLoc());
308 return cir::CoroSizeOp::create(cgm.getBuilder(), loc);
309}
310
311static mlir::LogicalResult
313
314 CXXCatchStmt catchStmt(s.getBeginLoc(), /*exDecl=*/nullptr,
315 cgf.curCoro.data->exceptionHandler);
316 auto *tryStmt = CXXTryStmt::Create(cgf.getContext(), s.getBeginLoc(),
317 s.getBody(), &catchStmt);
318 struct handlerEmitter final : CIRGenFunction::cxxTryBodyEmitter {
319 const CoroutineBodyStmt &s;
320
321 handlerEmitter(const CoroutineBodyStmt &s) : s(s) /*, scope(scope)*/ {}
322 mlir::LogicalResult operator()(CIRGenFunction &cgf) override {
323 return emitBodyAndFallthrough(cgf, s, s.getBody(), cgf.curLexScope);
324 }
325 ~handlerEmitter() override = default;
326 } emitter{s};
327
328 mlir::LogicalResult res = cgf.emitCXXTryStmt(*tryStmt, emitter);
329
330 return res;
331}
332
333mlir::LogicalResult
335 mlir::Location openCurlyLoc = getLoc(s.getBeginLoc());
336 cir::ConstantOp nullPtrCst = builder.getNullPtr(voidPtrTy, openCurlyLoc);
337
338 auto fn = mlir::cast<cir::FuncOp>(curFn);
339 fn.setCoroutine(true);
340 const TargetInfo &ti = cgm.getASTContext().getTargetInfo();
341 unsigned newAlign = ti.getNewAlign() / ti.getCharWidth();
342
343 cir::CoroIdOp coroId = cir::CoroIdOp::create(
344 cgm.getBuilder(), openCurlyLoc,
345 mlir::ValueRange{builder.getUInt32(newAlign, openCurlyLoc), nullPtrCst,
346 nullPtrCst, nullPtrCst});
347 createCoroData(*this, curCoro, coroId);
348
349 // Backend is allowed to elide memory allocations, to help it, emit
350 // auto mem = coro.alloc() ? 0 : ... allocation code ...;
351 cir::CoroAllocOp coroAlloc = cir::CoroAllocOp::create(
352 cgm.getBuilder(), openCurlyLoc,
353 mlir::ValueRange{curCoro.data->coroId.getResult()});
354
355 // Initialize address of coroutine frame to null
356 CanQualType astVoidPtrTy = cgm.getASTContext().VoidPtrTy;
357 mlir::Type allocaTy = convertTypeForMem(astVoidPtrTy);
358 Address coroFrame =
359 createTempAlloca(allocaTy, getContext().getTypeAlignInChars(astVoidPtrTy),
360 openCurlyLoc, "__coro_frame_addr",
361 /*ArraySize=*/nullptr);
362
363 mlir::Value storeAddr = coroFrame.getPointer();
364 builder.CIRBaseBuilderTy::createStore(openCurlyLoc, nullPtrCst, storeAddr);
365 cir::IfOp::create(
366 builder, openCurlyLoc, coroAlloc.getResult(),
367 /*withElseRegion=*/false,
368 /*thenBuilder=*/[&](mlir::OpBuilder &b, mlir::Location loc) {
369 builder.CIRBaseBuilderTy::createStore(
370 loc, emitScalarExpr(s.getAllocate()), storeAddr);
371 cir::YieldOp::create(builder, loc);
372 });
373 curCoro.data->coroBegin = cir::CoroBeginOp::create(
374 cgm.getBuilder(), openCurlyLoc,
375 mlir::ValueRange{
376 curCoro.data->coroId.getResult(),
377 cir::LoadOp::create(builder, openCurlyLoc, allocaTy, storeAddr)});
378
379 // Handle allocation failure if 'ReturnStmtOnAllocFailure' was provided.
381 cgm.errorNYI("handle coroutine return alloc failure");
382
383 {
385 ParamReferenceReplacerRAII paramReplacer(localDeclMap);
386 RunCleanupsScope resumeScope(*this);
387 ehStack.pushCleanup<CallCoroDelete>(NormalAndEHCleanup, s.getDeallocate());
388 // Create mapping between parameters and copy-params for coroutine
389 // function.
391 assert((paramMoves.size() == 0 || (paramMoves.size() == fnArgs.size())) &&
392 "ParamMoves and FnArgs should be the same size for coroutine "
393 "function");
394 // For zipping the arg map into debug info.
396
397 // Create parameter copies. We do it before creating a promise, since an
398 // evolution of coroutine TS may allow promise constructor to observe
399 // parameter copies.
401 for (auto *pm : paramMoves) {
402 if (emitStmt(pm, /*useCurrentScope=*/true).failed())
403 return mlir::failure();
404 paramReplacer.addCopy(cast<DeclStmt>(pm));
405 }
406
407 if (emitStmt(s.getPromiseDeclStmt(), /*useCurrentScope=*/true).failed())
408 return mlir::failure();
409 // returnValue should be valid as long as the coroutine's return type
410 // is not void. The assertion could help us to reduce the check later.
411 assert(returnValue.isValid() == (bool)s.getReturnStmt());
412 // Now we have the promise, initialize the GRO.
413 // We need to emit `get_return_object` first. According to:
414 // [dcl.fct.def.coroutine]p7
415 // The call to get_return_­object is sequenced before the call to
416 // initial_suspend and is invoked at most once.
417 //
418 // So we couldn't emit return value when we emit return statment,
419 // otherwise the call to get_return_object wouldn't be in front
420 // of initial_suspend.
421 if (returnValue.isValid())
424 /*isInit*/ true);
425
427
428 curCoro.data->currentAwaitKind = cir::AwaitKind::Init;
429 curCoro.data->exceptionHandler = s.getExceptionHandler();
430
431 if (emitStmt(s.getInitSuspendStmt(), /*useCurrentScope=*/true).failed())
432 return mlir::failure();
433
434 curCoro.data->currentAwaitKind = cir::AwaitKind::User;
435
436 mlir::OpBuilder::InsertPoint userBody;
437 auto coroBodyOp =
438 cir::CoroBodyOp::create(builder, openCurlyLoc, /*scopeBuilder=*/
439 [&](mlir::OpBuilder &b, mlir::Location loc) {
440 userBody = b.saveInsertionPoint();
441 });
442 {
443 mlir::OpBuilder::InsertionGuard guard(builder);
444 builder.restoreInsertionPoint(userBody);
445 if (curCoro.data->exceptionHandler) {
446 // This bit of code is supposed to do:
447 //
448 // if (await-resume-didnt-throw-exception) {
449 // try {
450 // coroutine-body
451 // } catch (...) {
452 // unhandled_exception();
453 // }
454 // }
455 //
456 // IF resume couldn't have thrown an exception(await_resume is
457 // noexcept), we skip the 'if'.
458 //
459 // Note that we've reversed the condition of the 'if' from classic
460 // codegen so that we don't need an 'else' block.
461 if (curCoro.data->resumeEHVar.isValid()) {
462 mlir::Value shouldSkip = builder.createFlagLoad(
463 openCurlyLoc, curCoro.data->resumeEHVar.getPointer());
464 mlir::LogicalResult res = mlir::success();
465 cir::IfOp::create(builder, openCurlyLoc, shouldSkip,
466 /*withElseRegion=*/false,
467 [&](mlir::OpBuilder &b, mlir::Location loc) {
468 res = coroutineBodyExceptionHelper(*this, s);
469 builder.createYield(openCurlyLoc);
470 });
471
472 if (res.failed())
473 return mlir::failure();
474
475 } else if (coroutineBodyExceptionHelper(*this, s).failed()) {
476 return mlir::failure();
477 }
478 } else if (emitBodyAndFallthrough(*this, s, s.getBody(), curLexScope)
479 .failed()) {
480 return mlir::failure();
481 }
482 }
483
484 mlir::Block &coroBodyBlock = coroBodyOp.getBody().back();
485 if (!coroBodyBlock.mightHaveTerminator()) {
486 mlir::OpBuilder::InsertionGuard guard(builder);
487 builder.setInsertionPointToEnd(&coroBodyBlock);
488 cir::YieldOp::create(builder, openCurlyLoc);
489 }
490
491 // Note that LLVM checks CanFallthrough by looking into the availability
492 // of the insert block which is kinda brittle and unintuitive, seems to be
493 // related with how landing pads are handled.
494 //
495 // CIRGen handles this by checking pre-existing co_returns in the current
496 // scope instead.
497 //
498 // From LLVM IR Gen: const bool CanFallthrough = Builder.GetInsertBlock();
499 const bool canFallthrough = curLexScope->hasCoreturn();
500 const bool hasCoreturns = curCoro.data->coreturnCount > 0;
501 if (canFallthrough || hasCoreturns) {
502 curCoro.data->currentAwaitKind = cir::AwaitKind::Final;
503 {
504 mlir::OpBuilder::InsertionGuard guard(builder);
505 if (emitStmt(s.getFinalSuspendStmt(), /*useCurrentScope=*/true)
506 .failed())
507 return mlir::failure();
508 }
509 }
510 }
511
512 cir::ConstantOp nullHandler =
513 builder.getNullPtr(builder.getVoidPtrTy(), openCurlyLoc);
514 cir::ConstantOp noUnwind = builder.getBool(false, openCurlyLoc);
515 auto tkNone = cir::TokenNoneOp::create(builder, openCurlyLoc);
516 cir::CoroEndOp::create(builder, openCurlyLoc, nullHandler, noUnwind, tkNone);
517
518 if (auto *ret = cast_or_null<ReturnStmt>(s.getReturnStmt())) {
519 // Since we already emitted the return value above, so we shouldn't
520 // emit it again here.
521 Expr *previousRetValue = ret->getRetValue();
522 ret->setRetValue(nullptr);
523 if (emitStmt(ret, /*useCurrentScope=*/true).failed())
524 return mlir::failure();
525 // Set the return value back. The code generator, as the AST **Consumer**,
526 // shouldn't change the AST.
527 ret->setRetValue(previousRetValue);
528 }
529 return mlir::success();
530}
531
532static bool memberCallExpressionCanThrow(const Expr *e) {
533 if (const auto *ce = dyn_cast<CXXMemberCallExpr>(e))
534 if (const auto *proto =
535 ce->getMethodDecl()->getType()->getAs<FunctionProtoType>())
536 if (isNoexceptExceptionSpec(proto->getExceptionSpecType()) &&
537 proto->canThrow() == CT_Cannot)
538 return false;
539 return true;
540}
541
542// Given a suspend expression which roughly looks like:
543//
544// auto && x = CommonExpr();
545// if (!x.await_ready()) {
546// x.await_suspend(...); (*)
547// }
548// x.await_resume();
549//
550// where the result of the entire expression is the result of x.await_resume()
551//
552// (*) If x.await_suspend return type is bool, it allows to veto a suspend:
553// if (x.await_suspend(...))
554// llvm_coro_suspend();
555//
556// This is more higher level than LLVM codegen, for that one see llvm's
557// docs/Coroutines.md for more details.
558namespace {
559struct LValueOrRValue {
560 LValue lv;
561 RValue rv;
562};
563} // namespace
564
565static LValueOrRValue
567 CoroutineSuspendExpr const &s, cir::AwaitKind kind,
568 AggValueSlot aggSlot, bool ignoreResult,
569 mlir::Block *scopeParentBlock,
570 mlir::Value &tmpResumeRValAddr, bool forLValue) {
571 [[maybe_unused]] mlir::LogicalResult awaitBuild = mlir::success();
572 LValueOrRValue awaitRes;
573
576 CIRGenBuilderTy &builder = cgf.getBuilder();
577 [[maybe_unused]] cir::AwaitOp awaitOp = cir::AwaitOp::create(
578 builder, cgf.getLoc(s.getSourceRange()), kind,
579 /*readyBuilder=*/
580 [&](mlir::OpBuilder &b, mlir::Location loc) {
581 Expr *condExpr = s.getReadyExpr()->IgnoreParens();
582 builder.createCondition(cgf.evaluateExprAsBool(condExpr));
583 },
584 /*suspendBuilder=*/
585 [&](mlir::OpBuilder &b, mlir::Location loc) {
586 // Note that differently from LLVM codegen we do not emit coro.save
587 // and coro.suspend here, that should be done as part of lowering this
588 // to LLVM dialect (or some other MLIR dialect)
589
590 // A invalid suspendRet indicates "void returning await_suspend"
591 mlir::Value suspendRet = cgf.emitScalarExpr(s.getSuspendExpr());
592
593 // Veto suspension if requested by bool returning await_suspend.
594 if (suspendRet) {
595 cgf.cgm.errorNYI("Veto await_suspend");
596 }
597
598 // Signals the parent that execution flows to next region.
599 cir::YieldOp::create(builder, loc);
600 },
601 /*resumeBuilder=*/
602 [&](mlir::OpBuilder &b, mlir::Location loc) {
603 // Exception handling requires additional IR. If the 'await_resume'
604 // function is marked as 'noexcept', we avoid generating this additional
605 // IR.
606 if (coro.exceptionHandler && kind == cir::AwaitKind::Init &&
607 memberCallExpressionCanThrow(s.getResumeExpr())) {
608 // we are basically just emitting:
609 // resumeEh = false;
610 // try {
611 // resumeExpr();
612 // resumeEh = true;
613 // } catch(...) {
614 // exceptionHandler();
615 // }
616 // Note the values of resumeEh are reversed from classic codegen,
617 // simply so we can use an 'IfOp' without a 'else' later.
618 ASTContext &ctx = cgf.getContext();
619 SourceLocation resumeLoc = s.getResumeExpr()->getExprLoc();
620 mlir::Location mlirLoc = cgf.getLoc(resumeLoc);
621 coro.resumeEHVar = cgf.createTempAlloca(
622 builder.getBoolTy(), ctx.getTypeAlignInChars(ctx.BoolTy), mlirLoc,
623 "resume.eh");
624 builder.createFlagStore(mlirLoc, false,
625 coro.resumeEHVar.getPointer());
626
627 CXXCatchStmt catchStmt(resumeLoc,
628 /*exDecl=*/nullptr, coro.exceptionHandler);
629 auto *tryBody =
630 CompoundStmt::Create(ctx, s.getResumeExpr(), FPOptionsOverride(),
631 resumeLoc, resumeLoc);
632 CXXTryStmt *tryStmt =
633 CXXTryStmt::Create(ctx, resumeLoc, tryBody, &catchStmt);
634
635 struct resumeEmitter final : CIRGenFunction::cxxTryBodyEmitter {
636 const CXXTryStmt &tryStmt;
637 mlir::Location loc;
638 mlir::Value resumeEHVar;
639 resumeEmitter(const CXXTryStmt &tryStmt, mlir::Location loc,
640 Address resumeEHVar)
641 : tryStmt(tryStmt), loc(loc),
642 resumeEHVar(resumeEHVar.getPointer()) {}
643
644 mlir::LogicalResult operator()(CIRGenFunction &cgf) override {
645 mlir::LogicalResult res =
646 cgf.emitStmt(tryStmt.getTryBlock(), /*useCurrentScope=*/true);
647 cgf.getBuilder().createFlagStore(loc, true, resumeEHVar);
648 return res;
649 }
650
651 ~resumeEmitter() override = default;
652 } emitter{*tryStmt, mlirLoc, coro.resumeEHVar};
653
654 awaitBuild = cgf.emitCXXTryStmt(*tryStmt, emitter);
655 // We are not supposed to obtain the value from init suspend
656 // await_resume().
657 awaitRes.rv = RValue::getIgnored();
658 } else if (forLValue) {
659 // FIXME(cir): the alloca for the resume expr should be placed in the
660 // enclosing cir.scope instead.
661 awaitRes.lv = cgf.emitLValue(s.getResumeExpr());
662 } else {
663 awaitRes.rv =
664 cgf.emitAnyExpr(s.getResumeExpr(), aggSlot, ignoreResult);
665 if (!awaitRes.rv.isIgnored()) {
666 // Create the alloca in the block before the scope wrapping
667 // cir.await.
668 mlir::Value value;
669 RValue rv = awaitRes.rv;
670 if (rv.isScalar()) {
671 value = rv.getValue();
672 } else if (rv.isComplex()) {
673 value = rv.getComplexValue();
674 } else {
675 cgf.cgm.errorNYI("emitSuspendExpression: Aggregate value");
676 return;
677 }
678
679 tmpResumeRValAddr = cgf.emitAlloca(
680 "__coawait_resume_rval", value.getType(), loc, CharUnits::One(),
681 builder.getBestAllocaInsertPoint(scopeParentBlock));
682 // Store the rvalue so we can reload it before the promise call.
683 builder.CIRBaseBuilderTy::createStore(loc, value,
684 tmpResumeRValAddr);
685 }
686 }
687
688 // Returns control back to parent.
689 cir::YieldOp::create(builder, loc);
690 });
691
692 assert(awaitBuild.succeeded() && "Should know how to codegen");
693 return awaitRes;
694}
695
697 const CoroutineSuspendExpr &e,
698 cir::AwaitKind kind, AggValueSlot aggSlot,
699 bool ignoreResult) {
700 RValue rval;
701 mlir::Location scopeLoc = cgf.getLoc(e.getSourceRange());
702
703 // Since we model suspend / resume as an inner region, we must store
704 // resume scalar results in a tmp alloca, and load it after we build the
705 // suspend expression. An alternative way to do this would be to make
706 // every region return a value when promise.return_value() is used, but
707 // it's a bit awkward given that resume is the only region that actually
708 // returns a value.
709 mlir::Block *currEntryBlock = cgf.curLexScope->getEntryBlock();
710 [[maybe_unused]] mlir::Value tmpResumeRValAddr;
711
712 // No need to explicitly wrap this into a scope since the AST already uses a
713 // ExprWithCleanups, which will wrap this into a cir.scope anyways.
714 rval = emitSuspendExpression(cgf, *cgf.curCoro.data, e, kind, aggSlot,
715 ignoreResult, currEntryBlock, tmpResumeRValAddr,
716 /*forLValue*/ false)
717 .rv;
718
719 if (ignoreResult || rval.isIgnored())
720 return rval;
721
722 if (rval.isScalar()) {
723 rval = RValue::get(cir::LoadOp::create(cgf.getBuilder(), scopeLoc,
724 rval.getValue().getType(),
725 tmpResumeRValAddr));
726 } else if (rval.isAggregate()) {
727 // This is probably already handled via AggSlot, remove this assertion
728 // once we have a testcase and prove all pieces work.
729 cgf.cgm.errorNYI("emitSuspendExpr Aggregate");
730 } else { // complex
731 rval = RValue::getComplex(cir::LoadOp::create(
732 cgf.getBuilder(), scopeLoc, rval.getComplexValue().getType(),
733 tmpResumeRValAddr));
734 }
735 return rval;
736}
737
739 AggValueSlot aggSlot,
740 bool ignoreResult) {
741 return emitSuspendExpr(*this, e, curCoro.data->currentAwaitKind, aggSlot,
742 ignoreResult);
743}
744
746 AggValueSlot aggSlot,
747 bool ignoreResult) {
748 return emitSuspendExpr(*this, e, cir::AwaitKind::Yield, aggSlot,
749 ignoreResult);
750}
751
752mlir::LogicalResult CIRGenFunction::emitCoreturnStmt(CoreturnStmt const &s) {
753 ++curCoro.data->coreturnCount;
754 curLexScope->setCoreturn();
755
756 const Expr *rv = s.getOperand();
757 if (rv && rv->getType()->isVoidType() && !isa<InitListExpr>(rv)) {
758 // Make sure to evaluate the non initlist expression of a co_return
759 // with a void expression for side effects.
760 RunCleanupsScope cleanupScope(*this);
761 emitIgnoredExpr(rv);
762 }
763
764 if (emitStmt(s.getPromiseCall(), /*useCurrentScope=*/true).failed())
765 return mlir::failure();
766 // Create a new return block (if not existent) and add a branch to
767 // it. The actual return instruction is only inserted during current
768 // scope cleanup handling.
769 mlir::Location loc = getLoc(s.getSourceRange());
770 cir::CoReturnOp::create(builder, loc);
771
772 return mlir::success();
773}
static void emit(Program &P, llvm::SmallVectorImpl< std::byte > &Code, const T &Val, bool &Success)
Helper to write bytecode and bail out if 32-bit offsets become invalid.
static void createCoroData(CIRGenFunction &cgf, CIRGenFunction::CGCoroInfo &curCoro, cir::CoroIdOp coroId, CallExpr const *coroIdExpr=nullptr)
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 RValue emitSuspendExpr(CIRGenFunction &cgf, const CoroutineSuspendExpr &e, cir::AwaitKind kind, AggValueSlot aggSlot, bool ignoreResult)
static bool memberCallExpressionCanThrow(const Expr *e)
static mlir::LogicalResult coroutineBodyExceptionHelper(CIRGenFunction &cgf, const CoroutineBodyStmt &s)
static mlir::LogicalResult emitBodyAndFallthrough(CIRGenFunction &cgf, const CoroutineBodyStmt &s, Stmt *body, const CIRGenFunction::LexicalScope *currLexScope)
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
cir::StoreOp createFlagStore(mlir::Location loc, bool val, mlir::Value dst)
mlir::Value createPtrIsNotNull(mlir::Value ptr)
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
CanQualType BoolTy
mlir::Value getPointer() const
Definition Address.h:98
static Address invalid()
Definition Address.h:76
An aggregate value slot.
An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited.
mlir::LogicalResult emitCoreturnStmt(const CoreturnStmt &s)
cir::AllocaOp createTempAlloca(mlir::Type ty, mlir::Location loc, const Twine &name="tmp", mlir::Value arraySize=nullptr, bool insertIntoFnEntryBlock=false)
This creates an alloca and inserts it into the entry block if ArraySize is nullptr,...
cir::CoroAllocOp emitCoroAllocBuiltinCall(const CallExpr *e)
llvm::DenseMap< const clang::Decl *, Address > DeclMapTy
LValue emitLValue(const clang::Expr *e)
Emit code to compute a designator that specifies the location of the expression.
mlir::Location getLoc(clang::SourceLocation srcLoc)
Helpers to convert Clang's SourceLocation to a MLIR Location.
cir::CoroBeginOp emitCoroBeginBuiltinCall(const CallExpr *e)
void emitAnyExprToMem(const Expr *e, Address location, Qualifiers quals, bool isInitializer)
Emits the code necessary to evaluate an arbitrary expression into the given memory location.
RValue emitCoyieldExpr(const CoyieldExpr &e, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
cir::CoroFreeOp emitCoroFreeBuiltin(const CallExpr *e)
mlir::Operation * curFn
The current function or global initializer that is generated code for.
EHScopeStack ehStack
Tracks function scope overall cleanup handling.
llvm::SmallVector< const ParmVarDecl * > fnArgs
Save Parameter Decl for coroutine.
mlir::Type convertTypeForMem(QualType t)
mlir::LogicalResult emitCXXTryStmt(const clang::CXXTryStmt &s, cxxTryBodyEmitter &bodyCallback)
mlir::Value emitAlloca(llvm::StringRef name, mlir::Type ty, mlir::Location loc, clang::CharUnits alignment, bool insertIntoFnEntryBlock, mlir::Value arraySize=nullptr)
Address returnValue
The temporary alloca to hold the return value.
cir::CoroEndOp emitCoroEndBuiltinCall(const CallExpr *e)
mlir::Value emitScalarExpr(const clang::Expr *e, bool ignoreResultAssign=false)
Emit the computation of the specified expression of scalar type.
CIRGenBuilderTy & getBuilder()
DeclMapTy localDeclMap
This keeps track of the CIR allocas or globals for local C declarations.
RValue emitCoawaitExpr(const CoawaitExpr &e, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
RValue emitAnyExpr(const clang::Expr *e, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
Emit code to compute the specified expression which can have any type.
cir::CoroSizeOp emitCoroSizeBuiltinCall(const CallExpr *e)
cir::CoroIdOp emitCoroIDBuiltinCall(const CallExpr *e)
clang::ASTContext & getContext() const
mlir::LogicalResult emitCoroutineBody(const CoroutineBodyStmt &s)
mlir::LogicalResult emitStmt(const clang::Stmt *s, bool useCurrentScope, llvm::ArrayRef< const Attr * > attrs={})
void emitIgnoredExpr(const clang::Expr *e)
Emit code to compute the specified expression, ignoring the result.
DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef)
Helpers to emit "not yet implemented" error diagnostics.
void error(SourceLocation loc, llvm::StringRef error)
Emit a general error that something can't be done.
This trivial value class is used to represent the result of an expression that is evaluated.
Definition CIRGenValue.h:33
bool isAggregate() const
Definition CIRGenValue.h:51
static RValue get(mlir::Value v)
Definition CIRGenValue.h:83
static RValue getComplex(mlir::Value v)
Definition CIRGenValue.h:91
bool isComplex() const
Definition CIRGenValue.h:50
mlir::Value getValue() const
Return the value of this scalar value.
Definition CIRGenValue.h:57
bool isScalar() const
Definition CIRGenValue.h:49
bool isIgnored() const
Definition CIRGenValue.h:52
mlir::Value getComplexValue() const
Return the value of this complex value.
Definition CIRGenValue.h:63
static RValue getIgnored()
Definition CIRGenValue.h:78
CXXCatchStmt - This represents a C++ catch block.
Definition StmtCXX.h:29
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:2954
SourceLocation getBeginLoc() const
Definition Expr.h:3288
arg_range arguments()
Definition Expr.h:3206
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
Represents a 'co_await' expression.
Definition ExprCXX.h:5368
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
Stmt * getReturnStmt() const
Definition StmtCXX.h:420
Stmt * getInitSuspendStmt() const
Definition StmtCXX.h:392
Stmt * getPromiseDeclStmt() const
Definition StmtCXX.h:385
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:5254
OpaqueValueExpr * getOpaqueValue() const
getOpaqueValue - Return the opaque value placeholder.
Definition ExprCXX.h:5308
Represents a 'co_yield' expression.
Definition ExprCXX.h:5449
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1281
ValueDecl * getDecl()
Definition Expr.h:1349
bool isSingleDecl() const
isSingleDecl - This method returns true if this DeclStmt refers to a single Decl.
Definition Stmt.h:1653
const Decl * getSingleDecl() const
Definition Stmt.h:1655
This represents one expression.
Definition Expr.h:112
QualType getType() const
Definition Expr.h:144
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5421
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8544
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:304
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
Exposes information about the current target.
Definition TargetInfo.h:227
unsigned getNewAlign() const
Return the largest alignment for which a suitably-sized allocation with 'operator new(size_t)' is gua...
Definition TargetInfo.h:773
unsigned getCharWidth() const
Definition TargetInfo.h:527
bool isVoidType() const
Definition TypeBase.h:9113
const Expr * getInit() const
Definition Decl.h:1391
Defines the clang::TargetInfo interface.
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isNoexceptExceptionSpec(ExceptionSpecificationType ESpecType)
U cast(CodeGen::Address addr)
Definition Address.h:327
static bool ehCleanupScope()
static bool coroOutsideFrameMD()
static bool generateDebugInfo()
std::unique_ptr< CGCoroData > data
Represents a scope, including function bodies, compound statements, and the substatements of if/while...
cir::PointerType voidPtrTy
void* in address space 0