15#include "mlir/Dialect/Func/IR/FuncOps.h"
16#include "mlir/IR/Block.h"
17#include "mlir/IR/Builders.h"
18#include "mlir/IR/PatternMatch.h"
19#include "mlir/Interfaces/SideEffectInterfaces.h"
20#include "mlir/Rewrite/PatternApplicator.h"
21#include "mlir/Support/LogicalResult.h"
22#include "mlir/Transforms/DialectConversion.h"
28#include "llvm/ADT/TypeSwitch.h"
34#define GEN_PASS_DEF_CIRFLATTENCFG
35#include "clang/CIR/Dialect/Passes.h.inc"
41void lowerTerminator(mlir::Operation *op, mlir::Block *dest,
42 mlir::PatternRewriter &rewriter,
43 mlir::DistinctAttr loopId = {},
44 cir::LoopHintAttr loopHints = {}) {
45 assert(op->hasTrait<mlir::OpTrait::IsTerminator>() &&
"not a terminator");
46 mlir::OpBuilder::InsertionGuard guard(rewriter);
47 rewriter.setInsertionPoint(op);
48 rewriter.replaceOpWithNewOp<cir::BrOp>(op, mlir::ValueRange{}, loopId,
54template <
typename... Ops>
55void walkRegionSkipping(
57 mlir::function_ref<mlir::WalkResult(mlir::Operation *)> callback) {
58 region.walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
60 return mlir::WalkResult::skip();
76static bool hasNestedOpsToFlatten(mlir::Region ®ion) {
78 .walk([](mlir::Operation *op) {
79 if (op->getNumRegions() > 0 && !isa<cir::CaseOp>(op) &&
80 isa<cir::CIRDialect>(op->getDialect()))
81 return mlir::WalkResult::interrupt();
82 return mlir::WalkResult::advance();
93static bool isNonReturningTerminator(mlir::Operation *op) {
94 return mlir::isa_and_nonnull<cir::UnreachableOp, cir::TrapOp>(op);
112static mlir::LogicalResult
113rewriteRegionExitToContinue(mlir::PatternRewriter &rewriter,
114 mlir::Region ®ion, mlir::Block *continueBlock,
115 llvm::StringRef regionDescription) {
116 mlir::Operation *terminator = region.back().getTerminator();
117 rewriter.setInsertionPointToEnd(®ion.back());
118 if (
auto yieldOp = mlir::dyn_cast<cir::YieldOp>(terminator)) {
119 rewriter.replaceOpWithNewOp<cir::BrOp>(
120 yieldOp, yieldOp.getArgs(),
nullptr,
nullptr,
122 return mlir::success();
124 if (isNonReturningTerminator(terminator))
125 return mlir::success();
126 terminator->emitError(
"unexpected terminator in ")
128 <<
" region, expected yield, unreachable, or trap, got: "
129 << terminator->getName();
130 return mlir::failure();
133struct CIRFlattenCFGPass :
public impl::CIRFlattenCFGBase<CIRFlattenCFGPass> {
135 CIRFlattenCFGPass() =
default;
136 void runOnOperation()
override;
139struct CIRIfFlattening :
public mlir::OpRewritePattern<cir::IfOp> {
140 using OpRewritePattern<IfOp>::OpRewritePattern;
143 matchAndRewrite(cir::IfOp ifOp,
144 mlir::PatternRewriter &rewriter)
const override {
145 mlir::OpBuilder::InsertionGuard guard(rewriter);
146 mlir::Location loc = ifOp.getLoc();
147 bool emptyElse = ifOp.getElseRegion().empty();
148 mlir::Block *currentBlock = rewriter.getInsertionBlock();
149 mlir::Block *remainingOpsBlock =
150 rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
151 mlir::Block *continueBlock;
152 if (ifOp->getResults().empty())
153 continueBlock = remainingOpsBlock;
155 llvm_unreachable(
"NYI");
158 mlir::Block *thenBeforeBody = &ifOp.getThenRegion().front();
159 mlir::Block *thenAfterBody = &ifOp.getThenRegion().back();
160 rewriter.inlineRegionBefore(ifOp.getThenRegion(), continueBlock);
162 rewriter.setInsertionPointToEnd(thenAfterBody);
163 if (
auto thenYieldOp =
164 dyn_cast<cir::YieldOp>(thenAfterBody->getTerminator())) {
165 rewriter.replaceOpWithNewOp<cir::BrOp>(
166 thenYieldOp, thenYieldOp.getArgs(),
167 nullptr,
nullptr, continueBlock);
170 rewriter.setInsertionPointToEnd(continueBlock);
173 mlir::Block *elseBeforeBody =
nullptr;
174 mlir::Block *elseAfterBody =
nullptr;
176 elseBeforeBody = &ifOp.getElseRegion().front();
177 elseAfterBody = &ifOp.getElseRegion().back();
178 rewriter.inlineRegionBefore(ifOp.getElseRegion(), continueBlock);
180 elseBeforeBody = elseAfterBody = continueBlock;
183 rewriter.setInsertionPointToEnd(currentBlock);
184 cir::BrCondOp::create(rewriter, loc, ifOp.getCondition(), thenBeforeBody,
188 rewriter.setInsertionPointToEnd(elseAfterBody);
189 if (
auto elseYieldOP =
190 dyn_cast<cir::YieldOp>(elseAfterBody->getTerminator())) {
191 rewriter.replaceOpWithNewOp<cir::BrOp>(
192 elseYieldOP, elseYieldOP.getArgs(),
nullptr,
193 nullptr, continueBlock);
197 rewriter.replaceOp(ifOp, continueBlock->getArguments());
198 return mlir::success();
202class CIRScopeOpFlattening :
public mlir::OpRewritePattern<cir::ScopeOp> {
204 using OpRewritePattern<cir::ScopeOp>::OpRewritePattern;
207 matchAndRewrite(cir::ScopeOp scopeOp,
208 mlir::PatternRewriter &rewriter)
const override {
209 mlir::OpBuilder::InsertionGuard guard(rewriter);
210 mlir::Location loc = scopeOp.getLoc();
218 if (scopeOp.isEmpty()) {
219 rewriter.eraseOp(scopeOp);
220 return mlir::success();
225 mlir::Block *currentBlock = rewriter.getInsertionBlock();
226 mlir::Block *continueBlock =
227 rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
228 if (scopeOp.getNumResults() > 0)
229 continueBlock->addArguments(scopeOp.getResultTypes(), loc);
232 mlir::Block *beforeBody = &scopeOp.getScopeRegion().front();
233 mlir::Block *afterBody = &scopeOp.getScopeRegion().back();
234 rewriter.inlineRegionBefore(scopeOp.getScopeRegion(), continueBlock);
237 rewriter.setInsertionPointToEnd(currentBlock);
239 cir::BrOp::create(rewriter, loc, mlir::ValueRange(),
nullptr,
240 nullptr, beforeBody);
244 rewriter.setInsertionPointToEnd(afterBody);
245 if (
auto yieldOp = dyn_cast<cir::YieldOp>(afterBody->getTerminator())) {
246 rewriter.replaceOpWithNewOp<cir::BrOp>(
247 yieldOp, yieldOp.getArgs(),
248 nullptr,
nullptr, continueBlock);
252 rewriter.replaceOp(scopeOp, continueBlock->getArguments());
254 return mlir::success();
258class CIRSwitchOpFlattening :
public mlir::OpRewritePattern<cir::SwitchOp> {
260 using OpRewritePattern<cir::SwitchOp>::OpRewritePattern;
262 inline void rewriteYieldOp(mlir::PatternRewriter &rewriter,
263 cir::YieldOp yieldOp,
264 mlir::Block *destination)
const {
265 rewriter.setInsertionPoint(yieldOp);
266 rewriter.replaceOpWithNewOp<cir::BrOp>(yieldOp, yieldOp.getOperands(),
268 nullptr, destination);
272 Block *condBrToRangeDestination(cir::SwitchOp op,
273 mlir::PatternRewriter &rewriter,
274 mlir::Block *rangeDestination,
275 mlir::Block *defaultDestination,
276 const APInt &lowerBound,
277 const APInt &upperBound)
const {
278 auto condType = mlir::cast<cir::IntType>(op.getCondition().getType());
279 bool isSigned = condType.isSigned();
281 (isSigned ? lowerBound.sle(upperBound) : lowerBound.ule(upperBound)) &&
283 mlir::Block *resBlock = rewriter.createBlock(defaultDestination);
289 cir::IntType uIntType =
290 cir::IntType::get(op.getContext(), condType.getWidth(),
293 cir::ConstantOp lowerBoundValue = cir::ConstantOp::create(
294 rewriter, op.getLoc(), cir::IntAttr::get(condType, lowerBound));
295 mlir::Value diffValue = cir::SubOp::create(
296 rewriter, op.getLoc(), op.getCondition(), lowerBoundValue);
304 diffValue = cir::CastOp::create(rewriter, op.getLoc(), uIntType,
305 CastKind::integral, diffValue);
307 cir::ConstantOp rangeLength = cir::ConstantOp::create(
308 rewriter, op.getLoc(),
309 cir::IntAttr::get(uIntType, upperBound - lowerBound));
311 cir::CmpOp cmpResult = cir::CmpOp::create(
312 rewriter, op.getLoc(), cir::CmpOpKind::le, diffValue, rangeLength);
313 cir::BrCondOp::create(rewriter, op.getLoc(), cmpResult, rangeDestination,
319 matchAndRewrite(cir::SwitchOp op,
320 mlir::PatternRewriter &rewriter)
const override {
325 for (mlir::Region ®ion : op->getRegions())
326 if (hasNestedOpsToFlatten(region))
327 return mlir::failure();
330 if (op.getBody().hasOneBlock() &&
331 op.getBody().front().without_terminator().empty()) {
332 rewriter.eraseOp(op);
333 return mlir::success();
336 llvm::SmallVector<CaseOp> cases;
337 op.collectCases(cases);
340 mlir::Block *exitBlock = rewriter.splitBlock(
341 rewriter.getBlock(), op->getNextNode()->getIterator());
354 walkRegionSkipping<cir::LoopOpInterface, cir::SwitchOp>(
355 op.getBody(), [&](mlir::Operation *op) {
356 if (!isa<cir::BreakOp>(op))
357 return mlir::WalkResult::advance();
359 lowerTerminator(op, exitBlock, rewriter);
360 return mlir::WalkResult::skip();
366 cir::YieldOp switchYield =
nullptr;
368 for (mlir::Block &block :
369 llvm::make_early_inc_range(op.getBody().getBlocks()))
370 if (
auto yieldOp = dyn_cast<cir::YieldOp>(block.getTerminator()))
371 switchYield = yieldOp;
373 assert(!op.getBody().empty());
374 mlir::Block *originalBlock = op->getBlock();
375 mlir::Block *swopBlock =
376 rewriter.splitBlock(originalBlock, op->getIterator());
377 rewriter.inlineRegionBefore(op.getBody(), exitBlock);
380 rewriteYieldOp(rewriter, switchYield, exitBlock);
382 rewriter.setInsertionPointToEnd(originalBlock);
383 cir::BrOp::create(rewriter, op.getLoc(), swopBlock);
388 llvm::SmallVector<mlir::APInt, 8> caseValues;
389 llvm::SmallVector<mlir::Block *, 8> caseDestinations;
390 llvm::SmallVector<mlir::ValueRange, 8> caseOperands;
392 llvm::SmallVector<std::pair<APInt, APInt>> rangeValues;
393 llvm::SmallVector<mlir::Block *> rangeDestinations;
394 llvm::SmallVector<mlir::ValueRange> rangeOperands;
397 mlir::Block *defaultDestination = exitBlock;
398 mlir::ValueRange defaultOperands = exitBlock->getArguments();
401 for (cir::CaseOp caseOp : cases) {
402 mlir::Region ®ion = caseOp.getCaseRegion();
405 switch (caseOp.getKind()) {
406 case cir::CaseOpKind::Default:
407 defaultDestination = ®ion.front();
408 defaultOperands = defaultDestination->getArguments();
410 case cir::CaseOpKind::Range:
411 assert(caseOp.getValue().size() == 2 &&
412 "Case range should have 2 case value");
413 rangeValues.push_back(
414 {cast<cir::IntAttr>(caseOp.getValue()[0]).getValue(),
415 cast<cir::IntAttr>(caseOp.getValue()[1]).getValue()});
416 rangeDestinations.push_back(®ion.front());
417 rangeOperands.push_back(rangeDestinations.back()->getArguments());
419 case cir::CaseOpKind::Anyof:
420 case cir::CaseOpKind::Equal:
422 for (
const mlir::Attribute &value : caseOp.getValue()) {
423 caseValues.push_back(cast<cir::IntAttr>(value).getValue());
424 caseDestinations.push_back(®ion.front());
425 caseOperands.push_back(caseDestinations.back()->getArguments());
431 for (mlir::Block &blk : region.getBlocks()) {
432 if (blk.getNumSuccessors())
435 if (
auto yieldOp = dyn_cast<cir::YieldOp>(blk.getTerminator())) {
436 mlir::Operation *nextOp = caseOp->getNextNode();
437 assert(nextOp &&
"caseOp is not expected to be the last op");
438 mlir::Block *oldBlock = nextOp->getBlock();
439 mlir::Block *newBlock =
440 rewriter.splitBlock(oldBlock, nextOp->getIterator());
441 rewriter.setInsertionPointToEnd(oldBlock);
442 cir::BrOp::create(rewriter, nextOp->getLoc(), mlir::ValueRange(),
445 rewriteYieldOp(rewriter, yieldOp, newBlock);
449 mlir::Block *oldBlock = caseOp->getBlock();
450 mlir::Block *newBlock =
451 rewriter.splitBlock(oldBlock, caseOp->getIterator());
453 mlir::Block &entryBlock = caseOp.getCaseRegion().front();
454 rewriter.inlineRegionBefore(caseOp.getCaseRegion(), newBlock);
457 rewriter.setInsertionPointToEnd(oldBlock);
458 cir::BrOp::create(rewriter, caseOp.getLoc(), &entryBlock);
462 for (cir::CaseOp caseOp : cases) {
463 mlir::Block *caseBlock = caseOp->getBlock();
466 if (caseBlock->hasNoPredecessors())
467 rewriter.eraseBlock(caseBlock);
469 rewriter.eraseOp(caseOp);
473 mlir::cast<cir::IntType>(op.getCondition().getType()).isSigned();
474 for (
auto [rangeVal, operand, destination] :
475 llvm::zip(rangeValues, rangeOperands, rangeDestinations)) {
476 APInt lowerBound = rangeVal.first;
477 APInt upperBound = rangeVal.second;
480 if (isSigned ? lowerBound.sgt(upperBound) : lowerBound.ugt(upperBound))
485 constexpr uint64_t kSmallRangeThreshold = 64;
486 APInt rangeSize = upperBound - lowerBound;
487 if (rangeSize.ult(kSmallRangeThreshold)) {
494 APInt caseValue = lowerBound;
495 for (
uint64_t n = rangeSize.getZExtValue() + 1; n != 0; --n) {
496 caseValues.push_back(caseValue++);
497 caseOperands.push_back(operand);
498 caseDestinations.push_back(destination);
504 condBrToRangeDestination(op, rewriter, destination,
505 defaultDestination, lowerBound, upperBound);
506 defaultOperands = operand;
510 rewriter.setInsertionPoint(op);
511 rewriter.replaceOpWithNewOp<cir::SwitchFlatOp>(
512 op, op.getCondition(), defaultDestination, defaultOperands, caseValues,
513 caseDestinations, caseOperands);
515 return mlir::success();
519class CIRLoopOpInterfaceFlattening
520 :
public mlir::OpInterfaceRewritePattern<cir::LoopOpInterface> {
522 using mlir::OpInterfaceRewritePattern<
523 cir::LoopOpInterface>::OpInterfaceRewritePattern;
525 inline void lowerConditionOp(cir::ConditionOp op, mlir::Block *body,
527 mlir::PatternRewriter &rewriter,
528 mlir::DistinctAttr loopId = {},
529 cir::LoopHintAttr loopHints = {})
const {
530 mlir::OpBuilder::InsertionGuard guard(rewriter);
531 rewriter.setInsertionPoint(op);
532 rewriter.replaceOpWithNewOp<cir::BrCondOp>(
533 op, op.getCondition(), mlir::ValueRange{}, mlir::ValueRange{}, loopId,
534 loopHints, body, exit);
571 rewriteLoopWithCleanup(cir::LoopOpInterface op,
572 mlir::PatternRewriter &rewriter)
const {
573 mlir::Location loc = op.getLoc();
574 mlir::Region *stepRegion = op.maybeGetStep();
576 cir::CleanupKindAttr cleanupKind = op.maybeGetCleanupKind();
577 assert(cleanupKind &&
"loop cleanup region without a cleanup kind");
579 mlir::Region &condRegion = op.getCond();
580 mlir::Region &bodyRegion = op.getBody();
581 mlir::Region &cleanupRegion = *op.maybeGetCleanup();
587 cast<cir::ConditionOp>(condRegion.back().getTerminator());
588 mlir::Value condVal = conditionOp.getCondition();
593 mlir::Block *bodyFront = &bodyRegion.front();
594 mlir::Block *stepFront = stepRegion ? &stepRegion->front() :
nullptr;
599 llvm::SmallVector<cir::YieldOp> bodyYieldsToStep;
600 llvm::SmallVector<cir::ContinueOp> continuesToStep;
602 for (mlir::Block &blk : bodyRegion.getBlocks())
603 if (
auto y = dyn_cast<cir::YieldOp>(blk.getTerminator()))
604 bodyYieldsToStep.push_back(y);
605 op.walkBodySkippingNestedLoops([&](mlir::Operation *o) {
606 if (
auto c = dyn_cast<cir::ContinueOp>(o)) {
607 continuesToStep.push_back(c);
608 return mlir::WalkResult::skip();
610 return mlir::WalkResult::advance();
616 rewriter.inlineRegionBefore(bodyRegion, condRegion, condRegion.end());
618 rewriter.inlineRegionBefore(*stepRegion, condRegion, condRegion.end());
622 mlir::Block *breakBlock =
623 rewriter.createBlock(&condRegion, condRegion.end());
624 rewriter.setInsertionPointToEnd(breakBlock);
625 cir::BreakOp::create(rewriter, conditionOp.getLoc());
627 rewriter.setInsertionPoint(conditionOp);
628 rewriter.replaceOpWithNewOp<cir::BrCondOp>(conditionOp, condVal, bodyFront,
633 for (cir::YieldOp y : bodyYieldsToStep)
634 lowerTerminator(y, stepFront, rewriter);
635 for (cir::ContinueOp c : continuesToStep)
636 lowerTerminator(c, stepFront, rewriter);
640 mlir::Block *newBodyBlock = rewriter.createBlock(&bodyRegion);
641 rewriter.setInsertionPointToEnd(newBodyBlock);
642 auto emitYield = [](mlir::OpBuilder &b, mlir::Location l) {
643 cir::YieldOp::create(b, l);
645 auto scope = cir::CleanupScopeOp::create(
646 rewriter, loc, cleanupKind.getValue(), emitYield, emitYield);
647 cir::YieldOp::create(rewriter, loc);
652 mlir::Block *bodyPlaceholder = &scope.getBodyRegion().front();
653 rewriter.inlineRegionBefore(condRegion, bodyPlaceholder);
654 rewriter.eraseBlock(bodyPlaceholder);
656 mlir::Block *cleanupPlaceholder = &scope.getCleanupRegion().front();
657 rewriter.inlineRegionBefore(cleanupRegion, cleanupPlaceholder);
658 rewriter.eraseBlock(cleanupPlaceholder);
661 mlir::Block *newCondBlock = rewriter.createBlock(&condRegion);
662 rewriter.setInsertionPointToEnd(newCondBlock);
663 mlir::Value trueVal = cir::ConstantOp::create(
664 rewriter, loc, cir::BoolAttr::get(rewriter.getContext(),
true));
665 cir::ConditionOp::create(rewriter, loc, trueVal);
669 mlir::Block *newStepBlock = rewriter.createBlock(stepRegion);
670 rewriter.setInsertionPointToEnd(newStepBlock);
671 cir::YieldOp::create(rewriter, loc);
677 if (
auto whileOp = mlir::dyn_cast<cir::WhileOp>(op.getOperation()))
678 whileOp.removeCleanupKindAttr();
679 else if (
auto forOp = mlir::dyn_cast<cir::ForOp>(op.getOperation()))
680 forOp.removeCleanupKindAttr();
682 return mlir::success();
686 matchAndRewrite(cir::LoopOpInterface op,
687 mlir::PatternRewriter &rewriter)
const final {
692 for (mlir::Region ®ion : op->getRegions())
693 if (hasNestedOpsToFlatten(region))
694 return mlir::failure();
704 if (op.maybeGetCleanup())
705 return rewriteLoopWithCleanup(op, rewriter);
708 mlir::Block *entry = rewriter.getInsertionBlock();
710 rewriter.splitBlock(entry, rewriter.getInsertionPoint());
711 mlir::Block *cond = &op.getCond().front();
712 mlir::Block *body = &op.getBody().front();
714 (op.maybeGetStep() ? &op.maybeGetStep()->front() :
nullptr);
717 mlir::Block *firstBlock = &op.getEntry().front();
718 rewriter.setInsertionPointToEnd(entry);
719 cir::BrOp::create(rewriter, op.getLoc(), firstBlock);
725 cir::LoopHintAttr loopHints = op.getLoopHintsAttr();
726 mlir::DistinctAttr loopId = op.getLoopIdAttr();
727 auto idFor = [&](mlir::Block *target) {
728 return target == firstBlock ? loopId : mlir::DistinctAttr{};
730 auto hintsFor = [&](mlir::Block *target) {
731 return target == firstBlock ? loopHints : cir::LoopHintAttr{};
739 cast<cir::ConditionOp>(op.getCond().back().getTerminator());
740 lowerConditionOp(conditionOp, body, exit, rewriter, idFor(body),
748 mlir::Block *dest = (
step ?
step : cond);
749 op.walkBodySkippingNestedLoops([&](mlir::Operation *op) {
750 if (!isa<cir::ContinueOp>(op))
751 return mlir::WalkResult::advance();
753 lowerTerminator(op, dest, rewriter, idFor(dest), hintsFor(dest));
754 return mlir::WalkResult::skip();
758 walkRegionSkipping<cir::LoopOpInterface, cir::SwitchOp>(
759 op.getBody(), [&](mlir::Operation *op) {
760 if (!isa<cir::BreakOp>(op))
761 return mlir::WalkResult::advance();
763 lowerTerminator(op, exit, rewriter);
764 return mlir::WalkResult::skip();
768 for (mlir::Block &blk : op.getBody().getBlocks()) {
769 auto bodyYield = dyn_cast<cir::YieldOp>(blk.getTerminator());
771 lowerTerminator(bodyYield, dest, rewriter, idFor(dest), hintsFor(dest));
779 cast<cir::YieldOp>(op.maybeGetStep()->back().getTerminator()), cond,
780 rewriter, idFor(cond), hintsFor(cond));
783 rewriter.inlineRegionBefore(op.getCond(), exit);
784 rewriter.inlineRegionBefore(op.getBody(), exit);
786 rewriter.inlineRegionBefore(*op.maybeGetStep(), exit);
788 rewriter.eraseOp(op);
789 return mlir::success();
793class CIRTernaryOpFlattening :
public mlir::OpRewritePattern<cir::TernaryOp> {
795 using OpRewritePattern<cir::TernaryOp>::OpRewritePattern;
798 matchAndRewrite(cir::TernaryOp op,
799 mlir::PatternRewriter &rewriter)
const override {
800 Location loc = op->getLoc();
801 Block *condBlock = rewriter.getInsertionBlock();
802 Block::iterator opPosition = rewriter.getInsertionPoint();
803 Block *remainingOpsBlock = rewriter.splitBlock(condBlock, opPosition);
804 llvm::SmallVector<mlir::Location, 2> locs;
807 if (op->getResultTypes().size())
809 Block *continueBlock =
810 rewriter.createBlock(remainingOpsBlock, op->getResultTypes(), locs);
811 cir::BrOp::create(rewriter, loc, remainingOpsBlock);
813 Region &trueRegion = op.getTrueRegion();
814 Block *trueBlock = &trueRegion.front();
819 if (failed(rewriteRegionExitToContinue(rewriter, trueRegion, continueBlock,
821 return mlir::success();
822 rewriter.inlineRegionBefore(trueRegion, continueBlock);
824 Block *falseBlock = continueBlock;
825 Region &falseRegion = op.getFalseRegion();
827 falseBlock = &falseRegion.front();
828 if (failed(rewriteRegionExitToContinue(rewriter, falseRegion, continueBlock,
830 return mlir::success();
831 rewriter.inlineRegionBefore(falseRegion, continueBlock);
833 rewriter.setInsertionPointToEnd(condBlock);
834 cir::BrCondOp::create(rewriter, loc, op.getCond(), trueBlock, falseBlock);
836 rewriter.replaceOp(op, continueBlock->getArguments());
839 return mlir::success();
846static cir::AllocaOp getOrCreateCleanupDestSlot(cir::FuncOp funcOp,
847 mlir::PatternRewriter &rewriter,
848 mlir::Location loc) {
849 mlir::Block &entryBlock = funcOp.getBody().front();
852 auto it = llvm::find_if(entryBlock, [](
auto &op) {
853 return mlir::isa<AllocaOp>(&op) &&
854 mlir::cast<AllocaOp>(&op).getCleanupDestSlot();
856 if (it != entryBlock.end())
857 return mlir::cast<cir::AllocaOp>(*it);
860 mlir::OpBuilder::InsertionGuard guard(rewriter);
861 rewriter.setInsertionPointToStart(&entryBlock);
862 cir::IntType s32Type =
863 cir::IntType::get(rewriter.getContext(), 32,
true);
865 cir::PointerType ptrToS32Type = cir::PointerType::get(
866 s32Type, dataLayout.getAllocaAddrSpace(rewriter.getContext()));
867 uint64_t alignment = dataLayout.getAlignment(s32Type,
true).value();
868 auto allocaOp = cir::AllocaOp::create(
869 rewriter, loc, ptrToS32Type,
"__cleanup_dest_slot",
870 rewriter.getI64IntegerAttr(alignment));
871 allocaOp.setCleanupDestSlot(
true);
881static bool isLifetimeMarkerOnly(mlir::Region ®ion) {
882 return llvm::hasSingleElement(region) &&
885 [](mlir::Operation &op) { return isa<cir::LifetimeEndOp>(op); }) &&
886 llvm::all_of(region.front(), [](mlir::Operation &op) {
887 return isa<cir::LifetimeEndOp, cir::YieldOp>(op);
894static bool hasEnclosingEHRequirement(mlir::Operation *op) {
895 for (mlir::Region *region = op->getParentRegion(); region;
896 region = region->getParentRegion()) {
897 mlir::Operation *parent = region->getParentOp();
898 if (!parent || isa<cir::FuncOp>(parent))
900 if (
auto tryOp = dyn_cast<cir::TryOp>(parent)) {
901 auto handlers = tryOp.getHandlerTypesAttr();
902 if (region == &tryOp.getTryRegion() && handlers &&
903 llvm::any_of(handlers, [](mlir::Attribute handler) {
904 return !isa<cir::UnwindAttr>(handler);
907 }
else if (
auto cleanupOp = dyn_cast<cir::CleanupScopeOp>(parent)) {
908 if (region == &cleanupOp.getBodyRegion() &&
909 cleanupOp.getCleanupKindAttr().isEH() &&
910 !isLifetimeMarkerOnly(cleanupOp.getCleanupRegion()))
912 }
else if (
auto loopOp = dyn_cast<cir::LoopOpInterface>(parent)) {
914 mlir::Region *
cleanup = loopOp.maybeGetCleanup();
915 if (cleanup && region != cleanup && loopOp.maybeGetCleanupKind().isEH() &&
916 !isLifetimeMarkerOnly(*cleanup))
928collectThrowingCalls(mlir::Region ®ion,
930 region.walk([&](cir::CallOp callOp) {
934 if (!callOp.getNothrow() && !callOp.getMusttail())
935 callsToRewrite.push_back(callOp);
945collectThrows(mlir::Region ®ion,
948 [&](cir::ThrowOp throwOp) { throwsToRewrite.push_back(throwOp); });
957static void collectResumeOps(mlir::Region ®ion,
959 region.walk([&](cir::ResumeOp resumeOp) { resumeOps.push_back(resumeOp); });
965static mlir::Block *buildUnwindBlock(mlir::Block *dest,
bool isCleanupOnly,
967 mlir::Block *insertBefore,
968 mlir::PatternRewriter &rewriter) {
969 mlir::Block *unwindBlock = rewriter.createBlock(insertBefore);
970 rewriter.setInsertionPointToEnd(unwindBlock);
972 cir::EhInitiateOp::create(rewriter, loc, isCleanupOnly);
973 cir::BrOp::create(rewriter, loc, mlir::ValueRange{ehInitiate.getEhToken()},
974 nullptr,
nullptr, dest);
981static mlir::Block *buildTerminateUnwindBlock(mlir::Location loc,
982 mlir::Block *insertBefore,
983 mlir::PatternRewriter &rewriter) {
984 mlir::Block *terminateBlock = rewriter.createBlock(insertBefore);
985 rewriter.setInsertionPointToEnd(terminateBlock);
986 auto ehInitiate = cir::EhInitiateOp::create(rewriter, loc,
false);
987 cir::EhTerminateOp::create(rewriter, loc, ehInitiate.getEhToken());
988 return terminateBlock;
991class CIRCleanupScopeOpFlattening
992 :
public mlir::OpRewritePattern<cir::CleanupScopeOp> {
994 using OpRewritePattern<cir::CleanupScopeOp>::OpRewritePattern;
999 mlir::Operation *exitOp;
1005 CleanupExit(mlir::Operation *op,
int id) : exitOp(op), destinationId(id) {}
1015 static bool gotoTargetsLabelInRegion(cir::GotoOp gotoOp,
1016 mlir::Region ®ion) {
1017 llvm::StringRef targetLabel = gotoOp.getLabel();
1019 .walk([&](cir::LabelOp labelOp) {
1020 if (labelOp.getLabel() == targetLabel)
1021 return mlir::WalkResult::interrupt();
1022 return mlir::WalkResult::advance();
1050 void collectExits(mlir::Region &cleanupBodyRegion,
1051 llvm::SmallVectorImpl<CleanupExit> &exits,
1052 int &nextId)
const {
1056 for (mlir::Block &block : cleanupBodyRegion) {
1057 auto *terminator = block.getTerminator();
1058 if (isa<cir::YieldOp>(terminator))
1059 exits.emplace_back(terminator, nextId++);
1066 auto isGotoThatExitsCleanup = [&](mlir::Operation *op) {
1067 auto gotoOp = dyn_cast<cir::GotoOp>(op);
1068 return gotoOp && !gotoTargetsLabelInRegion(gotoOp, cleanupBodyRegion);
1077 auto isReturnThatExitsCleanup = [](mlir::Operation *op) {
1078 if (!isa<cir::ReturnOp>(op))
1080 auto callOp = dyn_cast_if_present<cir::CallOp>(op->getPrevNode());
1081 return !callOp || !callOp.getMusttail();
1088 auto collectExitsInLoop = [&](mlir::Operation *loopOp) {
1089 loopOp->walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *nestedOp) {
1090 if (isa<cir::CoroCleanupOp>(nestedOp) ||
1091 isReturnThatExitsCleanup(nestedOp) ||
1092 isGotoThatExitsCleanup(nestedOp)) {
1093 exits.emplace_back(nestedOp, nextId++);
1095 return mlir::WalkResult::advance();
1100 std::function<void(mlir::Region &,
bool)> collectExitsInCleanup;
1101 std::function<void(mlir::Operation *)> collectExitsInSwitch;
1105 collectExitsInSwitch = [&](mlir::Operation *switchOp) {
1106 switchOp->walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *nestedOp) {
1107 if (isa<cir::CleanupScopeOp>(nestedOp)) {
1110 collectExitsInCleanup(
1111 cast<cir::CleanupScopeOp>(nestedOp).getBodyRegion(),
1113 return mlir::WalkResult::skip();
1114 }
else if (isa<cir::LoopOpInterface>(nestedOp)) {
1115 collectExitsInLoop(nestedOp);
1116 return mlir::WalkResult::skip();
1117 }
else if (isa<cir::ContinueOp, cir::CoReturnOp, cir::CoroCleanupOp>(
1119 isReturnThatExitsCleanup(nestedOp) ||
1120 isGotoThatExitsCleanup(nestedOp)) {
1121 exits.emplace_back(nestedOp, nextId++);
1123 return mlir::WalkResult::advance();
1130 collectExitsInCleanup = [&](mlir::Region ®ion,
bool ignoreBreak) {
1131 region.walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
1138 if (!ignoreBreak && isa<cir::BreakOp>(op)) {
1139 exits.emplace_back(op, nextId++);
1140 }
else if (isa<cir::ContinueOp, cir::CoReturnOp, cir::CoroCleanupOp>(
1142 isReturnThatExitsCleanup(op) || isGotoThatExitsCleanup(op)) {
1143 exits.emplace_back(op, nextId++);
1144 }
else if (isa<cir::CleanupScopeOp>(op)) {
1146 collectExitsInCleanup(cast<cir::CleanupScopeOp>(op).getBodyRegion(),
1148 return mlir::WalkResult::skip();
1149 }
else if (isa<cir::LoopOpInterface>(op)) {
1153 collectExitsInLoop(op);
1154 return mlir::WalkResult::skip();
1155 }
else if (isa<cir::SwitchOp>(op)) {
1159 collectExitsInSwitch(op);
1160 return mlir::WalkResult::skip();
1162 return mlir::WalkResult::advance();
1167 collectExitsInCleanup(cleanupBodyRegion,
false);
1173 static bool slotMayChangeBeforeCleanupEnd(cir::AllocaOp alloca,
1175 mlir::Region &cleanupRegion) {
1176 mlir::Block *loadBlock = loadOp->getBlock();
1177 return llvm::any_of(alloca->getUsers(), [&](mlir::Operation *user) {
1179 if (mlir::isa<cir::LoadOp>(user))
1184 if (auto storeOp = mlir::dyn_cast<cir::StoreOp>(user)) {
1185 if (storeOp.getValue() == alloca.getResult())
1187 }
else if (!mlir::isa<cir::LifetimeStartOp, cir::LifetimeEndOp>(user)) {
1192 if (cleanupRegion.isAncestor(user->getParentRegion()))
1194 mlir::Operation *userInBlock = loadBlock->findAncestorOpInBlock(*user);
1195 return userInBlock && loadOp->isBeforeInBlock(userInBlock);
1203 static bool shouldSinkReturnOperand(mlir::Value operand,
1204 cir::ReturnOp returnOp,
1205 mlir::Region &cleanupRegion) {
1207 mlir::Operation *defOp = operand.getDefiningOp();
1213 if (!mlir::isa<cir::ConstantOp, cir::LoadOp>(defOp))
1217 if (!operand.hasOneUse())
1221 if (defOp->getBlock() != returnOp->getBlock())
1224 if (
auto loadOp = mlir::dyn_cast<cir::LoadOp>(defOp)) {
1226 if (loadOp.isVolatileOrAtomic())
1230 mlir::Value ptr = loadOp.getAddr();
1231 auto funcOp = returnOp->getParentOfType<cir::FuncOp>();
1232 assert(funcOp &&
"Return op has no function parent?");
1233 mlir::Block &funcEntryBlock = funcOp.getBody().front();
1238 mlir::dyn_cast_if_present<cir::AllocaOp>(ptr.getDefiningOp());
1239 return allocaOp && allocaOp->getBlock() == &funcEntryBlock &&
1240 !slotMayChangeBeforeCleanupEnd(allocaOp, loadOp, cleanupRegion);
1244 assert(mlir::isa<cir::ConstantOp>(defOp) &&
"Expected constant op");
1252 void getReturnOpOperands(
1253 cir::ReturnOp returnOp, mlir::Operation *exitOp, mlir::Location loc,
1254 const llvm::SmallPtrSetImpl<mlir::Operation *> &sinkableOperands,
1255 mlir::PatternRewriter &rewriter,
1257 mlir::Block *destBlock = rewriter.getInsertionBlock();
1258 auto funcOp = exitOp->getParentOfType<cir::FuncOp>();
1259 assert(funcOp &&
"Return op has no function parent?");
1260 mlir::Block &funcEntryBlock = funcOp.getBody().front();
1262 for (mlir::Value operand : returnOp.getOperands()) {
1263 if (sinkableOperands.contains(operand.getDefiningOp())) {
1265 mlir::Operation *defOp = operand.getDefiningOp();
1266 rewriter.moveOpBefore(defOp, destBlock, destBlock->end());
1267 returnValues.push_back(operand);
1270 cir::AllocaOp alloca;
1272 mlir::OpBuilder::InsertionGuard guard(rewriter);
1273 rewriter.setInsertionPointToStart(&funcEntryBlock);
1275 funcOp->getParentOfType<mlir::ModuleOp>());
1277 dataLayout.getAlignment(operand.getType(),
true).value();
1278 cir::PointerType ptrType = cir::PointerType::get(
1280 dataLayout.getAllocaAddrSpace(rewriter.getContext()));
1282 cir::AllocaOp::create(rewriter, loc, ptrType,
"__ret_operand_tmp",
1283 rewriter.getI64IntegerAttr(alignment));
1288 mlir::OpBuilder::InsertionGuard guard(rewriter);
1289 rewriter.setInsertionPoint(exitOp);
1290 cir::StoreOp::create(rewriter, loc, operand, alloca,
1293 mlir::IntegerAttr(),
1294 cir::SyncScopeKindAttr(), cir::MemOrderAttr());
1298 rewriter.setInsertionPointToEnd(destBlock);
1300 cir::LoadOp::create(rewriter, loc, alloca,
false,
1302 mlir::IntegerAttr(),
1303 cir::SyncScopeKindAttr(), cir::MemOrderAttr(),
1305 returnValues.push_back(loaded);
1314 mlir::LogicalResult createExitTerminator(
1315 mlir::Operation *exitOp, mlir::Location loc, mlir::Block *continueBlock,
1316 const llvm::SmallPtrSetImpl<mlir::Operation *> &sinkableOperands,
1317 mlir::PatternRewriter &rewriter)
const {
1318 return llvm::TypeSwitch<mlir::Operation *, mlir::LogicalResult>(exitOp)
1319 .Case<cir::YieldOp>([&](
auto) {
1321 cir::BrOp::create(rewriter, loc, continueBlock);
1322 return mlir::success();
1324 .Case<cir::BreakOp>([&](
auto) {
1326 cir::BreakOp::create(rewriter, loc);
1327 return mlir::success();
1329 .Case<cir::ContinueOp>([&](
auto) {
1331 cir::ContinueOp::create(rewriter, loc);
1332 return mlir::success();
1334 .Case<cir::CoReturnOp>([&](
auto) {
1338 cir::CoReturnOp::create(rewriter, loc);
1339 return mlir::success();
1341 .Case<cir::CoroCleanupOp>([&](
auto) {
1344 cir::CoroCleanupOp::create(rewriter, loc);
1345 return mlir::success();
1347 .Case<cir::ReturnOp>([&](
auto returnOp) {
1351 if (returnOp.hasOperand()) {
1353 getReturnOpOperands(returnOp, exitOp, loc, sinkableOperands,
1354 rewriter, returnValues);
1355 cir::ReturnOp::create(rewriter, loc, returnValues);
1357 cir::ReturnOp::create(rewriter, loc);
1359 return mlir::success();
1361 .Case<cir::GotoOp>([&](
auto gotoOp) {
1366 cir::GotoOp::create(rewriter, loc, gotoOp.getLabel());
1367 return mlir::success();
1369 .
Default([&](mlir::Operation *op) {
1370 cir::UnreachableOp::create(rewriter, loc);
1371 return op->emitError(
1372 "unexpected exit operation in cleanup scope body");
1378 static bool regionExitsOnlyFromLastBlock(mlir::Region ®ion) {
1379 for (mlir::Block &block : region) {
1380 if (&block == ®ion.back())
1382 bool expectedTerminator =
1383 llvm::TypeSwitch<mlir::Operation *, bool>(block.getTerminator())
1390 .Case<cir::YieldOp, cir::ReturnOp, cir::ResumeFlatOp,
1391 cir::ContinueOp, cir::BreakOp, cir::GotoOp>(
1392 [](
auto) {
return false; })
1401 .Case<cir::TryCallOp>([](
auto) {
return false; })
1405 .Case<cir::EhDispatchOp>([](
auto) {
return false; })
1409 .Case<cir::SwitchFlatOp>([](
auto) {
return false; })
1412 .Case<cir::UnreachableOp, cir::TrapOp>([](
auto) {
return true; })
1414 .Case<cir::IndirectBrOp>([](
auto) {
return false; })
1417 .Case<cir::BrOp>([&](cir::BrOp brOp) {
1418 assert(brOp.getDest()->getParent() == ®ion &&
1419 "branch destination is not in the region");
1422 .Case<cir::BrCondOp>([&](cir::BrCondOp brCondOp) {
1423 assert(brCondOp.getDestTrue()->getParent() == ®ion &&
1424 "branch destination is not in the region");
1425 assert(brCondOp.getDestFalse()->getParent() == ®ion &&
1426 "branch destination is not in the region");
1430 .
Default([](mlir::Operation *) ->
bool {
1431 llvm_unreachable(
"unexpected terminator in cleanup region");
1433 if (!expectedTerminator)
1461 mlir::Block *buildEHCleanupBlocks(cir::CleanupScopeOp cleanupOp,
1463 mlir::Block *insertBefore,
1464 mlir::PatternRewriter &rewriter)
const {
1465 assert(regionExitsOnlyFromLastBlock(cleanupOp.getCleanupRegion()) &&
1466 "cleanup region has exits in non-final blocks");
1470 mlir::Block *blockBeforeClone =
insertBefore->getPrevNode();
1473 rewriter.cloneRegionBefore(cleanupOp.getCleanupRegion(), insertBefore);
1476 mlir::Block *clonedEntry = blockBeforeClone
1477 ? blockBeforeClone->getNextNode()
1482 auto ehTokenType = cir::EhTokenType::get(rewriter.getContext());
1483 mlir::Value ehToken = clonedEntry->addArgument(ehTokenType, loc);
1485 rewriter.setInsertionPointToStart(clonedEntry);
1486 auto beginCleanup = cir::BeginCleanupOp::create(rewriter, loc, ehToken);
1490 mlir::Block *lastClonedBlock =
insertBefore->getPrevNode();
1492 mlir::dyn_cast<cir::YieldOp>(lastClonedBlock->getTerminator());
1494 rewriter.setInsertionPoint(yieldOp);
1495 cir::EndCleanupOp::create(rewriter, loc, beginCleanup.getCleanupToken());
1496 rewriter.replaceOpWithNewOp<cir::ResumeOp>(yieldOp, ehToken);
1498 cleanupOp->emitError(
"Not yet implemented: cleanup region terminated "
1499 "with non-yield operation");
1528 flattenCleanup(cir::CleanupScopeOp cleanupOp,
1533 mlir::PatternRewriter &rewriter)
const {
1534 mlir::Location loc = cleanupOp.getLoc();
1535 cir::CleanupKindAttr cleanupKind = cleanupOp.getCleanupKindAttr();
1536 bool hasNormalCleanup = cleanupKind.isNormal();
1537 bool hasEHCleanup = cleanupKind.isEH();
1538 bool isMultiExit = exits.size() > 1;
1545 bool emitNormalCleanup = hasNormalCleanup && !exits.empty();
1548 mlir::Block *bodyEntry = &cleanupOp.getBodyRegion().front();
1549 mlir::Block *cleanupEntry = &cleanupOp.getCleanupRegion().front();
1550 mlir::Block *cleanupExit = &cleanupOp.getCleanupRegion().back();
1551 assert(regionExitsOnlyFromLastBlock(cleanupOp.getCleanupRegion()) &&
1552 "cleanup region has exits in non-final blocks");
1553 auto cleanupYield = dyn_cast<cir::YieldOp>(cleanupExit->getTerminator());
1554 if (!cleanupYield) {
1555 return rewriter.notifyMatchFailure(cleanupOp,
1556 "Not yet implemented: cleanup region "
1557 "terminated with non-yield operation");
1564 cir::AllocaOp destSlot;
1565 if (isMultiExit && emitNormalCleanup) {
1566 auto funcOp = cleanupOp->getParentOfType<cir::FuncOp>();
1568 return cleanupOp->emitError(
"cleanup scope not inside a function");
1569 destSlot = getOrCreateCleanupDestSlot(funcOp, rewriter, loc);
1575 if (emitNormalCleanup) {
1576 for (
const CleanupExit &exit : exits) {
1577 auto returnOp = dyn_cast<cir::ReturnOp>(exit.exitOp);
1580 for (mlir::Value operand : returnOp.getOperands())
1581 if (shouldSinkReturnOperand(operand, returnOp,
1582 cleanupOp.getCleanupRegion()))
1583 sinkableOperands.insert(operand.getDefiningOp());
1588 mlir::Block *currentBlock = rewriter.getInsertionBlock();
1589 mlir::Block *continueBlock =
1590 rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
1600 mlir::Block *unwindBlock =
nullptr;
1601 mlir::Block *ehCleanupEntry =
nullptr;
1602 if (hasEHCleanup && (!callsToRewrite.empty() || !throwsToRewrite.empty() ||
1603 !resumeOpsToChain.empty())) {
1605 buildEHCleanupBlocks(cleanupOp, loc, continueBlock, rewriter);
1609 if (!callsToRewrite.empty() || !throwsToRewrite.empty())
1610 unwindBlock = buildUnwindBlock(ehCleanupEntry,
true,
1611 loc, ehCleanupEntry, rewriter);
1618 mlir::Block *normalInsertPt =
1619 unwindBlock ? unwindBlock
1620 : (ehCleanupEntry ? ehCleanupEntry : continueBlock);
1623 rewriter.inlineRegionBefore(cleanupOp.getBodyRegion(), normalInsertPt);
1626 if (emitNormalCleanup)
1627 rewriter.inlineRegionBefore(cleanupOp.getCleanupRegion(), normalInsertPt);
1630 rewriter.setInsertionPointToEnd(currentBlock);
1631 cir::BrOp::create(rewriter, loc, bodyEntry);
1634 mlir::LogicalResult result = mlir::success();
1635 if (emitNormalCleanup) {
1637 mlir::Block *exitBlock = rewriter.createBlock(normalInsertPt);
1640 rewriter.setInsertionPoint(cleanupYield);
1641 rewriter.replaceOpWithNewOp<cir::BrOp>(cleanupYield, exitBlock);
1645 rewriter.setInsertionPointToEnd(exitBlock);
1649 cir::LoadOp::create(rewriter, loc, destSlot,
false,
1651 mlir::IntegerAttr(),
1652 cir::SyncScopeKindAttr(), cir::MemOrderAttr(),
1659 cir::IntType s32Type =
1660 cir::IntType::get(rewriter.getContext(), 32,
true);
1662 for (
const CleanupExit &exit : exits) {
1664 mlir::Block *destBlock = rewriter.createBlock(normalInsertPt);
1665 rewriter.setInsertionPointToEnd(destBlock);
1666 result = createExitTerminator(exit.exitOp, loc, continueBlock,
1667 sinkableOperands, rewriter);
1670 caseValues.push_back(
1671 llvm::APInt(32,
static_cast<uint64_t>(exit.destinationId),
true));
1672 caseDestinations.push_back(destBlock);
1673 caseOperands.push_back(mlir::ValueRange());
1677 rewriter.setInsertionPoint(exit.exitOp);
1678 auto destIdConst = cir::ConstantOp::create(
1679 rewriter, loc, cir::IntAttr::get(s32Type, exit.destinationId));
1680 cir::StoreOp::create(rewriter, loc, destIdConst, destSlot,
1683 mlir::IntegerAttr(),
1684 cir::SyncScopeKindAttr(), cir::MemOrderAttr());
1685 rewriter.replaceOpWithNewOp<cir::BrOp>(exit.exitOp, cleanupEntry);
1693 if (result.failed())
1698 mlir::Block *defaultBlock = rewriter.createBlock(normalInsertPt);
1699 rewriter.setInsertionPointToEnd(defaultBlock);
1700 cir::UnreachableOp::create(rewriter, loc);
1703 rewriter.setInsertionPointToEnd(exitBlock);
1704 cir::SwitchFlatOp::create(rewriter, loc, slotValue, defaultBlock,
1705 mlir::ValueRange(), caseValues,
1706 caseDestinations, caseOperands);
1710 rewriter.setInsertionPointToEnd(exitBlock);
1711 mlir::Operation *exitOp = exits[0].exitOp;
1712 result = createExitTerminator(exitOp, loc, continueBlock,
1713 sinkableOperands, rewriter);
1716 rewriter.setInsertionPoint(exitOp);
1717 rewriter.replaceOpWithNewOp<cir::BrOp>(exitOp, cleanupEntry);
1722 for (CleanupExit &exit : exits) {
1723 if (isa<cir::YieldOp>(exit.exitOp)) {
1724 rewriter.setInsertionPoint(exit.exitOp);
1725 rewriter.replaceOpWithNewOp<cir::BrOp>(exit.exitOp, continueBlock);
1736 for (cir::CallOp callOp : callsToRewrite)
1738 for (cir::ThrowOp throwOp : throwsToRewrite)
1748 if (ehCleanupEntry) {
1751 for (mlir::Block *block = ehCleanupEntry; block != continueBlock;
1752 block = block->getNextNode()) {
1753 block->walk([&](mlir::Operation *op) {
1754 if (
auto callOp = mlir::dyn_cast<cir::CallOp>(op)) {
1755 if (!callOp.getNothrow())
1756 ehCleanupThrowingCalls.push_back(callOp);
1757 }
else if (
auto throwOp = mlir::dyn_cast<cir::ThrowOp>(op)) {
1758 ehCleanupThrows.push_back(throwOp);
1762 if (!ehCleanupThrowingCalls.empty() || !ehCleanupThrows.empty()) {
1763 mlir::Block *terminateBlock =
1764 buildTerminateUnwindBlock(loc, continueBlock, rewriter);
1765 for (cir::CallOp callOp : ehCleanupThrowingCalls)
1767 for (cir::ThrowOp throwOp : ehCleanupThrows)
1777 if (ehCleanupEntry) {
1778 for (cir::ResumeOp resumeOp : resumeOpsToChain) {
1779 mlir::Value ehToken = resumeOp.getEhToken();
1780 rewriter.setInsertionPoint(resumeOp);
1781 rewriter.replaceOpWithNewOp<cir::BrOp>(
1782 resumeOp, mlir::ValueRange{ehToken},
nullptr,
1783 nullptr, ehCleanupEntry);
1788 rewriter.eraseOp(cleanupOp);
1793 return mlir::success();
1797 matchAndRewrite(cir::CleanupScopeOp cleanupOp,
1798 mlir::PatternRewriter &rewriter)
const override {
1799 mlir::OpBuilder::InsertionGuard guard(rewriter);
1814 cleanupOp.getBodyRegion().walk([&](cir::CleanupScopeOp nested) {
1815 if (mlir::isOpTriviallyDead(nested))
1816 deadNestedOps.push_back(nested);
1818 for (
auto op : deadNestedOps)
1819 rewriter.eraseOp(op);
1821 if (hasNestedOpsToFlatten(cleanupOp.getBodyRegion()))
1822 return mlir::failure();
1824 bool hasEHCleanup = cleanupOp.getCleanupKindAttr().isEH();
1829 collectExits(cleanupOp.getBodyRegion(), exits, nextId);
1834 bool hasMustTailCall =
false;
1835 cleanupOp.getBodyRegion().walk(
1836 [&](cir::CallOp callOp) { hasMustTailCall |= callOp.getMusttail(); });
1837 assert((!exits.empty() || hasMustTailCall) &&
1838 "cleanup scope body has no exit");
1846 if (hasEHCleanup && (!isLifetimeMarkerOnly(cleanupOp.getCleanupRegion()) ||
1847 hasEnclosingEHRequirement(cleanupOp))) {
1848 collectThrowingCalls(cleanupOp.getBodyRegion(), callsToRewrite);
1849 collectThrows(cleanupOp.getBodyRegion(), throwsToRewrite);
1857 collectResumeOps(cleanupOp.getBodyRegion(), resumeOpsToChain);
1859 return flattenCleanup(cleanupOp, exits, callsToRewrite, throwsToRewrite,
1860 resumeOpsToChain, rewriter);
1867static cir::EhInitiateOp traceToEhInitiate(mlir::Value ehToken) {
1869 if (
auto initiate = ehToken.getDefiningOp<cir::EhInitiateOp>())
1871 auto blockArg = mlir::dyn_cast<mlir::BlockArgument>(ehToken);
1874 mlir::Block *pred = blockArg.getOwner()->getSinglePredecessor();
1877 auto brOp = mlir::dyn_cast<cir::BrOp>(pred->getTerminator());
1880 ehToken = brOp.getDestOperands()[blockArg.getArgNumber()];
1885class CIRTryOpFlattening :
public mlir::OpRewritePattern<cir::TryOp> {
1887 using OpRewritePattern<cir::TryOp>::OpRewritePattern;
1892 mlir::Block *buildCatchDispatchBlock(
1893 cir::TryOp tryOp, mlir::ArrayAttr handlerTypes,
1894 llvm::SmallVectorImpl<mlir::Block *> &catchHandlerBlocks,
1895 mlir::Location loc, mlir::Block *insertBefore,
1896 mlir::PatternRewriter &rewriter)
const {
1897 mlir::Block *dispatchBlock = rewriter.createBlock(insertBefore);
1898 auto ehTokenType = cir::EhTokenType::get(rewriter.getContext());
1899 mlir::Value ehToken = dispatchBlock->addArgument(ehTokenType, loc);
1901 rewriter.setInsertionPointToEnd(dispatchBlock);
1904 llvm::SmallVector<mlir::Attribute> catchTypeAttrs;
1905 llvm::SmallVector<mlir::Block *> catchDests;
1906 mlir::Block *defaultDest =
nullptr;
1907 bool defaultIsCatchAll =
false;
1913 cir::EhFilterAttr filterAttr;
1914 mlir::Block *filterUnwindDest =
nullptr;
1915 mlir::Block *filterClauseDest =
nullptr;
1917 for (
auto zipped : llvm::zip(handlerTypes, catchHandlerBlocks)) {
1918 mlir::Attribute typeAttr = std::get<0>(zipped);
1919 mlir::Block *handlerBlock = std::get<1>(zipped);
1920 llvm::TypeSwitch<mlir::Attribute>(typeAttr)
1921 .Case<cir::CatchAllAttr>([&](
auto) {
1922 assert(!defaultDest &&
"multiple catch_all or unwind handlers");
1923 defaultDest = handlerBlock;
1924 defaultIsCatchAll =
true;
1926 .Case<cir::UnwindAttr>([&](
auto) {
1927 assert(!defaultDest &&
"multiple catch_all or unwind handlers");
1928 defaultDest = handlerBlock;
1929 defaultIsCatchAll =
false;
1931 .Case<cir::EhFilterAttr>([&](cir::EhFilterAttr ehFilter) {
1932 assert(!filterAttr &&
"multiple filter handlers");
1933 filterAttr = ehFilter;
1934 filterUnwindDest = handlerBlock;
1936 .Case<cir::EhUnexpectedAttr>([&](
auto) {
1937 assert(!filterClauseDest &&
"multiple unexpected handlers");
1938 filterClauseDest = handlerBlock;
1940 .
Default([&](mlir::Attribute attr) {
1942 catchTypeAttrs.push_back(attr);
1943 catchDests.push_back(handlerBlock);
1948 assert(filterUnwindDest && filterClauseDest &&
1949 "filter handler requires an unexpected handler");
1950 assert(!defaultDest &&
1951 "filter handler cannot share a dispatch with catch_all or unwind");
1952 catchTypeAttrs.push_back(filterAttr);
1953 catchDests.push_back(filterClauseDest);
1954 defaultDest = filterUnwindDest;
1955 defaultIsCatchAll =
false;
1958 assert(defaultDest &&
"dispatch must have a catch_all or unwind handler");
1960 mlir::ArrayAttr catchTypesArrayAttr;
1961 if (!catchTypeAttrs.empty())
1962 catchTypesArrayAttr = rewriter.getArrayAttr(catchTypeAttrs);
1964 cir::EhDispatchOp::create(rewriter, loc, ehToken, catchTypesArrayAttr,
1965 defaultIsCatchAll, defaultDest, catchDests);
1967 return dispatchBlock;
1984 mlir::Block *flattenCatchHandler(mlir::Region &handlerRegion,
1985 mlir::Block *continueBlock,
1987 mlir::Block *insertBefore,
1988 mlir::PatternRewriter &rewriter)
const {
1990 mlir::Block *handlerEntry = &handlerRegion.front();
1993 rewriter.inlineRegionBefore(handlerRegion, insertBefore);
1996 for (mlir::Block &block : llvm::make_range(handlerEntry->getIterator(),
1998 if (
auto yieldOp = dyn_cast<cir::YieldOp>(block.getTerminator())) {
2011 if (mlir::Operation *prev = yieldOp->getPrevNode())
2012 return isa<cir::EndCatchOp>(prev);
2013 llvm::SmallPtrSet<mlir::Block *, 8> visited;
2014 llvm::SmallVector<mlir::Block *, 4> worklist;
2015 for (mlir::Block *pred : block.getPredecessors())
2016 worklist.push_back(pred);
2017 while (!worklist.empty()) {
2018 mlir::Block *b = worklist.pop_back_val();
2019 if (!visited.insert(b).second)
2021 mlir::Operation *term = b->getTerminator();
2022 if (mlir::Operation *prev = term->getPrevNode()) {
2023 if (isa<cir::EndCatchOp>(prev))
2026 for (mlir::Block *pred : b->getPredecessors())
2027 worklist.push_back(pred);
2031 "expected end_catch reachable before yield "
2032 "in catch handler");
2033 rewriter.setInsertionPoint(yieldOp);
2034 rewriter.replaceOpWithNewOp<cir::BrOp>(yieldOp, continueBlock);
2038 return handlerEntry;
2047 mlir::Block *flattenUnwindHandler(mlir::Region &unwindRegion,
2049 mlir::Block *insertBefore,
2050 mlir::PatternRewriter &rewriter)
const {
2051 mlir::Block *unwindEntry = &unwindRegion.front();
2052 rewriter.inlineRegionBefore(unwindRegion, insertBefore);
2057 matchAndRewrite(cir::TryOp tryOp,
2058 mlir::PatternRewriter &rewriter)
const override {
2065 for (mlir::Region ®ion : tryOp->getRegions())
2066 if (hasNestedOpsToFlatten(region))
2067 return mlir::failure();
2069 mlir::OpBuilder::InsertionGuard guard(rewriter);
2070 mlir::Location loc = tryOp.getLoc();
2072 mlir::ArrayAttr handlerTypes = tryOp.getHandlerTypesAttr();
2073 mlir::MutableArrayRef<mlir::Region> handlerRegions =
2074 tryOp.getHandlerRegions();
2077 llvm::SmallVector<cir::CallOp> callsToRewrite;
2078 collectThrowingCalls(tryOp.getTryRegion(), callsToRewrite);
2079 llvm::SmallVector<cir::ThrowOp> throwsToRewrite;
2080 collectThrows(tryOp.getTryRegion(), throwsToRewrite);
2083 llvm::SmallVector<cir::ResumeOp> resumeOpsToChain;
2084 collectResumeOps(tryOp.getTryRegion(), resumeOpsToChain);
2087 mlir::Block *currentBlock = rewriter.getInsertionBlock();
2088 mlir::Block *continueBlock =
2089 rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
2092 mlir::Block *bodyEntry = &tryOp.getTryRegion().front();
2093 mlir::Block *bodyExit = &tryOp.getTryRegion().back();
2096 rewriter.inlineRegionBefore(tryOp.getTryRegion(), continueBlock);
2099 rewriter.setInsertionPointToEnd(currentBlock);
2100 cir::BrOp::create(rewriter, loc, bodyEntry);
2103 if (
auto bodyYield = dyn_cast<cir::YieldOp>(bodyExit->getTerminator())) {
2104 rewriter.setInsertionPoint(bodyYield);
2105 rewriter.replaceOpWithNewOp<cir::BrOp>(bodyYield, continueBlock);
2109 if (!handlerTypes || handlerTypes.empty()) {
2110 rewriter.eraseOp(tryOp);
2111 return mlir::success();
2119 if (callsToRewrite.empty() && throwsToRewrite.empty() &&
2120 resumeOpsToChain.empty()) {
2121 for (mlir::Region &handlerRegion : handlerRegions)
2122 for (mlir::Block &block : handlerRegion)
2123 block.dropAllDefinedValueUses();
2124 rewriter.eraseOp(tryOp);
2125 return mlir::success();
2131 llvm::SmallVector<mlir::Block *> catchHandlerBlocks;
2133 for (
const auto &[idx, typeAttr] : llvm::enumerate(handlerTypes)) {
2134 mlir::Region &handlerRegion = handlerRegions[idx];
2136 if (mlir::isa<cir::UnwindAttr, cir::EhFilterAttr, cir::EhUnexpectedAttr>(
2138 mlir::Block *unwindEntry =
2139 flattenUnwindHandler(handlerRegion, loc, continueBlock, rewriter);
2140 catchHandlerBlocks.push_back(unwindEntry);
2142 mlir::Block *handlerEntry = flattenCatchHandler(
2143 handlerRegion, continueBlock, loc, continueBlock, rewriter);
2144 catchHandlerBlocks.push_back(handlerEntry);
2149 mlir::Block *dispatchBlock =
2150 buildCatchDispatchBlock(tryOp, handlerTypes, catchHandlerBlocks, loc,
2151 catchHandlerBlocks.front(), rewriter);
2162 handlerTypes && llvm::any_of(handlerTypes, [](mlir::Attribute attr) {
2163 return mlir::isa<cir::CatchAllAttr>(attr);
2172 bool isCleanupOnly = tryOp.getCleanup() && !hasCatchAll;
2173 if (!callsToRewrite.empty() || !throwsToRewrite.empty()) {
2175 mlir::Block *unwindBlock = buildUnwindBlock(dispatchBlock, isCleanupOnly,
2176 loc, dispatchBlock, rewriter);
2178 for (cir::CallOp callOp : callsToRewrite)
2180 for (cir::ThrowOp throwOp : throwsToRewrite)
2187 for (cir::ResumeOp resumeOp : resumeOpsToChain) {
2192 if (
auto ehInitiate = traceToEhInitiate(resumeOp.getEhToken())) {
2193 rewriter.modifyOpInPlace(ehInitiate,
2194 [&] { ehInitiate.removeCleanupAttr(); });
2198 mlir::Value ehToken = resumeOp.getEhToken();
2199 rewriter.setInsertionPoint(resumeOp);
2200 rewriter.replaceOpWithNewOp<cir::BrOp>(
2201 resumeOp, mlir::ValueRange{ehToken},
nullptr,
2202 nullptr, dispatchBlock);
2206 rewriter.eraseOp(tryOp);
2208 return mlir::success();
2213collectCoReturnsOps(mlir::Region ®ion,
2216 [&](cir::CoReturnOp coReturnOp) { coReturnOps.push_back(coReturnOp); });
2234class CIRCoroutineFlattening :
public mlir::OpRewritePattern<cir::CoroutineOp> {
2238 template <
class PlaceholderOp>
2240 collectAwaitPlaceholders(cir::CoroutineOp coroOp,
2241 llvm::SmallVectorImpl<PlaceholderOp> &ops)
const {
2242 auto collect = [&](PlaceholderOp op) { ops.push_back(op); };
2243 coroOp.getInitialSuspend().walk(collect);
2244 coroOp.getBody().walk(collect);
2245 coroOp.getFinalSuspend().walk(collect);
2249 void replaceYieldWithBr(mlir::PatternRewriter &rewriter, mlir::Region ®ion,
2250 mlir::Block *dest)
const {
2251 auto yieldOp = cast<cir::YieldOp>(region.back().getTerminator());
2252 rewriter.setInsertionPoint(yieldOp);
2253 rewriter.replaceOpWithNewOp<cir::BrOp>(yieldOp, dest, yieldOp.getArgs());
2258 void inlineInitialSuspend(mlir::PatternRewriter &rewriter,
2259 cir::CoroutineOp coroOp, mlir::Block *insertBefore,
2260 mlir::Block *beforeBody)
const {
2261 mlir::Region &initialRegion = coroOp.getInitialSuspend();
2262 replaceYieldWithBr(rewriter, initialRegion, beforeBody);
2263 rewriter.inlineRegionBefore(initialRegion, insertBefore);
2269 void inlineBody(mlir::PatternRewriter &rewriter, cir::CoroutineOp coroOp,
2270 mlir::Block *insertBefore, mlir::Block *beforeFinal)
const {
2271 mlir::Region &bodyRegion = coroOp.getBody();
2273 llvm::SmallVector<cir::CoReturnOp> coReturnsOps;
2274 collectCoReturnsOps(bodyRegion, coReturnsOps);
2276 mlir::Operation *bodyTerminator = bodyRegion.back().getTerminator();
2277 if (
auto bodyYield = dyn_cast<cir::YieldOp>(bodyTerminator)) {
2278 rewriter.setInsertionPoint(bodyYield);
2279 rewriter.replaceOpWithNewOp<cir::BrOp>(bodyYield, beforeFinal,
2280 mlir::ValueRange{});
2283 for (
auto &coReturn : coReturnsOps) {
2284 rewriter.setInsertionPoint(coReturn);
2285 rewriter.replaceOpWithNewOp<cir::BrOp>(coReturn, beforeFinal,
2286 mlir::ValueRange{});
2289 rewriter.inlineRegionBefore(bodyRegion, insertBefore);
2294 void inlineFinalSuspend(mlir::PatternRewriter &rewriter,
2295 cir::CoroutineOp coroOp, mlir::Block *insertBefore,
2296 mlir::Block *beforeDestroy)
const {
2297 mlir::Region &finalRegion = coroOp.getFinalSuspend();
2298 replaceYieldWithBr(rewriter, finalRegion, beforeDestroy);
2299 rewriter.inlineRegionBefore(finalRegion, insertBefore);
2304 void inlineDestroy(mlir::PatternRewriter &rewriter, cir::CoroutineOp coroOp,
2305 mlir::Block *insertBefore, mlir::Block *beforeExit)
const {
2306 mlir::Region &destroyRegion = coroOp.getDestroy();
2307 replaceYieldWithBr(rewriter, destroyRegion, beforeExit);
2308 rewriter.inlineRegionBefore(destroyRegion, insertBefore);
2312 void inlineExit(mlir::PatternRewriter &rewriter, cir::CoroutineOp coroOp,
2313 mlir::Block *insertBefore)
const {
2314 rewriter.inlineRegionBefore(coroOp.getExit(), insertBefore);
2319 void lowerCoroExits(mlir::PatternRewriter &rewriter,
2320 llvm::ArrayRef<cir::CoroExitOp> coroExitsOps,
2321 mlir::Block *beforeExit)
const {
2322 for (cir::CoroExitOp coroExit : coroExitsOps) {
2326 rewriter.setInsertionPoint(coroExit);
2327 rewriter.replaceOpWithNewOp<cir::BrOp>(coroExit, beforeExit,
2328 mlir::ValueRange{});
2336 void lowerCoroCleanups(mlir::PatternRewriter &rewriter,
2337 llvm::ArrayRef<cir::CoroCleanupOp> coroCleanupOps,
2338 mlir::Block *beforeDestroy)
const {
2339 for (cir::CoroCleanupOp coroCleanup : coroCleanupOps) {
2340 rewriter.setInsertionPoint(coroCleanup);
2341 rewriter.replaceOpWithNewOp<cir::BrOp>(coroCleanup, beforeDestroy,
2342 mlir::ValueRange{});
2347 using OpRewritePattern<cir::CoroutineOp>::OpRewritePattern;
2350 matchAndRewrite(cir::CoroutineOp coroOp,
2351 mlir::PatternRewriter &rewriter)
const override {
2354 for (mlir::Region ®ion : coroOp->getRegions())
2355 if (hasNestedOpsToFlatten(region))
2356 return mlir::failure();
2361 llvm::SmallVector<cir::CoroExitOp> coroExitsOps;
2362 collectAwaitPlaceholders(coroOp, coroExitsOps);
2363 llvm::SmallVector<cir::CoroCleanupOp> coroCleanupOps;
2364 collectAwaitPlaceholders(coroOp, coroCleanupOps);
2367 mlir::Block *beforeInitial = &coroOp.getInitialSuspend().front();
2368 mlir::Block *beforeBody = &coroOp.getBody().front();
2369 mlir::Block *beforeFinal = &coroOp.getFinalSuspend().front();
2370 mlir::Block *beforeDestroy = &coroOp.getDestroy().front();
2371 mlir::Block *beforeExit = &coroOp.getExit().front();
2373 mlir::Block *coroBlock = rewriter.getInsertionBlock();
2376 mlir::Block *remainingOpsBlock =
2377 rewriter.splitBlock(coroBlock, rewriter.getInsertionPoint());
2379 lowerCoroExits(rewriter, coroExitsOps, beforeExit);
2380 lowerCoroCleanups(rewriter, coroCleanupOps, beforeDestroy);
2382 inlineInitialSuspend(rewriter, coroOp, remainingOpsBlock, beforeBody);
2383 inlineBody(rewriter, coroOp, remainingOpsBlock, beforeFinal);
2384 inlineFinalSuspend(rewriter, coroOp, remainingOpsBlock, beforeDestroy);
2385 inlineDestroy(rewriter, coroOp, remainingOpsBlock, beforeExit);
2386 inlineExit(rewriter, coroOp, remainingOpsBlock);
2388 rewriter.setInsertionPointToEnd(coroBlock);
2389 cir::BrOp::create(rewriter, coroOp.getLoc(), beforeInitial,
2390 mlir::ValueRange{});
2392 auto func = coroOp->getParentOfType<cir::FuncOp>();
2396 func.setCoroutineKind(cir::CoroutineKind::FlattenedCoroutine);
2398 rewriter.eraseOp(coroOp);
2399 return mlir::success();
2403class CIRAwaitOpFlattening :
public mlir::OpRewritePattern<cir::AwaitOp> {
2408 void flattenReadyRegion(mlir::PatternRewriter &rewriter, cir::AwaitOp awaitOp,
2409 mlir::Block *resumeEntry, mlir::Block *suspendEntry,
2410 mlir::Block *remainingOpsBlock)
const {
2411 mlir::Region &readyRegion = awaitOp.getReady();
2413 cast<cir::ConditionOp>(readyRegion.back().getTerminator());
2414 rewriter.setInsertionPoint(conditionOp);
2415 rewriter.replaceOpWithNewOp<cir::BrCondOp>(
2416 conditionOp, conditionOp.getCondition(), resumeEntry, suspendEntry);
2417 rewriter.inlineRegionBefore(readyRegion, remainingOpsBlock);
2425 void flattenSuspendRegion(mlir::PatternRewriter &rewriter,
2426 cir::AwaitOp awaitOp, mlir::Block *resumeEntry,
2427 mlir::Block *remainingOpsBlock)
const {
2428 mlir::Region &suspendRegion = awaitOp.getSuspend();
2430 cast<cir::CoroSuspendPoint>(suspendRegion.back().getTerminator());
2431 cir::CoroSuspendOp coroSuspendIntri =
2432 emitCoroSuspend(rewriter, awaitOp, suspendPoint);
2436 rewriter.inlineRegionBefore(suspendRegion, remainingOpsBlock);
2438 mlir::Location loc = awaitOp.getLoc();
2439 mlir::Block *cleanupBlock =
2440 createDestroyBlock(rewriter, loc, remainingOpsBlock);
2441 mlir::Block *retBlock =
2442 createSuspendedBlock(rewriter, loc, remainingOpsBlock);
2445 llvm::SmallVector<mlir::APInt> caseValues{mlir::APInt(8, 0),
2447 llvm::SmallVector<mlir::Block *> caseDestinations{resumeEntry,
2449 llvm::SmallVector<mlir::ValueRange> caseOperands{caseValues.size()};
2453 rewriter.setInsertionPoint(suspendPoint);
2454 rewriter.replaceOpWithNewOp<cir::SwitchFlatOp>(
2455 suspendPoint, coroSuspendIntri.getResult(), retBlock,
2456 mlir::ValueRange{}, caseValues, caseDestinations, caseOperands);
2461 cir::CoroSuspendOp emitCoroSuspend(mlir::PatternRewriter &rewriter,
2462 cir::AwaitOp awaitOp,
2463 cir::CoroSuspendPoint suspendPoint)
const {
2464 mlir::Location loc = awaitOp.getLoc();
2468 rewriter.setInsertionPointToStart(&awaitOp.getSuspend().front());
2473 auto voidPtrTy = cir::PointerType::get(cir::VoidType::get(getContext()));
2474 auto nullPtr = cir::ConstantOp::create(
2476 cir::ConstPtrAttr::get(voidPtrTy, rewriter.getI64IntegerAttr(0)));
2477 auto coroSave = cir::CoroSaveOp::create(rewriter, loc, nullPtr);
2478 rewriter.setInsertionPoint(suspendPoint);
2479 if (suspendPoint.getCond() !=
nullptr) {
2480 auto *oldinsertpoint = rewriter.getInsertionBlock();
2481 mlir::Block *suspendBlock = rewriter.splitBlock(
2482 rewriter.getInsertionBlock(), rewriter.getInsertionPoint());
2483 mlir::OpBuilder::InsertionGuard guard(rewriter);
2484 rewriter.setInsertionPointToEnd(oldinsertpoint);
2485 cir::BrCondOp::create(rewriter, loc, suspendPoint.getCond(), suspendBlock,
2486 &awaitOp.getResume().front(), mlir::ValueRange{},
2487 mlir::ValueRange{});
2489 rewriter.setInsertionPoint(suspendPoint);
2495 bool isFinalSuspend = awaitOp.getKind() == cir::AwaitKind::Final;
2496 auto isFinalCoroSuspend = cir::ConstantOp::create(
2497 rewriter, loc, cir::BoolAttr::get(getContext(), isFinalSuspend));
2503 return cir::CoroSuspendOp::create(
2505 mlir::ValueRange{coroSave.getResult(), isFinalCoroSuspend});
2515 mlir::Block *createDestroyBlock(mlir::PatternRewriter &rewriter,
2517 mlir::Block *insertBefore)
const {
2518 mlir::OpBuilder::InsertionGuard guard(rewriter);
2519 mlir::Block *cleanupBlock = rewriter.createBlock(insertBefore);
2520 cir::CoroCleanupOp::create(rewriter, loc);
2521 return cleanupBlock;
2526 mlir::Block *createSuspendedBlock(mlir::PatternRewriter &rewriter,
2528 mlir::Block *insertBefore)
const {
2529 mlir::OpBuilder::InsertionGuard guard(rewriter);
2531 mlir::Block *retBlock = rewriter.createBlock(insertBefore);
2532 cir::CoroExitOp::create(rewriter, loc);
2536 void flattenResumeRegion(mlir::PatternRewriter &rewriter,
2537 cir::AwaitOp awaitOp,
2538 mlir::Block *remainingOpsBlock)
const {
2539 mlir::Region &resumeRegion = awaitOp.getResume();
2540 auto resumeYield = cast<cir::YieldOp>(resumeRegion.back().getTerminator());
2541 rewriter.setInsertionPoint(resumeYield);
2544 rewriter.replaceOpWithNewOp<cir::BrOp>(resumeYield, remainingOpsBlock);
2545 rewriter.inlineRegionBefore(resumeRegion, remainingOpsBlock);
2549 using OpRewritePattern<cir::AwaitOp>::OpRewritePattern;
2573 matchAndRewrite(cir::AwaitOp awaitOp,
2574 mlir::PatternRewriter &rewriter)
const override {
2578 for (mlir::Region ®ion : awaitOp->getRegions())
2579 if (hasNestedOpsToFlatten(region))
2580 return mlir::failure();
2582 mlir::Block *awaitBlock = rewriter.getInsertionBlock();
2585 mlir::Block *remainingOpsBlock =
2586 rewriter.splitBlock(awaitBlock, rewriter.getInsertionPoint());
2589 mlir::Block *readyEntry = &awaitOp.getReady().front();
2590 mlir::Block *suspendEntry = &awaitOp.getSuspend().front();
2591 mlir::Block *resumeEntry = &awaitOp.getResume().front();
2593 flattenReadyRegion(rewriter, awaitOp, resumeEntry, suspendEntry,
2598 rewriter.setInsertionPointToEnd(awaitBlock);
2599 cir::BrOp::create(rewriter, awaitOp.getLoc(), readyEntry);
2601 flattenSuspendRegion(rewriter, awaitOp, resumeEntry, remainingOpsBlock);
2602 flattenResumeRegion(rewriter, awaitOp, remainingOpsBlock);
2604 rewriter.eraseOp(awaitOp);
2605 return mlir::success();
2609void populateFlattenCFGPatterns(RewritePatternSet &patterns) {
2611 .add<CIRIfFlattening, CIRLoopOpInterfaceFlattening, CIRScopeOpFlattening,
2612 CIRSwitchOpFlattening, CIRTernaryOpFlattening,
2613 CIRCleanupScopeOpFlattening, CIRTryOpFlattening,
2614 CIRAwaitOpFlattening, CIRCoroutineFlattening>(patterns.getContext());
2622class MLIRChangedListener final :
public mlir::RewriterBase::Listener {
2623 bool hasChanged =
false;
2626 void reset() { hasChanged =
false; }
2628 bool changed()
const {
return hasChanged; }
2630 void notifyBlockErased(Block *)
override { hasChanged =
true; }
2631 void notifyOperationModified(Operation *)
override { hasChanged =
true; }
2632 void notifyOperationReplaced(Operation *, Operation *)
override {
2635 void notifyOperationReplaced(Operation *, ValueRange)
override {
2638 void notifyOperationErased(Operation *)
override { hasChanged =
true; }
2642 void notifyOperationInserted(Operation *,
2643 mlir::IRRewriter::InsertPoint)
override {
2646 void notifyBlockInserted(Block *, Region *, Region::iterator)
override {
2652void CIRFlattenCFGPass::runOnOperation() {
2653 RewritePatternSet patternList(&getContext());
2654 populateFlattenCFGPatterns(patternList);
2655 FrozenRewritePatternSet patterns(std::move(patternList));
2657 PatternApplicator applicator(patterns);
2660 applicator.applyDefaultCostModel();
2662 mlir::PatternRewriter rewriter(&getContext());
2663 MLIRChangedListener changedListener;
2664 rewriter.setListener(&changedListener);
2667 changedListener.reset();
2674 llvm::SmallVector<Operation *, 16> ops;
2675 getOperation()->walk<mlir::WalkOrder::PostOrder>([&](Operation *op) {
2676 if (isa<IfOp, ScopeOp, SwitchOp, LoopOpInterface, TernaryOp,
2677 CleanupScopeOp, TryOp, AwaitOp, CoroutineOp>(op))
2681 for (mlir::Operation *op : ops) {
2682 rewriter.setInsertionPoint(op);
2683 (void)applicator.matchAndRewrite(op, rewriter);
2685 }
while (changedListener.changed());
2693 return std::make_unique<CIRFlattenCFGPass>();
mlir::Block * replaceThrowWithTryThrow(cir::ThrowOp throwOp, mlir::Block *unwindDest, mlir::Location loc, mlir::RewriterBase &rewriter)
Replace a cir::ThrowOp with a cir::TryThrowOp whose unwind destination is unwindDest.
mlir::Block * replaceCallWithTryCall(cir::CallOp callOp, mlir::Block *unwindDest, mlir::Location loc, mlir::RewriterBase &rewriter)
Replace a cir::CallOp with a cir::TryCallOp whose unwind destination is unwindDest.
@ Default
Set to the current date and time.
std::unique_ptr< Pass > createCIRFlattenCFGPass()
int const char * function
float __ovld __cnfn step(float, float)
Returns 0.0 if x < edge, otherwise it returns 1.0.
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t uint64_t __builtin_riscv_ssha_i32 __builtin_riscv_sshl_u32 uint64_t
static bool stackSaveOp()
static bool coroGetRetObjManager()
static bool coroUnwindRegion()