1 //===- ExpandOps.cpp - Pass to legalize Arithmetic ops for LLVM lowering --===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 9 #include "PassDetail.h" 10 #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h" 11 #include "mlir/Dialect/Arithmetic/Transforms/Passes.h" 12 #include "mlir/Dialect/StandardOps/IR/Ops.h" 13 #include "mlir/IR/TypeUtilities.h" 14 #include "mlir/Transforms/DialectConversion.h" 15 16 using namespace mlir; 17 18 /// Create an integer or index constant. 19 static Value createConst(Location loc, Type type, int value, 20 PatternRewriter &rewriter) { 21 return rewriter.create<arith::ConstantOp>( 22 loc, rewriter.getIntegerAttr(type, value)); 23 } 24 25 namespace { 26 27 /// Expands CeilDivUIOp (n, m) into 28 /// n == 0 ? 0 : ((n-1) / m) + 1 29 struct CeilDivUIOpConverter : public OpRewritePattern<arith::CeilDivUIOp> { 30 using OpRewritePattern::OpRewritePattern; 31 LogicalResult matchAndRewrite(arith::CeilDivUIOp op, 32 PatternRewriter &rewriter) const final { 33 Location loc = op.getLoc(); 34 Value a = op.getLhs(); 35 Value b = op.getRhs(); 36 Value zero = createConst(loc, a.getType(), 0, rewriter); 37 Value compare = 38 rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::eq, a, zero); 39 Value one = createConst(loc, a.getType(), 1, rewriter); 40 Value minusOne = rewriter.create<arith::SubIOp>(loc, a, one); 41 Value quotient = rewriter.create<arith::DivUIOp>(loc, minusOne, b); 42 Value plusOne = rewriter.create<arith::AddIOp>(loc, quotient, one); 43 rewriter.replaceOpWithNewOp<SelectOp>(op, compare, zero, plusOne); 44 return success(); 45 } 46 }; 47 48 /// Expands CeilDivSIOp (n, m) into 49 /// 1) x = (m > 0) ? -1 : 1 50 /// 2) (n*m>0) ? ((n+x) / m) + 1 : - (-n / m) 51 struct CeilDivSIOpConverter : public OpRewritePattern<arith::CeilDivSIOp> { 52 using OpRewritePattern::OpRewritePattern; 53 LogicalResult matchAndRewrite(arith::CeilDivSIOp op, 54 PatternRewriter &rewriter) const final { 55 Location loc = op.getLoc(); 56 Type type = op.getType(); 57 Value a = op.getLhs(); 58 Value b = op.getRhs(); 59 Value plusOne = createConst(loc, type, 1, rewriter); 60 Value zero = createConst(loc, type, 0, rewriter); 61 Value minusOne = createConst(loc, type, -1, rewriter); 62 // Compute x = (b>0) ? -1 : 1. 63 Value compare = 64 rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::sgt, b, zero); 65 Value x = rewriter.create<SelectOp>(loc, compare, minusOne, plusOne); 66 // Compute positive res: 1 + ((x+a)/b). 67 Value xPlusA = rewriter.create<arith::AddIOp>(loc, x, a); 68 Value xPlusADivB = rewriter.create<arith::DivSIOp>(loc, xPlusA, b); 69 Value posRes = rewriter.create<arith::AddIOp>(loc, plusOne, xPlusADivB); 70 // Compute negative res: - ((-a)/b). 71 Value minusA = rewriter.create<arith::SubIOp>(loc, zero, a); 72 Value minusADivB = rewriter.create<arith::DivSIOp>(loc, minusA, b); 73 Value negRes = rewriter.create<arith::SubIOp>(loc, zero, minusADivB); 74 // Result is (a*b>0) ? pos result : neg result. 75 // Note, we want to avoid using a*b because of possible overflow. 76 // The case that matters are a>0, a==0, a<0, b>0 and b<0. We do 77 // not particuliarly care if a*b<0 is true or false when b is zero 78 // as this will result in an illegal divide. So `a*b<0` can be reformulated 79 // as `(a<0 && b<0) || (a>0 && b>0)' or `(a<0 && b<0) || (a>0 && b>=0)'. 80 // We pick the first expression here. 81 Value aNeg = 82 rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::slt, a, zero); 83 Value aPos = 84 rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::sgt, a, zero); 85 Value bNeg = 86 rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::slt, b, zero); 87 Value bPos = 88 rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::sgt, b, zero); 89 Value firstTerm = rewriter.create<arith::AndIOp>(loc, aNeg, bNeg); 90 Value secondTerm = rewriter.create<arith::AndIOp>(loc, aPos, bPos); 91 Value compareRes = 92 rewriter.create<arith::OrIOp>(loc, firstTerm, secondTerm); 93 // Perform substitution and return success. 94 rewriter.replaceOpWithNewOp<SelectOp>(op, compareRes, posRes, negRes); 95 return success(); 96 } 97 }; 98 99 /// Expands FloorDivSIOp (n, m) into 100 /// 1) x = (m<0) ? 1 : -1 101 /// 2) return (n*m<0) ? - ((-n+x) / m) -1 : n / m 102 struct FloorDivSIOpConverter : public OpRewritePattern<arith::FloorDivSIOp> { 103 using OpRewritePattern::OpRewritePattern; 104 LogicalResult matchAndRewrite(arith::FloorDivSIOp op, 105 PatternRewriter &rewriter) const final { 106 Location loc = op.getLoc(); 107 Type type = op.getType(); 108 Value a = op.getLhs(); 109 Value b = op.getRhs(); 110 Value plusOne = createConst(loc, type, 1, rewriter); 111 Value zero = createConst(loc, type, 0, rewriter); 112 Value minusOne = createConst(loc, type, -1, rewriter); 113 // Compute x = (b<0) ? 1 : -1. 114 Value compare = 115 rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::slt, b, zero); 116 Value x = rewriter.create<SelectOp>(loc, compare, plusOne, minusOne); 117 // Compute negative res: -1 - ((x-a)/b). 118 Value xMinusA = rewriter.create<arith::SubIOp>(loc, x, a); 119 Value xMinusADivB = rewriter.create<arith::DivSIOp>(loc, xMinusA, b); 120 Value negRes = rewriter.create<arith::SubIOp>(loc, minusOne, xMinusADivB); 121 // Compute positive res: a/b. 122 Value posRes = rewriter.create<arith::DivSIOp>(loc, a, b); 123 // Result is (a*b<0) ? negative result : positive result. 124 // Note, we want to avoid using a*b because of possible overflow. 125 // The case that matters are a>0, a==0, a<0, b>0 and b<0. We do 126 // not particuliarly care if a*b<0 is true or false when b is zero 127 // as this will result in an illegal divide. So `a*b<0` can be reformulated 128 // as `(a>0 && b<0) || (a>0 && b<0)' or `(a>0 && b<0) || (a>0 && b<=0)'. 129 // We pick the first expression here. 130 Value aNeg = 131 rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::slt, a, zero); 132 Value aPos = 133 rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::sgt, a, zero); 134 Value bNeg = 135 rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::slt, b, zero); 136 Value bPos = 137 rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::sgt, b, zero); 138 Value firstTerm = rewriter.create<arith::AndIOp>(loc, aNeg, bPos); 139 Value secondTerm = rewriter.create<arith::AndIOp>(loc, aPos, bNeg); 140 Value compareRes = 141 rewriter.create<arith::OrIOp>(loc, firstTerm, secondTerm); 142 // Perform substitution and return success. 143 rewriter.replaceOpWithNewOp<SelectOp>(op, compareRes, negRes, posRes); 144 return success(); 145 } 146 }; 147 148 template <typename OpTy, arith::CmpFPredicate pred> 149 struct MaxMinFOpConverter : public OpRewritePattern<OpTy> { 150 public: 151 using OpRewritePattern<OpTy>::OpRewritePattern; 152 153 LogicalResult matchAndRewrite(OpTy op, 154 PatternRewriter &rewriter) const final { 155 Value lhs = op.getLhs(); 156 Value rhs = op.getRhs(); 157 158 Location loc = op.getLoc(); 159 // If any operand is NaN, 'cmp' will be true (and 'select' returns 'lhs'). 160 static_assert(pred == arith::CmpFPredicate::UGT || 161 pred == arith::CmpFPredicate::ULT, 162 "pred must be either UGT or ULT"); 163 Value cmp = rewriter.create<arith::CmpFOp>(loc, pred, lhs, rhs); 164 Value select = rewriter.create<SelectOp>(loc, cmp, lhs, rhs); 165 166 // Handle the case where rhs is NaN: 'isNaN(rhs) ? rhs : select'. 167 Value isNaN = rewriter.create<arith::CmpFOp>(loc, arith::CmpFPredicate::UNO, 168 rhs, rhs); 169 rewriter.replaceOpWithNewOp<SelectOp>(op, isNaN, rhs, select); 170 return success(); 171 } 172 }; 173 174 template <typename OpTy, arith::CmpIPredicate pred> 175 struct MaxMinIOpConverter : public OpRewritePattern<OpTy> { 176 public: 177 using OpRewritePattern<OpTy>::OpRewritePattern; 178 LogicalResult matchAndRewrite(OpTy op, 179 PatternRewriter &rewriter) const final { 180 Value lhs = op.getLhs(); 181 Value rhs = op.getRhs(); 182 183 Location loc = op.getLoc(); 184 Value cmp = rewriter.create<arith::CmpIOp>(loc, pred, lhs, rhs); 185 rewriter.replaceOpWithNewOp<SelectOp>(op, cmp, lhs, rhs); 186 return success(); 187 } 188 }; 189 190 struct ArithmeticExpandOpsPass 191 : public ArithmeticExpandOpsBase<ArithmeticExpandOpsPass> { 192 void runOnFunction() override { 193 RewritePatternSet patterns(&getContext()); 194 ConversionTarget target(getContext()); 195 196 arith::populateArithmeticExpandOpsPatterns(patterns); 197 198 target.addLegalDialect<arith::ArithmeticDialect, StandardOpsDialect>(); 199 // clang-format off 200 target.addIllegalOp< 201 arith::CeilDivSIOp, 202 arith::CeilDivUIOp, 203 arith::FloorDivSIOp, 204 arith::MaxFOp, 205 arith::MaxSIOp, 206 arith::MaxUIOp, 207 arith::MinFOp, 208 arith::MinSIOp, 209 arith::MinUIOp 210 >(); 211 // clang-format on 212 if (failed( 213 applyPartialConversion(getFunction(), target, std::move(patterns)))) 214 signalPassFailure(); 215 } 216 }; 217 218 } // namespace 219 220 void mlir::arith::populateArithmeticExpandOpsPatterns( 221 RewritePatternSet &patterns) { 222 // clang-format off 223 patterns.add< 224 CeilDivSIOpConverter, 225 CeilDivUIOpConverter, 226 FloorDivSIOpConverter, 227 MaxMinFOpConverter<MaxFOp, arith::CmpFPredicate::UGT>, 228 MaxMinFOpConverter<MinFOp, arith::CmpFPredicate::ULT>, 229 MaxMinIOpConverter<MaxSIOp, arith::CmpIPredicate::sgt>, 230 MaxMinIOpConverter<MaxUIOp, arith::CmpIPredicate::ugt>, 231 MaxMinIOpConverter<MinSIOp, arith::CmpIPredicate::slt>, 232 MaxMinIOpConverter<MinUIOp, arith::CmpIPredicate::ult> 233 >(patterns.getContext()); 234 // clang-format on 235 } 236 237 std::unique_ptr<Pass> mlir::arith::createArithmeticExpandOpsPass() { 238 return std::make_unique<ArithmeticExpandOpsPass>(); 239 } 240