|
| 1 | +#include "triton/Dialect/Triton/Transforms/LoopPeeling.h" |
| 2 | +#include "mlir/Dialect/SCF/IR/SCF.h" |
| 3 | +#include "mlir/Pass/Pass.h" |
| 4 | +#include "triton/Dialect/Triton/IR/Utility.h" |
| 5 | + |
| 6 | +using namespace mlir; |
| 7 | + |
| 8 | +namespace mlir { |
| 9 | +namespace triton { |
| 10 | + |
| 11 | +void peelLoopEpilogue( |
| 12 | + scf::ForOp forOp, |
| 13 | + function_ref<Operation *(RewriterBase &, Operation *, bool)> |
| 14 | + processPeeledOp) { |
| 15 | + SmallVector<Operation *> loopBodyOps; |
| 16 | + IRRewriter rewriter(forOp); |
| 17 | + Location loc = forOp.getLoc(); |
| 18 | + Type type = forOp.getStep().getType(); |
| 19 | + |
| 20 | + // Fetch loop bounds and step |
| 21 | + Value lowerBound = forOp.getLowerBound(); |
| 22 | + Value upperBound = forOp.getUpperBound(); |
| 23 | + Value step = forOp.getStep(); |
| 24 | + Value newUpperBound = rewriter.create<arith::SubIOp>(loc, upperBound, step); |
| 25 | + |
| 26 | + rewriter.setInsertionPointAfter(forOp); |
| 27 | + Value lastIV = getLastInductionValue(rewriter, forOp); |
| 28 | + |
| 29 | + auto cond = rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::slt, |
| 30 | + lowerBound, upperBound); |
| 31 | + |
| 32 | + // Create an if op to execute the peeled iteration |
| 33 | + IRMapping map; |
| 34 | + map.map(forOp.getRegionIterArgs(), forOp.getResults()); |
| 35 | + map.map(forOp.getInductionVar(), lastIV); |
| 36 | + auto ifOp = rewriter.create<scf::IfOp>(loc, forOp.getResultTypes(), cond, |
| 37 | + /*hasElse=*/true); |
| 38 | + ifOp.getThenRegion().front().erase(); |
| 39 | + forOp.getBodyRegion().cloneInto(&ifOp.getThenRegion(), map); |
| 40 | + rewriter.setInsertionPointToStart(&ifOp.getElseRegion().front()); |
| 41 | + rewriter.create<scf::YieldOp>(loc, forOp.getResults()); |
| 42 | + |
| 43 | + forOp->replaceUsesWithIf(ifOp, [&](OpOperand &operand) { |
| 44 | + return !ifOp->isAncestor(operand.getOwner()); |
| 45 | + }); |
| 46 | + |
| 47 | + forOp.getUpperBoundMutable().assign(newUpperBound); |
| 48 | + |
| 49 | + if (processPeeledOp) { |
| 50 | + for (auto &op : |
| 51 | + llvm::make_early_inc_range(forOp.getBody()->without_terminator())) { |
| 52 | + Operation *newOp = processPeeledOp(rewriter, &op, /*isEpilogue=*/false); |
| 53 | + if (newOp && newOp != &op) { |
| 54 | + op.replaceAllUsesWith(newOp); |
| 55 | + } |
| 56 | + } |
| 57 | + for (auto &op : llvm::make_early_inc_range( |
| 58 | + ifOp.getThenRegion().front().without_terminator())) { |
| 59 | + Operation *newOp = processPeeledOp(rewriter, &op, /*isEpilogue=*/true); |
| 60 | + if (newOp && newOp != &op) { |
| 61 | + op.replaceAllUsesWith(newOp); |
| 62 | + } |
| 63 | + } |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +} // namespace triton |
| 68 | +} // namespace mlir |
0 commit comments