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 assert(op->hasTrait<mlir::OpTrait::IsTerminator>() &&
"not a terminator");
44 mlir::OpBuilder::InsertionGuard guard(rewriter);
45 rewriter.setInsertionPoint(op);
46 rewriter.replaceOpWithNewOp<cir::BrOp>(op, dest);
51template <
typename... Ops>
52void walkRegionSkipping(
54 mlir::function_ref<mlir::WalkResult(mlir::Operation *)> callback) {
55 region.walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
57 return mlir::WalkResult::skip();
71static bool hasNestedOpsToFlatten(mlir::Region ®ion) {
73 .walk([](mlir::Operation *op) {
74 if (op->getNumRegions() > 0 && !isa<cir::CaseOp>(op))
75 return mlir::WalkResult::interrupt();
76 return mlir::WalkResult::advance();
87static bool isNonReturningTerminator(mlir::Operation *op) {
88 return mlir::isa_and_nonnull<cir::UnreachableOp, cir::TrapOp>(op);
106static mlir::LogicalResult
107rewriteRegionExitToContinue(mlir::PatternRewriter &rewriter,
108 mlir::Region ®ion, mlir::Block *continueBlock,
109 llvm::StringRef regionDescription) {
110 mlir::Operation *terminator = region.back().getTerminator();
111 rewriter.setInsertionPointToEnd(®ion.back());
112 if (
auto yieldOp = mlir::dyn_cast<cir::YieldOp>(terminator)) {
113 rewriter.replaceOpWithNewOp<cir::BrOp>(yieldOp, yieldOp.getArgs(),
115 return mlir::success();
117 if (isNonReturningTerminator(terminator))
118 return mlir::success();
119 terminator->emitError(
"unexpected terminator in ")
121 <<
" region, expected yield, unreachable, or trap, got: "
122 << terminator->getName();
123 return mlir::failure();
126struct CIRFlattenCFGPass :
public impl::CIRFlattenCFGBase<CIRFlattenCFGPass> {
128 CIRFlattenCFGPass() =
default;
129 void runOnOperation()
override;
132struct CIRIfFlattening :
public mlir::OpRewritePattern<cir::IfOp> {
133 using OpRewritePattern<IfOp>::OpRewritePattern;
136 matchAndRewrite(cir::IfOp ifOp,
137 mlir::PatternRewriter &rewriter)
const override {
138 mlir::OpBuilder::InsertionGuard guard(rewriter);
139 mlir::Location loc = ifOp.getLoc();
140 bool emptyElse = ifOp.getElseRegion().empty();
141 mlir::Block *currentBlock = rewriter.getInsertionBlock();
142 mlir::Block *remainingOpsBlock =
143 rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
144 mlir::Block *continueBlock;
145 if (ifOp->getResults().empty())
146 continueBlock = remainingOpsBlock;
148 llvm_unreachable(
"NYI");
151 mlir::Block *thenBeforeBody = &ifOp.getThenRegion().front();
152 mlir::Block *thenAfterBody = &ifOp.getThenRegion().back();
153 rewriter.inlineRegionBefore(ifOp.getThenRegion(), continueBlock);
155 rewriter.setInsertionPointToEnd(thenAfterBody);
156 if (
auto thenYieldOp =
157 dyn_cast<cir::YieldOp>(thenAfterBody->getTerminator())) {
158 rewriter.replaceOpWithNewOp<cir::BrOp>(thenYieldOp, thenYieldOp.getArgs(),
162 rewriter.setInsertionPointToEnd(continueBlock);
165 mlir::Block *elseBeforeBody =
nullptr;
166 mlir::Block *elseAfterBody =
nullptr;
168 elseBeforeBody = &ifOp.getElseRegion().front();
169 elseAfterBody = &ifOp.getElseRegion().back();
170 rewriter.inlineRegionBefore(ifOp.getElseRegion(), continueBlock);
172 elseBeforeBody = elseAfterBody = continueBlock;
175 rewriter.setInsertionPointToEnd(currentBlock);
176 cir::BrCondOp::create(rewriter, loc, ifOp.getCondition(), thenBeforeBody,
180 rewriter.setInsertionPointToEnd(elseAfterBody);
181 if (
auto elseYieldOP =
182 dyn_cast<cir::YieldOp>(elseAfterBody->getTerminator())) {
183 rewriter.replaceOpWithNewOp<cir::BrOp>(
184 elseYieldOP, elseYieldOP.getArgs(), continueBlock);
188 rewriter.replaceOp(ifOp, continueBlock->getArguments());
189 return mlir::success();
193class CIRScopeOpFlattening :
public mlir::OpRewritePattern<cir::ScopeOp> {
195 using OpRewritePattern<cir::ScopeOp>::OpRewritePattern;
198 matchAndRewrite(cir::ScopeOp scopeOp,
199 mlir::PatternRewriter &rewriter)
const override {
200 mlir::OpBuilder::InsertionGuard guard(rewriter);
201 mlir::Location loc = scopeOp.getLoc();
209 if (scopeOp.isEmpty()) {
210 rewriter.eraseOp(scopeOp);
211 return mlir::success();
216 mlir::Block *currentBlock = rewriter.getInsertionBlock();
217 mlir::Block *continueBlock =
218 rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
219 if (scopeOp.getNumResults() > 0)
220 continueBlock->addArguments(scopeOp.getResultTypes(), loc);
223 mlir::Block *beforeBody = &scopeOp.getScopeRegion().front();
224 mlir::Block *afterBody = &scopeOp.getScopeRegion().back();
225 rewriter.inlineRegionBefore(scopeOp.getScopeRegion(), continueBlock);
228 rewriter.setInsertionPointToEnd(currentBlock);
230 cir::BrOp::create(rewriter, loc, mlir::ValueRange(), beforeBody);
234 rewriter.setInsertionPointToEnd(afterBody);
235 if (
auto yieldOp = dyn_cast<cir::YieldOp>(afterBody->getTerminator())) {
236 rewriter.replaceOpWithNewOp<cir::BrOp>(yieldOp, yieldOp.getArgs(),
241 rewriter.replaceOp(scopeOp, continueBlock->getArguments());
243 return mlir::success();
247class CIRSwitchOpFlattening :
public mlir::OpRewritePattern<cir::SwitchOp> {
249 using OpRewritePattern<cir::SwitchOp>::OpRewritePattern;
251 inline void rewriteYieldOp(mlir::PatternRewriter &rewriter,
252 cir::YieldOp yieldOp,
253 mlir::Block *destination)
const {
254 rewriter.setInsertionPoint(yieldOp);
255 rewriter.replaceOpWithNewOp<cir::BrOp>(yieldOp, yieldOp.getOperands(),
260 Block *condBrToRangeDestination(cir::SwitchOp op,
261 mlir::PatternRewriter &rewriter,
262 mlir::Block *rangeDestination,
263 mlir::Block *defaultDestination,
264 const APInt &lowerBound,
265 const APInt &upperBound)
const {
266 auto condType = mlir::cast<cir::IntType>(op.getCondition().getType());
267 bool isSigned = condType.isSigned();
269 (isSigned ? lowerBound.sle(upperBound) : lowerBound.ule(upperBound)) &&
271 mlir::Block *resBlock = rewriter.createBlock(defaultDestination);
277 cir::IntType uIntType =
278 cir::IntType::get(op.getContext(), condType.getWidth(),
281 cir::ConstantOp lowerBoundValue = cir::ConstantOp::create(
282 rewriter, op.getLoc(), cir::IntAttr::get(condType, lowerBound));
283 mlir::Value diffValue = cir::SubOp::create(
284 rewriter, op.getLoc(), op.getCondition(), lowerBoundValue);
292 diffValue = cir::CastOp::create(rewriter, op.getLoc(), uIntType,
293 CastKind::integral, diffValue);
295 cir::ConstantOp rangeLength = cir::ConstantOp::create(
296 rewriter, op.getLoc(),
297 cir::IntAttr::get(uIntType, upperBound - lowerBound));
299 cir::CmpOp cmpResult = cir::CmpOp::create(
300 rewriter, op.getLoc(), cir::CmpOpKind::le, diffValue, rangeLength);
301 cir::BrCondOp::create(rewriter, op.getLoc(), cmpResult, rangeDestination,
307 matchAndRewrite(cir::SwitchOp op,
308 mlir::PatternRewriter &rewriter)
const override {
313 for (mlir::Region ®ion : op->getRegions())
314 if (hasNestedOpsToFlatten(region))
315 return mlir::failure();
318 if (op.getBody().hasOneBlock() &&
319 op.getBody().front().without_terminator().empty()) {
320 rewriter.eraseOp(op);
321 return mlir::success();
324 llvm::SmallVector<CaseOp> cases;
325 op.collectCases(cases);
328 mlir::Block *exitBlock = rewriter.splitBlock(
329 rewriter.getBlock(), op->getNextNode()->getIterator());
342 walkRegionSkipping<cir::LoopOpInterface, cir::SwitchOp>(
343 op.getBody(), [&](mlir::Operation *op) {
344 if (!isa<cir::BreakOp>(op))
345 return mlir::WalkResult::advance();
347 lowerTerminator(op, exitBlock, rewriter);
348 return mlir::WalkResult::skip();
354 cir::YieldOp switchYield =
nullptr;
356 for (mlir::Block &block :
357 llvm::make_early_inc_range(op.getBody().getBlocks()))
358 if (
auto yieldOp = dyn_cast<cir::YieldOp>(block.getTerminator()))
359 switchYield = yieldOp;
361 assert(!op.getBody().empty());
362 mlir::Block *originalBlock = op->getBlock();
363 mlir::Block *swopBlock =
364 rewriter.splitBlock(originalBlock, op->getIterator());
365 rewriter.inlineRegionBefore(op.getBody(), exitBlock);
368 rewriteYieldOp(rewriter, switchYield, exitBlock);
370 rewriter.setInsertionPointToEnd(originalBlock);
371 cir::BrOp::create(rewriter, op.getLoc(), swopBlock);
376 llvm::SmallVector<mlir::APInt, 8> caseValues;
377 llvm::SmallVector<mlir::Block *, 8> caseDestinations;
378 llvm::SmallVector<mlir::ValueRange, 8> caseOperands;
380 llvm::SmallVector<std::pair<APInt, APInt>> rangeValues;
381 llvm::SmallVector<mlir::Block *> rangeDestinations;
382 llvm::SmallVector<mlir::ValueRange> rangeOperands;
385 mlir::Block *defaultDestination = exitBlock;
386 mlir::ValueRange defaultOperands = exitBlock->getArguments();
389 for (cir::CaseOp caseOp : cases) {
390 mlir::Region ®ion = caseOp.getCaseRegion();
393 switch (caseOp.getKind()) {
394 case cir::CaseOpKind::Default:
395 defaultDestination = ®ion.front();
396 defaultOperands = defaultDestination->getArguments();
398 case cir::CaseOpKind::Range:
399 assert(caseOp.getValue().size() == 2 &&
400 "Case range should have 2 case value");
401 rangeValues.push_back(
402 {cast<cir::IntAttr>(caseOp.getValue()[0]).getValue(),
403 cast<cir::IntAttr>(caseOp.getValue()[1]).getValue()});
404 rangeDestinations.push_back(®ion.front());
405 rangeOperands.push_back(rangeDestinations.back()->getArguments());
407 case cir::CaseOpKind::Anyof:
408 case cir::CaseOpKind::Equal:
410 for (
const mlir::Attribute &value : caseOp.getValue()) {
411 caseValues.push_back(cast<cir::IntAttr>(value).getValue());
412 caseDestinations.push_back(®ion.front());
413 caseOperands.push_back(caseDestinations.back()->getArguments());
419 for (mlir::Block &blk : region.getBlocks()) {
420 if (blk.getNumSuccessors())
423 if (
auto yieldOp = dyn_cast<cir::YieldOp>(blk.getTerminator())) {
424 mlir::Operation *nextOp = caseOp->getNextNode();
425 assert(nextOp &&
"caseOp is not expected to be the last op");
426 mlir::Block *oldBlock = nextOp->getBlock();
427 mlir::Block *newBlock =
428 rewriter.splitBlock(oldBlock, nextOp->getIterator());
429 rewriter.setInsertionPointToEnd(oldBlock);
430 cir::BrOp::create(rewriter, nextOp->getLoc(), mlir::ValueRange(),
432 rewriteYieldOp(rewriter, yieldOp, newBlock);
436 mlir::Block *oldBlock = caseOp->getBlock();
437 mlir::Block *newBlock =
438 rewriter.splitBlock(oldBlock, caseOp->getIterator());
440 mlir::Block &entryBlock = caseOp.getCaseRegion().front();
441 rewriter.inlineRegionBefore(caseOp.getCaseRegion(), newBlock);
444 rewriter.setInsertionPointToEnd(oldBlock);
445 cir::BrOp::create(rewriter, caseOp.getLoc(), &entryBlock);
449 for (cir::CaseOp caseOp : cases) {
450 mlir::Block *caseBlock = caseOp->getBlock();
453 if (caseBlock->hasNoPredecessors())
454 rewriter.eraseBlock(caseBlock);
456 rewriter.eraseOp(caseOp);
460 mlir::cast<cir::IntType>(op.getCondition().getType()).isSigned();
461 for (
auto [rangeVal, operand, destination] :
462 llvm::zip(rangeValues, rangeOperands, rangeDestinations)) {
463 APInt lowerBound = rangeVal.first;
464 APInt upperBound = rangeVal.second;
467 if (isSigned ? lowerBound.sgt(upperBound) : lowerBound.ugt(upperBound))
472 constexpr uint64_t kSmallRangeThreshold = 64;
473 APInt rangeSize = upperBound - lowerBound;
474 if (rangeSize.ult(kSmallRangeThreshold)) {
481 APInt caseValue = lowerBound;
482 for (uint64_t n = rangeSize.getZExtValue() + 1; n != 0; --n) {
483 caseValues.push_back(caseValue++);
484 caseOperands.push_back(operand);
485 caseDestinations.push_back(destination);
491 condBrToRangeDestination(op, rewriter, destination,
492 defaultDestination, lowerBound, upperBound);
493 defaultOperands = operand;
497 rewriter.setInsertionPoint(op);
498 rewriter.replaceOpWithNewOp<cir::SwitchFlatOp>(
499 op, op.getCondition(), defaultDestination, defaultOperands, caseValues,
500 caseDestinations, caseOperands);
502 return mlir::success();
506class CIRLoopOpInterfaceFlattening
507 :
public mlir::OpInterfaceRewritePattern<cir::LoopOpInterface> {
509 using mlir::OpInterfaceRewritePattern<
510 cir::LoopOpInterface>::OpInterfaceRewritePattern;
512 inline void lowerConditionOp(cir::ConditionOp op, mlir::Block *body,
514 mlir::PatternRewriter &rewriter)
const {
515 mlir::OpBuilder::InsertionGuard guard(rewriter);
516 rewriter.setInsertionPoint(op);
517 rewriter.replaceOpWithNewOp<cir::BrCondOp>(op, op.getCondition(), body,
555 rewriteLoopWithCleanup(cir::LoopOpInterface op,
556 mlir::PatternRewriter &rewriter)
const {
557 mlir::Location loc = op.getLoc();
558 mlir::Region *stepRegion = op.maybeGetStep();
560 cir::CleanupKindAttr cleanupKind = op.maybeGetCleanupKind();
561 assert(cleanupKind &&
"loop cleanup region without a cleanup kind");
563 mlir::Region &condRegion = op.getCond();
564 mlir::Region &bodyRegion = op.getBody();
565 mlir::Region &cleanupRegion = *op.maybeGetCleanup();
571 cast<cir::ConditionOp>(condRegion.back().getTerminator());
572 mlir::Value condVal = conditionOp.getCondition();
577 mlir::Block *bodyFront = &bodyRegion.front();
578 mlir::Block *stepFront = stepRegion ? &stepRegion->front() :
nullptr;
583 llvm::SmallVector<cir::YieldOp> bodyYieldsToStep;
584 llvm::SmallVector<cir::ContinueOp> continuesToStep;
586 for (mlir::Block &blk : bodyRegion.getBlocks())
587 if (
auto y = dyn_cast<cir::YieldOp>(blk.getTerminator()))
588 bodyYieldsToStep.push_back(y);
589 op.walkBodySkippingNestedLoops([&](mlir::Operation *o) {
590 if (
auto c = dyn_cast<cir::ContinueOp>(o)) {
591 continuesToStep.push_back(c);
592 return mlir::WalkResult::skip();
594 return mlir::WalkResult::advance();
600 rewriter.inlineRegionBefore(bodyRegion, condRegion, condRegion.end());
602 rewriter.inlineRegionBefore(*stepRegion, condRegion, condRegion.end());
606 mlir::Block *breakBlock =
607 rewriter.createBlock(&condRegion, condRegion.end());
608 rewriter.setInsertionPointToEnd(breakBlock);
609 cir::BreakOp::create(rewriter, conditionOp.getLoc());
611 rewriter.setInsertionPoint(conditionOp);
612 rewriter.replaceOpWithNewOp<cir::BrCondOp>(conditionOp, condVal, bodyFront,
617 for (cir::YieldOp y : bodyYieldsToStep)
618 lowerTerminator(y, stepFront, rewriter);
619 for (cir::ContinueOp c : continuesToStep)
620 lowerTerminator(c, stepFront, rewriter);
624 mlir::Block *newBodyBlock = rewriter.createBlock(&bodyRegion);
625 rewriter.setInsertionPointToEnd(newBodyBlock);
626 auto emitYield = [](mlir::OpBuilder &b, mlir::Location l) {
627 cir::YieldOp::create(b, l);
629 auto scope = cir::CleanupScopeOp::create(
630 rewriter, loc, cleanupKind.getValue(), emitYield, emitYield);
631 cir::YieldOp::create(rewriter, loc);
636 mlir::Block *bodyPlaceholder = &scope.getBodyRegion().front();
637 rewriter.inlineRegionBefore(condRegion, bodyPlaceholder);
638 rewriter.eraseBlock(bodyPlaceholder);
640 mlir::Block *cleanupPlaceholder = &scope.getCleanupRegion().front();
641 rewriter.inlineRegionBefore(cleanupRegion, cleanupPlaceholder);
642 rewriter.eraseBlock(cleanupPlaceholder);
645 mlir::Block *newCondBlock = rewriter.createBlock(&condRegion);
646 rewriter.setInsertionPointToEnd(newCondBlock);
647 mlir::Value trueVal = cir::ConstantOp::create(
648 rewriter, loc, cir::BoolAttr::get(rewriter.getContext(),
true));
649 cir::ConditionOp::create(rewriter, loc, trueVal);
653 mlir::Block *newStepBlock = rewriter.createBlock(stepRegion);
654 rewriter.setInsertionPointToEnd(newStepBlock);
655 cir::YieldOp::create(rewriter, loc);
661 if (
auto whileOp = mlir::dyn_cast<cir::WhileOp>(op.getOperation()))
662 whileOp.removeCleanupKindAttr();
663 else if (
auto forOp = mlir::dyn_cast<cir::ForOp>(op.getOperation()))
664 forOp.removeCleanupKindAttr();
666 return mlir::success();
670 matchAndRewrite(cir::LoopOpInterface op,
671 mlir::PatternRewriter &rewriter)
const final {
676 for (mlir::Region ®ion : op->getRegions())
677 if (hasNestedOpsToFlatten(region))
678 return mlir::failure();
688 if (op.maybeGetCleanup())
689 return rewriteLoopWithCleanup(op, rewriter);
692 mlir::Block *entry = rewriter.getInsertionBlock();
694 rewriter.splitBlock(entry, rewriter.getInsertionPoint());
695 mlir::Block *cond = &op.getCond().front();
696 mlir::Block *body = &op.getBody().front();
698 (op.maybeGetStep() ? &op.maybeGetStep()->front() :
nullptr);
701 rewriter.setInsertionPointToEnd(entry);
702 cir::BrOp::create(rewriter, op.getLoc(), &op.getEntry().front());
709 cast<cir::ConditionOp>(op.getCond().back().getTerminator());
710 lowerConditionOp(conditionOp, body, exit, rewriter);
717 mlir::Block *dest = (
step ?
step : cond);
718 op.walkBodySkippingNestedLoops([&](mlir::Operation *op) {
719 if (!isa<cir::ContinueOp>(op))
720 return mlir::WalkResult::advance();
722 lowerTerminator(op, dest, rewriter);
723 return mlir::WalkResult::skip();
727 walkRegionSkipping<cir::LoopOpInterface, cir::SwitchOp>(
728 op.getBody(), [&](mlir::Operation *op) {
729 if (!isa<cir::BreakOp>(op))
730 return mlir::WalkResult::advance();
732 lowerTerminator(op, exit, rewriter);
733 return mlir::WalkResult::skip();
737 for (mlir::Block &blk : op.getBody().getBlocks()) {
738 auto bodyYield = dyn_cast<cir::YieldOp>(blk.getTerminator());
740 lowerTerminator(bodyYield, (
step ?
step : cond), rewriter);
748 cast<cir::YieldOp>(op.maybeGetStep()->back().getTerminator()), cond,
752 rewriter.inlineRegionBefore(op.getCond(), exit);
753 rewriter.inlineRegionBefore(op.getBody(), exit);
755 rewriter.inlineRegionBefore(*op.maybeGetStep(), exit);
757 rewriter.eraseOp(op);
758 return mlir::success();
762class CIRTernaryOpFlattening :
public mlir::OpRewritePattern<cir::TernaryOp> {
764 using OpRewritePattern<cir::TernaryOp>::OpRewritePattern;
767 matchAndRewrite(cir::TernaryOp op,
768 mlir::PatternRewriter &rewriter)
const override {
769 Location loc = op->getLoc();
770 Block *condBlock = rewriter.getInsertionBlock();
771 Block::iterator opPosition = rewriter.getInsertionPoint();
772 Block *remainingOpsBlock = rewriter.splitBlock(condBlock, opPosition);
773 llvm::SmallVector<mlir::Location, 2> locs;
776 if (op->getResultTypes().size())
778 Block *continueBlock =
779 rewriter.createBlock(remainingOpsBlock, op->getResultTypes(), locs);
780 cir::BrOp::create(rewriter, loc, remainingOpsBlock);
782 Region &trueRegion = op.getTrueRegion();
783 Block *trueBlock = &trueRegion.front();
788 if (failed(rewriteRegionExitToContinue(rewriter, trueRegion, continueBlock,
790 return mlir::success();
791 rewriter.inlineRegionBefore(trueRegion, continueBlock);
793 Block *falseBlock = continueBlock;
794 Region &falseRegion = op.getFalseRegion();
796 falseBlock = &falseRegion.front();
797 if (failed(rewriteRegionExitToContinue(rewriter, falseRegion, continueBlock,
799 return mlir::success();
800 rewriter.inlineRegionBefore(falseRegion, continueBlock);
802 rewriter.setInsertionPointToEnd(condBlock);
803 cir::BrCondOp::create(rewriter, loc, op.getCond(), trueBlock, falseBlock);
805 rewriter.replaceOp(op, continueBlock->getArguments());
808 return mlir::success();
815static cir::AllocaOp getOrCreateCleanupDestSlot(cir::FuncOp funcOp,
816 mlir::PatternRewriter &rewriter,
817 mlir::Location loc) {
818 mlir::Block &entryBlock = funcOp.getBody().front();
821 auto it = llvm::find_if(entryBlock, [](
auto &op) {
822 return mlir::isa<AllocaOp>(&op) &&
823 mlir::cast<AllocaOp>(&op).getCleanupDestSlot();
825 if (it != entryBlock.end())
826 return mlir::cast<cir::AllocaOp>(*it);
829 mlir::OpBuilder::InsertionGuard guard(rewriter);
830 rewriter.setInsertionPointToStart(&entryBlock);
831 cir::IntType s32Type =
832 cir::IntType::get(rewriter.getContext(), 32,
true);
833 cir::PointerType ptrToS32Type = cir::PointerType::get(s32Type);
835 uint64_t alignment = dataLayout.getAlignment(s32Type,
true).value();
836 auto allocaOp = cir::AllocaOp::create(
837 rewriter, loc, ptrToS32Type,
"__cleanup_dest_slot",
838 rewriter.getI64IntegerAttr(alignment));
839 allocaOp.setCleanupDestSlot(
true);
851collectThrowingCalls(mlir::Region ®ion,
853 region.walk([&](cir::CallOp callOp) {
854 if (!callOp.getNothrow())
855 callsToRewrite.push_back(callOp);
865collectThrows(mlir::Region ®ion,
868 [&](cir::ThrowOp throwOp) { throwsToRewrite.push_back(throwOp); });
877static void collectResumeOps(mlir::Region ®ion,
879 region.walk([&](cir::ResumeOp resumeOp) { resumeOps.push_back(resumeOp); });
885static mlir::Block *buildUnwindBlock(mlir::Block *dest,
bool isCleanupOnly,
887 mlir::Block *insertBefore,
888 mlir::PatternRewriter &rewriter) {
889 mlir::Block *unwindBlock = rewriter.createBlock(insertBefore);
890 rewriter.setInsertionPointToEnd(unwindBlock);
892 cir::EhInitiateOp::create(rewriter, loc, isCleanupOnly);
893 cir::BrOp::create(rewriter, loc, mlir::ValueRange{ehInitiate.getEhToken()},
901static mlir::Block *buildTerminateUnwindBlock(mlir::Location loc,
902 mlir::Block *insertBefore,
903 mlir::PatternRewriter &rewriter) {
904 mlir::Block *terminateBlock = rewriter.createBlock(insertBefore);
905 rewriter.setInsertionPointToEnd(terminateBlock);
906 auto ehInitiate = cir::EhInitiateOp::create(rewriter, loc,
false);
907 cir::EhTerminateOp::create(rewriter, loc, ehInitiate.getEhToken());
908 return terminateBlock;
911class CIRCleanupScopeOpFlattening
912 :
public mlir::OpRewritePattern<cir::CleanupScopeOp> {
914 using OpRewritePattern<cir::CleanupScopeOp>::OpRewritePattern;
919 mlir::Operation *exitOp;
925 CleanupExit(mlir::Operation *op,
int id) : exitOp(op), destinationId(id) {}
935 static bool gotoTargetsLabelInRegion(cir::GotoOp gotoOp,
936 mlir::Region ®ion) {
937 llvm::StringRef targetLabel = gotoOp.getLabel();
939 .walk([&](cir::LabelOp labelOp) {
940 if (labelOp.getLabel() == targetLabel)
941 return mlir::WalkResult::interrupt();
942 return mlir::WalkResult::advance();
965 void collectExits(mlir::Region &cleanupBodyRegion,
966 llvm::SmallVectorImpl<CleanupExit> &exits,
971 for (mlir::Block &block : cleanupBodyRegion) {
972 auto *terminator = block.getTerminator();
973 if (isa<cir::YieldOp>(terminator))
974 exits.emplace_back(terminator, nextId++);
981 auto isGotoThatExitsCleanup = [&](mlir::Operation *op) {
982 auto gotoOp = dyn_cast<cir::GotoOp>(op);
983 return gotoOp && !gotoTargetsLabelInRegion(gotoOp, cleanupBodyRegion);
990 auto collectExitsInLoop = [&](mlir::Operation *loopOp) {
991 loopOp->walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *nestedOp) {
992 if (isa<cir::ReturnOp>(nestedOp)) {
993 exits.emplace_back(nestedOp, nextId++);
994 }
else if (isGotoThatExitsCleanup(nestedOp)) {
995 exits.emplace_back(nestedOp, nextId++);
997 return mlir::WalkResult::advance();
1002 std::function<void(mlir::Region &,
bool)> collectExitsInCleanup;
1003 std::function<void(mlir::Operation *)> collectExitsInSwitch;
1007 collectExitsInSwitch = [&](mlir::Operation *switchOp) {
1008 switchOp->walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *nestedOp) {
1009 if (isa<cir::CleanupScopeOp>(nestedOp)) {
1012 collectExitsInCleanup(
1013 cast<cir::CleanupScopeOp>(nestedOp).getBodyRegion(),
1015 return mlir::WalkResult::skip();
1016 }
else if (isa<cir::LoopOpInterface>(nestedOp)) {
1017 collectExitsInLoop(nestedOp);
1018 return mlir::WalkResult::skip();
1019 }
else if (isa<cir::ReturnOp, cir::ContinueOp>(nestedOp)) {
1020 exits.emplace_back(nestedOp, nextId++);
1021 }
else if (isGotoThatExitsCleanup(nestedOp)) {
1022 exits.emplace_back(nestedOp, nextId++);
1024 return mlir::WalkResult::advance();
1031 collectExitsInCleanup = [&](mlir::Region ®ion,
bool ignoreBreak) {
1032 region.walk<mlir::WalkOrder::PreOrder>([&](mlir::Operation *op) {
1039 if (!ignoreBreak && isa<cir::BreakOp>(op)) {
1040 exits.emplace_back(op, nextId++);
1041 }
else if (isa<cir::ContinueOp, cir::ReturnOp>(op)) {
1042 exits.emplace_back(op, nextId++);
1043 }
else if (isGotoThatExitsCleanup(op)) {
1044 exits.emplace_back(op, nextId++);
1045 }
else if (isa<cir::CleanupScopeOp>(op)) {
1047 collectExitsInCleanup(cast<cir::CleanupScopeOp>(op).getBodyRegion(),
1049 return mlir::WalkResult::skip();
1050 }
else if (isa<cir::LoopOpInterface>(op)) {
1054 collectExitsInLoop(op);
1055 return mlir::WalkResult::skip();
1056 }
else if (isa<cir::SwitchOp>(op)) {
1060 collectExitsInSwitch(op);
1061 return mlir::WalkResult::skip();
1063 return mlir::WalkResult::advance();
1068 collectExitsInCleanup(cleanupBodyRegion,
false);
1074 static bool shouldSinkReturnOperand(mlir::Value operand,
1075 cir::ReturnOp returnOp) {
1077 mlir::Operation *defOp = operand.getDefiningOp();
1083 if (!mlir::isa<cir::ConstantOp, cir::LoadOp>(defOp))
1087 if (!operand.hasOneUse())
1091 if (defOp->getBlock() != returnOp->getBlock())
1094 if (
auto loadOp = mlir::dyn_cast<cir::LoadOp>(defOp)) {
1096 mlir::Value ptr = loadOp.getAddr();
1097 auto funcOp = returnOp->getParentOfType<cir::FuncOp>();
1098 assert(funcOp &&
"Return op has no function parent?");
1099 mlir::Block &funcEntryBlock = funcOp.getBody().front();
1103 mlir::dyn_cast_if_present<cir::AllocaOp>(ptr.getDefiningOp()))
1104 return allocaOp->getBlock() == &funcEntryBlock;
1110 assert(mlir::isa<cir::ConstantOp>(defOp) &&
"Expected constant op");
1119 getReturnOpOperands(cir::ReturnOp returnOp, mlir::Operation *exitOp,
1120 mlir::Location loc, mlir::PatternRewriter &rewriter,
1121 llvm::SmallVectorImpl<mlir::Value> &returnValues)
const {
1122 mlir::Block *destBlock = rewriter.getInsertionBlock();
1123 auto funcOp = exitOp->getParentOfType<cir::FuncOp>();
1124 assert(funcOp &&
"Return op has no function parent?");
1125 mlir::Block &funcEntryBlock = funcOp.getBody().front();
1127 for (mlir::Value operand : returnOp.getOperands()) {
1128 if (shouldSinkReturnOperand(operand, returnOp)) {
1130 mlir::Operation *defOp = operand.getDefiningOp();
1131 rewriter.moveOpBefore(defOp, destBlock, destBlock->end());
1132 returnValues.push_back(operand);
1135 cir::AllocaOp alloca;
1137 mlir::OpBuilder::InsertionGuard guard(rewriter);
1138 rewriter.setInsertionPointToStart(&funcEntryBlock);
1139 cir::CIRDataLayout dataLayout(
1140 funcOp->getParentOfType<mlir::ModuleOp>());
1142 dataLayout.getAlignment(operand.getType(),
true).value();
1143 cir::PointerType ptrType = cir::PointerType::get(operand.getType());
1145 cir::AllocaOp::create(rewriter, loc, ptrType,
"__ret_operand_tmp",
1146 rewriter.getI64IntegerAttr(alignment));
1151 mlir::OpBuilder::InsertionGuard guard(rewriter);
1152 rewriter.setInsertionPoint(exitOp);
1153 cir::StoreOp::create(rewriter, loc, operand, alloca,
1156 mlir::IntegerAttr(),
1157 cir::SyncScopeKindAttr(), cir::MemOrderAttr());
1161 rewriter.setInsertionPointToEnd(destBlock);
1163 cir::LoadOp::create(rewriter, loc, alloca,
false,
1165 mlir::IntegerAttr(),
1166 cir::SyncScopeKindAttr(), cir::MemOrderAttr(),
1168 returnValues.push_back(loaded);
1178 createExitTerminator(mlir::Operation *exitOp, mlir::Location loc,
1179 mlir::Block *continueBlock,
1180 mlir::PatternRewriter &rewriter)
const {
1181 return llvm::TypeSwitch<mlir::Operation *, mlir::LogicalResult>(exitOp)
1182 .Case<cir::YieldOp>([&](
auto) {
1184 cir::BrOp::create(rewriter, loc, continueBlock);
1185 return mlir::success();
1187 .Case<cir::BreakOp>([&](
auto) {
1189 cir::BreakOp::create(rewriter, loc);
1190 return mlir::success();
1192 .Case<cir::ContinueOp>([&](
auto) {
1194 cir::ContinueOp::create(rewriter, loc);
1195 return mlir::success();
1197 .Case<cir::ReturnOp>([&](
auto returnOp) {
1201 if (returnOp.hasOperand()) {
1202 llvm::SmallVector<mlir::Value, 2> returnValues;
1203 getReturnOpOperands(returnOp, exitOp, loc, rewriter, returnValues);
1204 cir::ReturnOp::create(rewriter, loc, returnValues);
1206 cir::ReturnOp::create(rewriter, loc);
1208 return mlir::success();
1210 .Case<cir::GotoOp>([&](
auto gotoOp) {
1215 cir::GotoOp::create(rewriter, loc, gotoOp.getLabel());
1216 return mlir::success();
1218 .
Default([&](mlir::Operation *op) {
1219 cir::UnreachableOp::create(rewriter, loc);
1220 return op->emitError(
1221 "unexpected exit operation in cleanup scope body");
1227 static bool regionExitsOnlyFromLastBlock(mlir::Region ®ion) {
1228 for (mlir::Block &block : region) {
1229 if (&block == ®ion.back())
1231 bool expectedTerminator =
1232 llvm::TypeSwitch<mlir::Operation *, bool>(block.getTerminator())
1239 .Case<cir::YieldOp, cir::ReturnOp, cir::ResumeFlatOp,
1240 cir::ContinueOp, cir::BreakOp, cir::GotoOp>(
1241 [](
auto) {
return false; })
1250 .Case<cir::TryCallOp>([](
auto) {
return false; })
1254 .Case<cir::EhDispatchOp>([](
auto) {
return false; })
1258 .Case<cir::SwitchFlatOp>([](
auto) {
return false; })
1261 .Case<cir::UnreachableOp, cir::TrapOp>([](
auto) {
return true; })
1263 .Case<cir::IndirectBrOp>([](
auto) {
return false; })
1266 .Case<cir::BrOp>([&](cir::BrOp brOp) {
1267 assert(brOp.getDest()->getParent() == ®ion &&
1268 "branch destination is not in the region");
1271 .Case<cir::BrCondOp>([&](cir::BrCondOp brCondOp) {
1272 assert(brCondOp.getDestTrue()->getParent() == ®ion &&
1273 "branch destination is not in the region");
1274 assert(brCondOp.getDestFalse()->getParent() == ®ion &&
1275 "branch destination is not in the region");
1279 .
Default([](mlir::Operation *) ->
bool {
1280 llvm_unreachable(
"unexpected terminator in cleanup region");
1282 if (!expectedTerminator)
1310 mlir::Block *buildEHCleanupBlocks(cir::CleanupScopeOp cleanupOp,
1312 mlir::Block *insertBefore,
1313 mlir::PatternRewriter &rewriter)
const {
1314 assert(regionExitsOnlyFromLastBlock(cleanupOp.getCleanupRegion()) &&
1315 "cleanup region has exits in non-final blocks");
1319 mlir::Block *blockBeforeClone =
insertBefore->getPrevNode();
1322 rewriter.cloneRegionBefore(cleanupOp.getCleanupRegion(), insertBefore);
1325 mlir::Block *clonedEntry = blockBeforeClone
1326 ? blockBeforeClone->getNextNode()
1331 auto ehTokenType = cir::EhTokenType::get(rewriter.getContext());
1332 mlir::Value ehToken = clonedEntry->addArgument(ehTokenType, loc);
1334 rewriter.setInsertionPointToStart(clonedEntry);
1335 auto beginCleanup = cir::BeginCleanupOp::create(rewriter, loc, ehToken);
1339 mlir::Block *lastClonedBlock =
insertBefore->getPrevNode();
1341 mlir::dyn_cast<cir::YieldOp>(lastClonedBlock->getTerminator());
1343 rewriter.setInsertionPoint(yieldOp);
1344 cir::EndCleanupOp::create(rewriter, loc, beginCleanup.getCleanupToken());
1345 rewriter.replaceOpWithNewOp<cir::ResumeOp>(yieldOp, ehToken);
1347 cleanupOp->emitError(
"Not yet implemented: cleanup region terminated "
1348 "with non-yield operation");
1377 flattenCleanup(cir::CleanupScopeOp cleanupOp,
1378 llvm::SmallVectorImpl<CleanupExit> &exits,
1379 llvm::SmallVectorImpl<cir::CallOp> &callsToRewrite,
1380 llvm::SmallVectorImpl<cir::ThrowOp> &throwsToRewrite,
1381 llvm::SmallVectorImpl<cir::ResumeOp> &resumeOpsToChain,
1382 mlir::PatternRewriter &rewriter)
const {
1383 mlir::Location loc = cleanupOp.getLoc();
1384 cir::CleanupKind cleanupKind = cleanupOp.getCleanupKind();
1385 bool hasNormalCleanup = cleanupKind == cir::CleanupKind::Normal ||
1386 cleanupKind == cir::CleanupKind::All;
1387 bool hasEHCleanup = cleanupKind == cir::CleanupKind::EH ||
1388 cleanupKind == cir::CleanupKind::All;
1389 bool isMultiExit = exits.size() > 1;
1392 mlir::Block *bodyEntry = &cleanupOp.getBodyRegion().front();
1393 mlir::Block *cleanupEntry = &cleanupOp.getCleanupRegion().front();
1394 mlir::Block *cleanupExit = &cleanupOp.getCleanupRegion().back();
1395 assert(regionExitsOnlyFromLastBlock(cleanupOp.getCleanupRegion()) &&
1396 "cleanup region has exits in non-final blocks");
1397 auto cleanupYield = dyn_cast<cir::YieldOp>(cleanupExit->getTerminator());
1398 if (!cleanupYield) {
1399 return rewriter.notifyMatchFailure(cleanupOp,
1400 "Not yet implemented: cleanup region "
1401 "terminated with non-yield operation");
1408 cir::AllocaOp destSlot;
1409 if (isMultiExit && hasNormalCleanup) {
1410 auto funcOp = cleanupOp->getParentOfType<cir::FuncOp>();
1412 return cleanupOp->emitError(
"cleanup scope not inside a function");
1413 destSlot = getOrCreateCleanupDestSlot(funcOp, rewriter, loc);
1417 mlir::Block *currentBlock = rewriter.getInsertionBlock();
1418 mlir::Block *continueBlock =
1419 rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
1429 mlir::Block *unwindBlock =
nullptr;
1430 mlir::Block *ehCleanupEntry =
nullptr;
1431 if (hasEHCleanup && (!callsToRewrite.empty() || !throwsToRewrite.empty() ||
1432 !resumeOpsToChain.empty())) {
1434 buildEHCleanupBlocks(cleanupOp, loc, continueBlock, rewriter);
1438 if (!callsToRewrite.empty() || !throwsToRewrite.empty())
1439 unwindBlock = buildUnwindBlock(ehCleanupEntry,
true,
1440 loc, ehCleanupEntry, rewriter);
1447 mlir::Block *normalInsertPt =
1448 unwindBlock ? unwindBlock
1449 : (ehCleanupEntry ? ehCleanupEntry : continueBlock);
1452 rewriter.inlineRegionBefore(cleanupOp.getBodyRegion(), normalInsertPt);
1455 if (hasNormalCleanup)
1456 rewriter.inlineRegionBefore(cleanupOp.getCleanupRegion(), normalInsertPt);
1459 rewriter.setInsertionPointToEnd(currentBlock);
1460 cir::BrOp::create(rewriter, loc, bodyEntry);
1463 mlir::LogicalResult result = mlir::success();
1464 if (hasNormalCleanup) {
1466 mlir::Block *exitBlock = rewriter.createBlock(normalInsertPt);
1469 rewriter.setInsertionPoint(cleanupYield);
1470 rewriter.replaceOpWithNewOp<cir::BrOp>(cleanupYield, exitBlock);
1474 rewriter.setInsertionPointToEnd(exitBlock);
1478 cir::LoadOp::create(rewriter, loc, destSlot,
false,
1480 mlir::IntegerAttr(),
1481 cir::SyncScopeKindAttr(), cir::MemOrderAttr(),
1485 llvm::SmallVector<mlir::APInt, 8> caseValues;
1486 llvm::SmallVector<mlir::Block *, 8> caseDestinations;
1487 llvm::SmallVector<mlir::ValueRange, 8> caseOperands;
1488 cir::IntType s32Type =
1489 cir::IntType::get(rewriter.getContext(), 32,
true);
1491 for (
const CleanupExit &exit : exits) {
1493 mlir::Block *destBlock = rewriter.createBlock(normalInsertPt);
1494 rewriter.setInsertionPointToEnd(destBlock);
1496 createExitTerminator(exit.exitOp, loc, continueBlock, rewriter);
1499 caseValues.push_back(
1500 llvm::APInt(32,
static_cast<uint64_t>(exit.destinationId),
true));
1501 caseDestinations.push_back(destBlock);
1502 caseOperands.push_back(mlir::ValueRange());
1506 rewriter.setInsertionPoint(exit.exitOp);
1507 auto destIdConst = cir::ConstantOp::create(
1508 rewriter, loc, cir::IntAttr::get(s32Type, exit.destinationId));
1509 cir::StoreOp::create(rewriter, loc, destIdConst, destSlot,
1512 mlir::IntegerAttr(),
1513 cir::SyncScopeKindAttr(), cir::MemOrderAttr());
1514 rewriter.replaceOpWithNewOp<cir::BrOp>(exit.exitOp, cleanupEntry);
1522 if (result.failed())
1527 mlir::Block *defaultBlock = rewriter.createBlock(normalInsertPt);
1528 rewriter.setInsertionPointToEnd(defaultBlock);
1529 cir::UnreachableOp::create(rewriter, loc);
1532 rewriter.setInsertionPointToEnd(exitBlock);
1533 cir::SwitchFlatOp::create(rewriter, loc, slotValue, defaultBlock,
1534 mlir::ValueRange(), caseValues,
1535 caseDestinations, caseOperands);
1539 rewriter.setInsertionPointToEnd(exitBlock);
1540 mlir::Operation *exitOp = exits[0].exitOp;
1541 result = createExitTerminator(exitOp, loc, continueBlock, rewriter);
1544 rewriter.setInsertionPoint(exitOp);
1545 rewriter.replaceOpWithNewOp<cir::BrOp>(exitOp, cleanupEntry);
1550 for (CleanupExit &exit : exits) {
1551 if (isa<cir::YieldOp>(exit.exitOp)) {
1552 rewriter.setInsertionPoint(exit.exitOp);
1553 rewriter.replaceOpWithNewOp<cir::BrOp>(exit.exitOp, continueBlock);
1564 for (cir::CallOp callOp : callsToRewrite)
1566 for (cir::ThrowOp throwOp : throwsToRewrite)
1576 if (ehCleanupEntry) {
1577 llvm::SmallVector<cir::CallOp> ehCleanupThrowingCalls;
1578 llvm::SmallVector<cir::ThrowOp> ehCleanupThrows;
1579 for (mlir::Block *block = ehCleanupEntry; block != continueBlock;
1580 block = block->getNextNode()) {
1581 block->walk([&](mlir::Operation *op) {
1582 if (
auto callOp = mlir::dyn_cast<cir::CallOp>(op)) {
1583 if (!callOp.getNothrow())
1584 ehCleanupThrowingCalls.push_back(callOp);
1585 }
else if (
auto throwOp = mlir::dyn_cast<cir::ThrowOp>(op)) {
1586 ehCleanupThrows.push_back(throwOp);
1590 if (!ehCleanupThrowingCalls.empty() || !ehCleanupThrows.empty()) {
1591 mlir::Block *terminateBlock =
1592 buildTerminateUnwindBlock(loc, continueBlock, rewriter);
1593 for (cir::CallOp callOp : ehCleanupThrowingCalls)
1595 for (cir::ThrowOp throwOp : ehCleanupThrows)
1605 if (ehCleanupEntry) {
1606 for (cir::ResumeOp resumeOp : resumeOpsToChain) {
1607 mlir::Value ehToken = resumeOp.getEhToken();
1608 rewriter.setInsertionPoint(resumeOp);
1609 rewriter.replaceOpWithNewOp<cir::BrOp>(
1610 resumeOp, mlir::ValueRange{ehToken}, ehCleanupEntry);
1615 rewriter.eraseOp(cleanupOp);
1620 return mlir::success();
1624 matchAndRewrite(cir::CleanupScopeOp cleanupOp,
1625 mlir::PatternRewriter &rewriter)
const override {
1626 mlir::OpBuilder::InsertionGuard guard(rewriter);
1640 llvm::SmallVector<cir::CleanupScopeOp> deadNestedOps;
1641 cleanupOp.getBodyRegion().walk([&](cir::CleanupScopeOp nested) {
1642 if (mlir::isOpTriviallyDead(nested))
1643 deadNestedOps.push_back(nested);
1645 for (
auto op : deadNestedOps)
1646 rewriter.eraseOp(op);
1648 if (hasNestedOpsToFlatten(cleanupOp.getBodyRegion()))
1649 return mlir::failure();
1651 cir::CleanupKind cleanupKind = cleanupOp.getCleanupKind();
1654 llvm::SmallVector<CleanupExit> exits;
1656 collectExits(cleanupOp.getBodyRegion(), exits, nextId);
1658 assert(!exits.empty() &&
"cleanup scope body has no exit");
1663 llvm::SmallVector<cir::CallOp> callsToRewrite;
1664 llvm::SmallVector<cir::ThrowOp> throwsToRewrite;
1665 if (cleanupKind != cir::CleanupKind::Normal) {
1666 collectThrowingCalls(cleanupOp.getBodyRegion(), callsToRewrite);
1667 collectThrows(cleanupOp.getBodyRegion(), throwsToRewrite);
1672 llvm::SmallVector<cir::ResumeOp> resumeOpsToChain;
1673 if (cleanupKind != cir::CleanupKind::Normal)
1674 collectResumeOps(cleanupOp.getBodyRegion(), resumeOpsToChain);
1676 return flattenCleanup(cleanupOp, exits, callsToRewrite, throwsToRewrite,
1677 resumeOpsToChain, rewriter);
1684static cir::EhInitiateOp traceToEhInitiate(mlir::Value ehToken) {
1686 if (
auto initiate = ehToken.getDefiningOp<cir::EhInitiateOp>())
1688 auto blockArg = mlir::dyn_cast<mlir::BlockArgument>(ehToken);
1691 mlir::Block *pred = blockArg.getOwner()->getSinglePredecessor();
1694 auto brOp = mlir::dyn_cast<cir::BrOp>(pred->getTerminator());
1697 ehToken = brOp.getDestOperands()[blockArg.getArgNumber()];
1702class CIRTryOpFlattening :
public mlir::OpRewritePattern<cir::TryOp> {
1704 using OpRewritePattern<cir::TryOp>::OpRewritePattern;
1709 mlir::Block *buildCatchDispatchBlock(
1710 cir::TryOp tryOp, mlir::ArrayAttr handlerTypes,
1711 llvm::SmallVectorImpl<mlir::Block *> &catchHandlerBlocks,
1712 mlir::Location loc, mlir::Block *insertBefore,
1713 mlir::PatternRewriter &rewriter)
const {
1714 mlir::Block *dispatchBlock = rewriter.createBlock(insertBefore);
1715 auto ehTokenType = cir::EhTokenType::get(rewriter.getContext());
1716 mlir::Value ehToken = dispatchBlock->addArgument(ehTokenType, loc);
1718 rewriter.setInsertionPointToEnd(dispatchBlock);
1721 llvm::SmallVector<mlir::Attribute> catchTypeAttrs;
1722 llvm::SmallVector<mlir::Block *> catchDests;
1723 mlir::Block *defaultDest =
nullptr;
1724 bool defaultIsCatchAll =
false;
1726 for (
auto [typeAttr, handlerBlock] :
1727 llvm::zip(handlerTypes, catchHandlerBlocks)) {
1728 if (mlir::isa<cir::CatchAllAttr>(typeAttr)) {
1729 assert(!defaultDest &&
"multiple catch_all or unwind handlers");
1730 defaultDest = handlerBlock;
1731 defaultIsCatchAll =
true;
1732 }
else if (mlir::isa<cir::UnwindAttr>(typeAttr)) {
1733 assert(!defaultDest &&
"multiple catch_all or unwind handlers");
1734 defaultDest = handlerBlock;
1735 defaultIsCatchAll =
false;
1738 catchTypeAttrs.push_back(typeAttr);
1739 catchDests.push_back(handlerBlock);
1743 assert(defaultDest &&
"dispatch must have a catch_all or unwind handler");
1745 mlir::ArrayAttr catchTypesArrayAttr;
1746 if (!catchTypeAttrs.empty())
1747 catchTypesArrayAttr = rewriter.getArrayAttr(catchTypeAttrs);
1749 cir::EhDispatchOp::create(rewriter, loc, ehToken, catchTypesArrayAttr,
1750 defaultIsCatchAll, defaultDest, catchDests);
1752 return dispatchBlock;
1769 mlir::Block *flattenCatchHandler(mlir::Region &handlerRegion,
1770 mlir::Block *continueBlock,
1772 mlir::Block *insertBefore,
1773 mlir::PatternRewriter &rewriter)
const {
1775 mlir::Block *handlerEntry = &handlerRegion.front();
1778 rewriter.inlineRegionBefore(handlerRegion, insertBefore);
1781 for (mlir::Block &block : llvm::make_range(handlerEntry->getIterator(),
1783 if (
auto yieldOp = dyn_cast<cir::YieldOp>(block.getTerminator())) {
1796 if (mlir::Operation *prev = yieldOp->getPrevNode())
1797 return isa<cir::EndCatchOp>(prev);
1798 llvm::SmallPtrSet<mlir::Block *, 8> visited;
1799 llvm::SmallVector<mlir::Block *, 4> worklist;
1800 for (mlir::Block *pred : block.getPredecessors())
1801 worklist.push_back(pred);
1802 while (!worklist.empty()) {
1803 mlir::Block *b = worklist.pop_back_val();
1804 if (!visited.insert(b).second)
1806 mlir::Operation *term = b->getTerminator();
1807 if (mlir::Operation *prev = term->getPrevNode()) {
1808 if (isa<cir::EndCatchOp>(prev))
1811 for (mlir::Block *pred : b->getPredecessors())
1812 worklist.push_back(pred);
1816 "expected end_catch reachable before yield "
1817 "in catch handler");
1818 rewriter.setInsertionPoint(yieldOp);
1819 rewriter.replaceOpWithNewOp<cir::BrOp>(yieldOp, continueBlock);
1823 return handlerEntry;
1832 mlir::Block *flattenUnwindHandler(mlir::Region &unwindRegion,
1834 mlir::Block *insertBefore,
1835 mlir::PatternRewriter &rewriter)
const {
1836 mlir::Block *unwindEntry = &unwindRegion.front();
1837 rewriter.inlineRegionBefore(unwindRegion, insertBefore);
1842 matchAndRewrite(cir::TryOp tryOp,
1843 mlir::PatternRewriter &rewriter)
const override {
1850 for (mlir::Region ®ion : tryOp->getRegions())
1851 if (hasNestedOpsToFlatten(region))
1852 return mlir::failure();
1854 mlir::OpBuilder::InsertionGuard guard(rewriter);
1855 mlir::Location loc = tryOp.getLoc();
1857 mlir::ArrayAttr handlerTypes = tryOp.getHandlerTypesAttr();
1858 mlir::MutableArrayRef<mlir::Region> handlerRegions =
1859 tryOp.getHandlerRegions();
1862 llvm::SmallVector<cir::CallOp> callsToRewrite;
1863 collectThrowingCalls(tryOp.getTryRegion(), callsToRewrite);
1864 llvm::SmallVector<cir::ThrowOp> throwsToRewrite;
1865 collectThrows(tryOp.getTryRegion(), throwsToRewrite);
1868 llvm::SmallVector<cir::ResumeOp> resumeOpsToChain;
1869 collectResumeOps(tryOp.getTryRegion(), resumeOpsToChain);
1872 mlir::Block *currentBlock = rewriter.getInsertionBlock();
1873 mlir::Block *continueBlock =
1874 rewriter.splitBlock(currentBlock, rewriter.getInsertionPoint());
1877 mlir::Block *bodyEntry = &tryOp.getTryRegion().front();
1878 mlir::Block *bodyExit = &tryOp.getTryRegion().back();
1881 rewriter.inlineRegionBefore(tryOp.getTryRegion(), continueBlock);
1884 rewriter.setInsertionPointToEnd(currentBlock);
1885 cir::BrOp::create(rewriter, loc, bodyEntry);
1888 if (
auto bodyYield = dyn_cast<cir::YieldOp>(bodyExit->getTerminator())) {
1889 rewriter.setInsertionPoint(bodyYield);
1890 rewriter.replaceOpWithNewOp<cir::BrOp>(bodyYield, continueBlock);
1894 if (!handlerTypes || handlerTypes.empty()) {
1895 rewriter.eraseOp(tryOp);
1896 return mlir::success();
1904 if (callsToRewrite.empty() && throwsToRewrite.empty() &&
1905 resumeOpsToChain.empty()) {
1906 for (mlir::Region &handlerRegion : handlerRegions)
1907 for (mlir::Block &block : handlerRegion)
1908 block.dropAllDefinedValueUses();
1909 rewriter.eraseOp(tryOp);
1910 return mlir::success();
1916 llvm::SmallVector<mlir::Block *> catchHandlerBlocks;
1918 for (
const auto &[idx, typeAttr] : llvm::enumerate(handlerTypes)) {
1919 mlir::Region &handlerRegion = handlerRegions[idx];
1921 if (mlir::isa<cir::UnwindAttr>(typeAttr)) {
1922 mlir::Block *unwindEntry =
1923 flattenUnwindHandler(handlerRegion, loc, continueBlock, rewriter);
1924 catchHandlerBlocks.push_back(unwindEntry);
1926 mlir::Block *handlerEntry = flattenCatchHandler(
1927 handlerRegion, continueBlock, loc, continueBlock, rewriter);
1928 catchHandlerBlocks.push_back(handlerEntry);
1933 mlir::Block *dispatchBlock =
1934 buildCatchDispatchBlock(tryOp, handlerTypes, catchHandlerBlocks, loc,
1935 catchHandlerBlocks.front(), rewriter);
1946 handlerTypes && llvm::any_of(handlerTypes, [](mlir::Attribute attr) {
1947 return mlir::isa<cir::CatchAllAttr>(attr);
1956 bool isCleanupOnly = tryOp.getCleanup() && !hasCatchAll;
1957 if (!callsToRewrite.empty() || !throwsToRewrite.empty()) {
1959 mlir::Block *unwindBlock = buildUnwindBlock(dispatchBlock, isCleanupOnly,
1960 loc, dispatchBlock, rewriter);
1962 for (cir::CallOp callOp : callsToRewrite)
1964 for (cir::ThrowOp throwOp : throwsToRewrite)
1971 for (cir::ResumeOp resumeOp : resumeOpsToChain) {
1976 if (
auto ehInitiate = traceToEhInitiate(resumeOp.getEhToken())) {
1977 rewriter.modifyOpInPlace(ehInitiate,
1978 [&] { ehInitiate.removeCleanupAttr(); });
1982 mlir::Value ehToken = resumeOp.getEhToken();
1983 rewriter.setInsertionPoint(resumeOp);
1984 rewriter.replaceOpWithNewOp<cir::BrOp>(
1985 resumeOp, mlir::ValueRange{ehToken}, dispatchBlock);
1989 rewriter.eraseOp(tryOp);
1991 return mlir::success();
1995void populateFlattenCFGPatterns(RewritePatternSet &patterns) {
1997 .add<CIRIfFlattening, CIRLoopOpInterfaceFlattening, CIRScopeOpFlattening,
1998 CIRSwitchOpFlattening, CIRTernaryOpFlattening,
1999 CIRCleanupScopeOpFlattening, CIRTryOpFlattening>(
2000 patterns.getContext());
2008class MLIRChangedListener final :
public mlir::RewriterBase::Listener {
2009 bool hasChanged =
false;
2012 void reset() { hasChanged =
false; }
2014 bool changed()
const {
return hasChanged; }
2016 void notifyBlockErased(Block *)
override { hasChanged =
true; }
2017 void notifyOperationModified(Operation *)
override { hasChanged =
true; }
2018 void notifyOperationReplaced(Operation *, Operation *)
override {
2021 void notifyOperationReplaced(Operation *, ValueRange)
override {
2024 void notifyOperationErased(Operation *)
override { hasChanged =
true; }
2028 void notifyOperationInserted(Operation *,
2029 mlir::IRRewriter::InsertPoint)
override {
2032 void notifyBlockInserted(Block *, Region *, Region::iterator)
override {
2038void CIRFlattenCFGPass::runOnOperation() {
2039 RewritePatternSet patternList(&getContext());
2040 populateFlattenCFGPatterns(patternList);
2041 FrozenRewritePatternSet patterns(std::move(patternList));
2043 PatternApplicator applicator(patterns);
2046 applicator.applyDefaultCostModel();
2048 mlir::PatternRewriter rewriter(&getContext());
2049 MLIRChangedListener changedListener;
2050 rewriter.setListener(&changedListener);
2053 changedListener.reset();
2060 llvm::SmallVector<Operation *, 16> ops;
2061 getOperation()->walk<mlir::WalkOrder::PostOrder>([&](Operation *op) {
2062 if (isa<IfOp, ScopeOp, SwitchOp, LoopOpInterface, TernaryOp,
2063 CleanupScopeOp, TryOp>(op))
2067 for (mlir::Operation *op : ops) {
2068 rewriter.setInsertionPoint(op);
2069 (void)applicator.matchAndRewrite(op, rewriter);
2071 }
while (changedListener.changed());
2079 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.
static bool stackSaveOp()