25#define GEN_PASS_DEF_MATHEXPANDOPSPASS
26#include "mlir/Dialect/Math/Transforms/Passes.h.inc"
32 auto shapedTy = dyn_cast<ShapedType>(type);
33 return shapedTy && !shapedTy.hasRank();
41 bool losesInfo =
false;
45 APFloat::rmNearestTiesToEven, &losesInfo);
46 auto attr =
b.getFloatAttr(eltType, value);
47 if (
auto shapedTy = dyn_cast<ShapedType>(type)) {
48 if (shapedTy.hasStaticShape())
49 return arith::ConstantOp::create(
b, loc,
53 Value scalar = arith::ConstantOp::create(
b, loc, eltType, attr);
55 for (
int64_t i = 0; i < shapedTy.getRank(); ++i) {
56 if (shapedTy.isDynamicDim(i))
57 dynamicSizes.push_back(
58 tensor::DimOp::create(
b, loc, dynamicShapeRef, i));
60 return tensor::SplatOp::create(
b, loc, type, scalar, dynamicSizes);
63 return arith::ConstantOp::create(
b, loc, attr);
77 auto attr =
b.getIntegerAttr(eltType, value);
78 if (
auto shapedTy = dyn_cast<ShapedType>(type)) {
79 if (shapedTy.hasStaticShape())
80 return arith::ConstantOp::create(
b, loc,
84 Value scalar = arith::ConstantOp::create(
b, loc, eltType, attr);
86 for (
int64_t i = 0; i < shapedTy.getRank(); ++i) {
87 if (shapedTy.isDynamicDim(i))
88 dynamicSizes.push_back(
89 tensor::DimOp::create(
b, loc, dynamicShapeRef, i));
91 return tensor::SplatOp::create(
b, loc, type, scalar, dynamicSizes);
94 return arith::ConstantOp::create(
b, loc, attr);
99 Type i64Ty =
b.getI64Type();
100 if (
auto shapedTy = dyn_cast<ShapedType>(opType))
101 i64Ty = shapedTy.clone(i64Ty);
102 Value fixedConvert = arith::FPToSIOp::create(
b, i64Ty, operand);
103 Value fpFixedConvert = arith::SIToFPOp::create(
b, opType, fixedConvert);
106 return math::CopySignOp::create(
b, fpFixedConvert, operand);
112 Value operand = op.getOperand();
118 Value exp = math::ExpOp::create(
b, operand);
119 Value neg = arith::NegFOp::create(
b, operand);
120 Value nexp = math::ExpOp::create(
b, neg);
121 Value sub = arith::SubFOp::create(
b, exp, nexp);
123 Value res = arith::MulFOp::create(
b, sub, half);
131 Value operand = op.getOperand();
137 Value exp = math::ExpOp::create(
b, operand);
138 Value neg = arith::NegFOp::create(
b, operand);
139 Value nexp = math::ExpOp::create(
b, neg);
140 Value add = arith::AddFOp::create(
b, exp, nexp);
142 Value res = arith::MulFOp::create(
b,
add, half);
156 Value operand = op.getOperand();
157 auto floatType = operand.
getType();
168 Value isNegative = arith::CmpFOp::create(
169 rewriter, loc, arith::CmpFPredicate::OLT, operand, zero);
170 Value isNegativeFloat =
171 arith::UIToFPOp::create(rewriter, loc, floatType, isNegative);
172 Value isNegativeTimesNegTwo =
173 arith::MulFOp::create(rewriter, loc, isNegativeFloat, negTwo);
174 Value sign = arith::AddFOp::create(rewriter, loc, isNegativeTimesNegTwo, one);
177 Value positiveX = arith::MulFOp::create(rewriter, loc, sign, operand);
180 Value negDoubledX = arith::MulFOp::create(rewriter, loc, negTwo, positiveX);
181 Value exp2x = math::ExpOp::create(rewriter, loc, negDoubledX);
182 Value dividend = arith::SubFOp::create(rewriter, loc, one, exp2x);
183 Value divisor = arith::AddFOp::create(rewriter, loc, one, exp2x);
184 Value positiveRes = arith::DivFOp::create(rewriter, loc, dividend, divisor);
195 Value operand = op.getOperand();
197 Value sin = math::SinOp::create(
b, type, operand);
198 Value cos = math::CosOp::create(
b, type, operand);
199 Value div = arith::DivFOp::create(
b, type, sin, cos);
208 Value operand = op.getOperand();
215 Value fma = math::FmaOp::create(
b, operand, operand, one);
216 Value sqrt = math::SqrtOp::create(
b, fma);
217 Value add = arith::AddFOp::create(
b, operand, sqrt);
227 Value operand = op.getOperand();
235 Value fma = math::FmaOp::create(
b, operand, operand, negOne);
236 Value sqrt = math::SqrtOp::create(
b, fma);
237 Value add = arith::AddFOp::create(
b, operand, sqrt);
247 Value operand = op.getOperand();
254 Value add = arith::AddFOp::create(
b, operand, one);
255 Value neg = arith::NegFOp::create(
b, operand);
256 Value sub = arith::AddFOp::create(
b, neg, one);
260 Value res = arith::MulFOp::create(
b, log, half);
267 Value operandA = op.getOperand(0);
268 Value operandB = op.getOperand(1);
269 Value operandC = op.getOperand(2);
270 Type type = op.getType();
271 Value mult = arith::MulFOp::create(
b, type, operandA, operandB);
272 Value add = arith::AddFOp::create(
b, type, mult, operandC);
284 Value operand = op.getOperand();
291 FloatType floatTy = llvm::dyn_cast<FloatType>(operandETy);
292 const llvm::fltSemantics &semantics = floatTy.getFloatSemantics();
294 unsigned bitWidth = floatTy.getWidth();
295 unsigned mantissaWidth = floatTy.getFPMantissaWidth() - 1;
296 const int bias = (&semantics == &APFloat::Float8E8M0FNU())
297 ? -semantics.minExponent
298 : -(semantics.minExponent - 1);
299 bool hasNegativeZeroNaNEncoding =
300 (semantics.nanEncoding == llvm::fltNanEncoding::NegativeZero);
303 if (
auto shapedTy = dyn_cast<ShapedType>(opType))
304 iTy = shapedTy.clone(iTy);
313 Value operandBitcast = arith::BitcastOp::create(
b, iTy, operand);
315 op->getLoc(), iTy,
static_cast<int64_t>((1ull << (bitWidth - 1)) - 1),
b,
317 Value unsignedBits = arith::AndIOp::create(
b, operandBitcast, cMask);
320 static_cast<int64_t>((uint64_t(bias + mantissaWidth)) << mantissaWidth),
322 Value isLargeExp = arith::CmpIOp::create(
b, arith::CmpIPredicate::uge,
323 unsignedBits, cThreshold);
324 Value isSpecialValOrLargeVal = isLargeExp;
328 if (hasNegativeZeroNaNEncoding) {
330 op->getLoc(), iTy,
static_cast<int64_t>(1ull << (bitWidth - 1)),
b,
332 Value isNegZeroEncoding = arith::CmpIOp::create(
333 b, arith::CmpIPredicate::eq, operandBitcast, cNegZeroBits);
334 isSpecialValOrLargeVal =
335 arith::OrIOp::create(
b, isLargeExp, isNegZeroEncoding);
344 Value gtCheck = arith::CmpFOp::create(
b, arith::CmpFPredicate::OGT, operand,
347 arith::SelectOp::create(
b, op->getLoc(), gtCheck, one, zero);
349 Value add = arith::AddFOp::create(
b, opType, fpFixedConvert, incrValue);
350 Value ret = arith::SelectOp::create(
b, isSpecialValOrLargeVal, operand,
add);
362 Value base = op.getOperand(0);
363 Value power = op.getOperand(1);
366 auto convertFPowItoPowf = [&]() -> LogicalResult {
367 Value castPowerToFp =
368 arith::SIToFPOp::create(rewriter, op.getLoc(), baseType, power);
369 Value res = math::PowFOp::create(rewriter, op.getLoc(), baseType, base,
377 return convertFPowItoPowf();
381 return convertFPowItoPowf();
383 int64_t powerInt = value.getSExtValue();
384 bool isNegative = powerInt < 0;
385 int64_t absPower = std::abs(powerInt);
389 while (absPower > 0) {
391 res = arith::MulFOp::create(
b, baseType, base, res);
393 base = arith::MulFOp::create(
b, baseType, base, base);
399 res = arith::DivFOp::create(
b, baseType, one, res);
410 Value operandA = op.getOperand(0);
411 Value operandB = op.getOperand(1);
412 auto typeA = operandA.
getType();
413 auto typeB = operandB.
getType();
419 return arith::MulFOp::create(
b, x, y);
422 if (valueB.isZero()) {
428 if (valueB.isExactlyValue(1.0)) {
433 if (valueB.isExactlyValue(-1.0)) {
436 Value div = arith::DivFOp::create(
b, one, operandA);
440 if (valueB.isExactlyValue(0.5)) {
442 Value sqrt = math::SqrtOp::create(
b, operandA);
446 if (valueB.isExactlyValue(-0.5)) {
448 Value rsqrt = math::RsqrtOp::create(
b, operandA);
452 if (valueB.isExactlyValue(2.0)) {
454 rewriter.
replaceOp(op, mulf(operandA, operandA));
457 if (valueB.isExactlyValue(-2.0)) {
461 Value div = arith::DivFOp::create(
b, one, mulf(operandA, operandA));
465 if (valueB.isExactlyValue(3.0)) {
466 rewriter.
replaceOp(op, mulf(mulf(operandA, operandA), operandA));
471 Value logA = math::LogOp::create(
b, operandA);
472 Value mult = arith::MulFOp::create(
b, operandB, logA);
473 Value expResult = math::ExpOp::create(
b, mult);
485 Value operand = op.getOperand();
493 Value mult = arith::MulFOp::create(
b, opType, operand, ln2);
494 Value exp = math::ExpOp::create(
b, op->getLoc(), mult);
503 Value operand = op.getOperand();
510 Type intType =
b.getI64Type();
511 if (
auto shapedType = dyn_cast<ShapedType>(opType))
512 intType = shapedType.clone(intType);
514 auto intConst = [&](
int64_t value) {
518 Value zero = intConst(0);
519 Value one = intConst(1);
520 Value allOnes = intConst(-1);
521 Value cFractionBits = intConst(52);
522 Value cBias = intConst(1023);
523 Value cRoundShiftBase = intConst(51);
524 Value cShiftMask = intConst(63);
525 Value magnitudeMask = intConst(0x7fffffffffffffffLL);
526 Value halfBits = intConst(0x3fe0000000000000LL);
527 Value oneBits = intConst(0x3ff0000000000000LL);
529 Value bits = arith::BitcastOp::create(
b, intType, operand);
530 Value magnitude = arith::AndIOp::create(
b, bits, magnitudeMask);
531 Value sign = arith::XOrIOp::create(
b, bits, magnitude);
532 Value exponentField = arith::ShRUIOp::create(
b, magnitude, cFractionBits);
533 Value exponent = arith::SubIOp::create(
b, exponentField, cBias);
534 Value roundShift = arith::SubIOp::create(
b, cRoundShiftBase, exponent);
535 roundShift = arith::AndIOp::create(
b, roundShift, cShiftMask);
536 Value roundBit = arith::ShLIOp::create(
b, one, roundShift);
538 arith::SubIOp::create(
b, arith::ShLIOp::create(
b, roundBit, one), one);
539 Value invertedMask = arith::XOrIOp::create(
b, mask, allOnes);
540 Value incremented = arith::AddIOp::create(
b, magnitude, roundBit);
541 Value roundedMagnitude = arith::AndIOp::create(
b, incremented, invertedMask);
543 arith::CmpIOp::create(
b, arith::CmpIPredicate::uge, magnitude, halfBits);
544 Value smallMagnitude = arith::SelectOp::create(
b, atLeastHalf, oneBits, zero);
546 arith::CmpIOp::create(
b, arith::CmpIPredicate::slt, exponent, zero);
547 Value resultMagnitude =
548 arith::SelectOp::create(
b, isSmall, smallMagnitude, roundedMagnitude);
549 Value isLarge = arith::CmpIOp::create(
b, arith::CmpIPredicate::sge, exponent,
552 arith::SelectOp::create(
b, isLarge, magnitude, resultMagnitude);
553 Value resultBits = arith::OrIOp::create(
b, resultMagnitude, sign);
554 rewriter.
replaceOp(op, arith::BitcastOp::create(
b, opType, resultBits));
562 Value operand = op.getOperand();
569 if (!opEType.
isF32()) {
573 Type i32Ty =
b.getI32Type();
574 if (
auto shapedTy = dyn_cast<ShapedType>(opType))
575 i32Ty = shapedTy.clone(i32Ty);
582 Value incrValue = math::CopySignOp::create(
b, half, operand);
583 Value add = arith::AddFOp::create(
b, opType, operand, incrValue);
606 Value operandBitcast = arith::BitcastOp::create(
b, i32Ty, operand);
607 Value operandExp = arith::AndIOp::create(
608 b, arith::ShRUIOp::create(
b, operandBitcast, c23), expMask);
609 Value operandBiasedExp = arith::SubIOp::create(
b, operandExp, c127);
610 Value isSpecialValOrLargeVal = arith::CmpIOp::create(
611 b, arith::CmpIPredicate::sge, operandBiasedExp, c23);
613 Value result = arith::SelectOp::create(
b, isSpecialValOrLargeVal, operand,
623 auto operand = op.getOperand();
624 auto operandTy = operand.getType();
632 if (!eTy.isIntOrFloat()) {
633 return rewriter.
notifyMatchFailure(op,
"ctlz expansion only supports int or float types");
636 int32_t bitwidth = eTy.getIntOrFloatBitWidth();
640 uint64_t allbits = -1;
642 allbits = allbits >> (64 - bitwidth);
647 for (int32_t bw = bitwidth; bw > 1; bw = bw / 2) {
649 auto bits =
createIntConst(loc, operandTy, half, rewriter, operand);
651 createIntConst(loc, operandTy, allbits >> half, rewriter, operand);
653 Value pred = arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::ule,
655 Value add = arith::AddIOp::create(rewriter, loc, count, bits);
656 Value shift = arith::ShLIOp::create(rewriter, loc, x, bits);
658 x = arith::SelectOp::create(rewriter, loc, pred, shift, x);
659 count = arith::SelectOp::create(rewriter, loc, pred,
add, count);
663 Value pred = arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::eq,
667 Value sel = arith::SelectOp::create(rewriter, loc, pred, bwval, count);
677 auto operand = op.getOperand();
678 Type operandTy = operand.getType();
679 Type resultTy = op.getType();
686 if (!isa<FloatType>(operandETy) || !isa<FloatType>(resultETy)) {
690 Type fTy = operandTy;
692 if (
auto shapedTy = dyn_cast<ShapedType>(fTy)) {
693 iTy = shapedTy.clone(iTy);
698 unsigned mantissaWidth =
699 llvm::cast<FloatType>(operandETy).getFPMantissaWidth() - 1;
700 unsigned exponentWidth = bitWidth - mantissaWidth - 1;
713 createIntConst(loc, iTy, (1ull << (exponentWidth - 1)) - 1,
b, operand);
721 Value operandBitcast = arith::BitcastOp::create(
b, iTy, operand);
722 Value round = math::RoundOp::create(
b, operand);
723 Value roundBitcast = arith::BitcastOp::create(
b, iTy, round);
726 Value operandExp = arith::AndIOp::create(
727 b, arith::ShRUIOp::create(
b, operandBitcast, c23), expMask);
728 Value operandBiasedExp = arith::SubIOp::create(
b, operandExp, c127);
729 Value roundExp = arith::AndIOp::create(
730 b, arith::ShRUIOp::create(
b, roundBitcast, c23), expMask);
731 Value roundBiasedExp = arith::SubIOp::create(
b, roundExp, c127);
735 Value clampedShift = arith::MaxSIOp::create(
b, shift, c0);
736 clampedShift = arith::MinSIOp::create(
b, clampedShift, c31);
737 return arith::ShRUIOp::create(
b, x, clampedShift);
740 auto maskMantissa = [&](
Value mantissa,
742 Value shiftedMantissaMask = safeShiftRight(c23Mask, mantissaMaskRightShift);
743 return arith::AndIOp::create(
b, mantissa, shiftedMantissaMask);
760 Value roundBiasedExpEq0 =
761 arith::CmpIOp::create(
b, arith::CmpIPredicate::eq, roundBiasedExp, c0);
762 Value roundBiasedExpMinus1 = arith::SubIOp::create(
b, roundBiasedExp, c1);
763 Value roundMaskedMantissa = maskMantissa(roundBitcast, roundBiasedExpMinus1);
764 Value roundIsNotEvenOrSpecialVal = arith::CmpIOp::create(
765 b, arith::CmpIPredicate::ne, roundMaskedMantissa, c0);
766 roundIsNotEvenOrSpecialVal =
767 arith::OrIOp::create(
b, roundIsNotEvenOrSpecialVal, roundBiasedExpEq0);
776 Value operandBiasedExpEqNeg1 = arith::CmpIOp::create(
777 b, arith::CmpIPredicate::eq, operandBiasedExp, cNeg1);
778 Value expectedOperandMaskedMantissa = arith::SelectOp::create(
779 b, operandBiasedExpEqNeg1, c0, safeShiftRight(c2To22, operandBiasedExp));
780 Value operandMaskedMantissa = maskMantissa(operandBitcast, operandBiasedExp);
781 Value operandIsHalfway =
782 arith::CmpIOp::create(
b, arith::CmpIPredicate::eq, operandMaskedMantissa,
783 expectedOperandMaskedMantissa);
785 Value operandBiasedExpGeNeg1 = arith::CmpIOp::create(
786 b, arith::CmpIPredicate::sge, operandBiasedExp, cNeg1);
787 Value operandBiasedExpLt23 = arith::CmpIOp::create(
788 b, arith::CmpIPredicate::slt, operandBiasedExp, c23);
790 arith::AndIOp::create(
b, operandIsHalfway, operandBiasedExpLt23);
792 arith::AndIOp::create(
b, operandIsHalfway, operandBiasedExpGeNeg1);
796 Value sign = math::CopySignOp::create(
b, c1Float, operand);
797 Value roundShifted = arith::SubFOp::create(
b, round, sign);
801 arith::AndIOp::create(
b, roundIsNotEvenOrSpecialVal, operandIsHalfway);
802 Value result = arith::SelectOp::create(
b, needsShift, roundShifted, round);
814 auto operand = op.getOperand();
815 auto operandTy = operand.getType();
821 if (!isa<FloatType>(eTy))
825 auto constOneFloat =
createFloatConst(loc, operandTy, 1.0, rewriter, operand);
826 auto sqrtOp = math::SqrtOp::create(rewriter, loc, operand);
834 auto minOp = arith::MinimumFOp::create(rewriter, op.getLoc(), op.getValue(),
835 op.getMax(), op.getFastmath());
843 auto filter = [&](StringRef name) {
847 assert(
"math" == MathDialect::getDialectNamespace());
848 name.consume_front(
"math.");
849 return opMnemonics.empty() || (llvm::count(opMnemonics, name) > 0);
851 if (filter(CountLeadingZerosOp::getOperationName()))
853 if (filter(SinhOp::getOperationName()))
855 if (filter(CoshOp::getOperationName()))
857 if (filter(TanOp::getOperationName()))
859 if (filter(TanhOp::getOperationName()))
861 if (filter(AsinhOp::getOperationName()))
863 if (filter(AcoshOp::getOperationName()))
865 if (filter(AtanhOp::getOperationName()))
867 if (filter(FmaOp::getOperationName()))
869 if (filter(CeilOp::getOperationName()))
871 if (filter(Exp2Op::getOperationName()))
873 if (filter(PowFOp::getOperationName()))
875 if (filter(FPowIOp::getOperationName()))
877 if (filter(RoundOp::getOperationName()))
879 if (filter(RoundEvenOp::getOperationName()))
881 if (filter(RsqrtOp::getOperationName()))
883 if (filter(ClampFOp::getOperationName()))
891struct MathExpandOpsPass final
892 : math::impl::MathExpandOpsPassBase<MathExpandOpsPass> {
893 using MathExpandOpsPassBase::MathExpandOpsPassBase;
895 void runOnOperation()
override {
898 llvm::to_vector_of<StringRef>(opMnemonics);
900 if (expandRoundF64 &&
901 (mnemonics.empty() || llvm::count(mnemonics,
"round") > 0))
904 return signalPassFailure();
static const llvm::fltSemantics * getFloatSemantics(TruncfSrcElemTypes etype)
Float semantics the element type attributes of xevm.truncf and xevm.extf stand for.
Attributes are known-constant values of operations.
IntegerType getIntegerType(unsigned width)
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
ImplicitLocOpBuilder maintains a 'current location', allowing use of the create<> method without spec...
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
This class helps build Operations.
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
void populateExpansionPatterns(RewritePatternSet &patterns, ArrayRef< StringRef > opMnemonics={})
Adds patterns to expand math operations into other more fundamental operations.
Include the generated interface declarations.
bool matchPattern(Value value, const Pattern &pattern)
Entry point for matching a pattern over a Value.
detail::constant_int_value_binder m_ConstantInt(IntegerAttr::ValueType *bind_value)
Matches a constant holding a scalar/vector/tensor integer (splat) and writes the integer value to bin...
LogicalResult applyPatternsGreedily(Region ®ion, const FrozenRewritePatternSet &patterns, GreedyRewriteConfig config=GreedyRewriteConfig(), bool *changed=nullptr)
Rewrite ops in the given region, which must be isolated from above, by repeatedly applying the highes...
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
detail::constant_op_matcher m_Constant()
Matches a constant foldable operation.
detail::constant_float_value_binder m_ConstantFloat(FloatAttr::ValueType *bind_value)
Matches a constant holding a scalar/vector/tensor float (splat) and writes the float value to bind_va...