xref: /llvm-project/mlir/lib/Dialect/Math/Transforms/ExpandPatterns.cpp (revision 10a57f3aff34be6ab43106dc1e45ace3f6da881c)
1 //===- ExpandPatterns.cpp - Code to expand various math operations. -------===//
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 // This file implements expansion of various math operations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "mlir/Dialect/Arith/IR/Arith.h"
14 #include "mlir/Dialect/Math/IR/Math.h"
15 #include "mlir/Dialect/Math/Transforms/Passes.h"
16 #include "mlir/Dialect/SCF/IR/SCF.h"
17 #include "mlir/Dialect/Vector/IR/VectorOps.h"
18 #include "mlir/IR/Builders.h"
19 #include "mlir/IR/ImplicitLocOpBuilder.h"
20 #include "mlir/IR/TypeUtilities.h"
21 #include "mlir/Transforms/DialectConversion.h"
22 
23 using namespace mlir;
24 
25 /// Create a float constant.
26 static Value createFloatConst(Location loc, Type type, APFloat value,
27                               OpBuilder &b) {
28   bool losesInfo = false;
29   auto eltType = getElementTypeOrSelf(type);
30   // Convert double to the given `FloatType` with round-to-nearest-ties-to-even.
31   value.convert(cast<FloatType>(eltType).getFloatSemantics(),
32                 APFloat::rmNearestTiesToEven, &losesInfo);
33   auto attr = b.getFloatAttr(eltType, value);
34   if (auto shapedTy = dyn_cast<ShapedType>(type)) {
35     return b.create<arith::ConstantOp>(loc,
36                                        DenseElementsAttr::get(shapedTy, attr));
37   }
38 
39   return b.create<arith::ConstantOp>(loc, attr);
40 }
41 
42 static Value createFloatConst(Location loc, Type type, double value,
43                               OpBuilder &b) {
44   return createFloatConst(loc, type, APFloat(value), b);
45 }
46 
47 /// Create an integer constant.
48 static Value createIntConst(Location loc, Type type, int64_t value,
49                             OpBuilder &b) {
50   auto attr = b.getIntegerAttr(getElementTypeOrSelf(type), value);
51   if (auto shapedTy = dyn_cast<ShapedType>(type)) {
52     return b.create<arith::ConstantOp>(loc,
53                                        DenseElementsAttr::get(shapedTy, attr));
54   }
55 
56   return b.create<arith::ConstantOp>(loc, attr);
57 }
58 
59 static Value createTruncatedFPValue(Value operand, ImplicitLocOpBuilder &b) {
60   Type opType = operand.getType();
61   Type i64Ty = b.getI64Type();
62   if (auto shapedTy = dyn_cast<ShapedType>(opType))
63     i64Ty = shapedTy.clone(i64Ty);
64   Value fixedConvert = b.create<arith::FPToSIOp>(i64Ty, operand);
65   Value fpFixedConvert = b.create<arith::SIToFPOp>(opType, fixedConvert);
66   // The truncation does not preserve the sign when the truncated
67   // value is -0. So here the sign is copied again.
68   return b.create<math::CopySignOp>(fpFixedConvert, operand);
69 }
70 
71 // sinhf(float x) -> (exp(x) - exp(-x)) / 2
72 static LogicalResult convertSinhOp(math::SinhOp op, PatternRewriter &rewriter) {
73   ImplicitLocOpBuilder b(op->getLoc(), rewriter);
74   Value operand = op.getOperand();
75   Type opType = operand.getType();
76   Value exp = b.create<math::ExpOp>(operand);
77 
78   Value one = createFloatConst(op->getLoc(), opType, 1.0, rewriter);
79   Value nexp = b.create<arith::DivFOp>(one, exp);
80   Value sub = b.create<arith::SubFOp>(exp, nexp);
81   Value two = createFloatConst(op->getLoc(), opType, 2.0, rewriter);
82   Value div = b.create<arith::DivFOp>(sub, two);
83   rewriter.replaceOp(op, div);
84   return success();
85 }
86 
87 // coshf(float x) -> (exp(x) + exp(-x)) / 2
88 static LogicalResult convertCoshOp(math::CoshOp op, PatternRewriter &rewriter) {
89   ImplicitLocOpBuilder b(op->getLoc(), rewriter);
90   Value operand = op.getOperand();
91   Type opType = operand.getType();
92   Value exp = b.create<math::ExpOp>(operand);
93 
94   Value one = createFloatConst(op->getLoc(), opType, 1.0, rewriter);
95   Value nexp = b.create<arith::DivFOp>(one, exp);
96   Value add = b.create<arith::AddFOp>(exp, nexp);
97   Value two = createFloatConst(op->getLoc(), opType, 2.0, rewriter);
98   Value div = b.create<arith::DivFOp>(add, two);
99   rewriter.replaceOp(op, div);
100   return success();
101 }
102 
103 /// Expands tanh op into
104 /// 1-exp^{-2x} / 1+exp^{-2x}
105 /// To avoid overflow we exploit the reflection symmetry `tanh(-x) = -tanh(x)`.
106 /// We compute a "signs" value which is -1 if input is negative and +1 if input
107 /// is positive.  Then multiply the input by this value, guaranteeing that the
108 /// result is positive, which also guarantees `exp^{-2x * sign(x)}` is in (0,
109 /// 1]. Expand the computation on the input `x * sign(x)`, then multiply the
110 /// result by `sign(x)` to retain sign of the real result.
111 static LogicalResult convertTanhOp(math::TanhOp op, PatternRewriter &rewriter) {
112   auto floatType = op.getOperand().getType();
113   Location loc = op.getLoc();
114   Value zero = createFloatConst(loc, floatType, 0.0, rewriter);
115   Value one = createFloatConst(loc, floatType, 1.0, rewriter);
116   Value negTwo = createFloatConst(loc, floatType, -2.0, rewriter);
117 
118   // Compute sign(x) = cast<float_type>(x < 0) * (-2) + 1
119   Value isNegative = rewriter.create<arith::CmpFOp>(
120       loc, arith::CmpFPredicate::OLT, op.getOperand(), zero);
121   Value isNegativeFloat =
122       rewriter.create<arith::UIToFPOp>(loc, floatType, isNegative);
123   Value isNegativeTimesNegTwo =
124       rewriter.create<arith::MulFOp>(loc, isNegativeFloat, negTwo);
125   Value sign = rewriter.create<arith::AddFOp>(loc, isNegativeTimesNegTwo, one);
126 
127   // Normalize input to positive value: y = sign(x) * x
128   Value positiveX = rewriter.create<arith::MulFOp>(loc, sign, op.getOperand());
129 
130   // Decompose on normalized input
131   Value negDoubledX = rewriter.create<arith::MulFOp>(loc, negTwo, positiveX);
132   Value exp2x = rewriter.create<math::ExpOp>(loc, negDoubledX);
133   Value dividend = rewriter.create<arith::SubFOp>(loc, one, exp2x);
134   Value divisor = rewriter.create<arith::AddFOp>(loc, one, exp2x);
135   Value positiveRes = rewriter.create<arith::DivFOp>(loc, dividend, divisor);
136 
137   // Multiply result by sign(x) to retain signs from negative inputs
138   rewriter.replaceOpWithNewOp<arith::MulFOp>(op, sign, positiveRes);
139 
140   return success();
141 }
142 
143 // Converts math.tan to math.sin, math.cos, and arith.divf.
144 static LogicalResult convertTanOp(math::TanOp op, PatternRewriter &rewriter) {
145   ImplicitLocOpBuilder b(op->getLoc(), rewriter);
146   Value operand = op.getOperand();
147   Type type = operand.getType();
148   Value sin = b.create<math::SinOp>(type, operand);
149   Value cos = b.create<math::CosOp>(type, operand);
150   Value div = b.create<arith::DivFOp>(type, sin, cos);
151   rewriter.replaceOp(op, div);
152   return success();
153 }
154 
155 static LogicalResult convertFmaFOp(math::FmaOp op, PatternRewriter &rewriter) {
156   ImplicitLocOpBuilder b(op->getLoc(), rewriter);
157   Value operandA = op.getOperand(0);
158   Value operandB = op.getOperand(1);
159   Value operandC = op.getOperand(2);
160   Type type = op.getType();
161   Value mult = b.create<arith::MulFOp>(type, operandA, operandB);
162   Value add = b.create<arith::AddFOp>(type, mult, operandC);
163   rewriter.replaceOp(op, add);
164   return success();
165 }
166 
167 // Converts a floorf() function to the following:
168 // floorf(float x) ->
169 //     y = (float)(int) x
170 //     if (x < 0) then incr = -1 else incr = 0
171 //     y = y + incr    <= replace this op with the floorf op.
172 static LogicalResult convertFloorOp(math::FloorOp op,
173                                     PatternRewriter &rewriter) {
174   ImplicitLocOpBuilder b(op->getLoc(), rewriter);
175   Value operand = op.getOperand();
176   Type opType = operand.getType();
177   Value fpFixedConvert = createTruncatedFPValue(operand, b);
178 
179   // Creating constants for later use.
180   Value zero = createFloatConst(op->getLoc(), opType, 0.00, rewriter);
181   Value negOne = createFloatConst(op->getLoc(), opType, -1.00, rewriter);
182 
183   Value negCheck =
184       b.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, operand, zero);
185   Value incrValue =
186       b.create<arith::SelectOp>(op->getLoc(), negCheck, negOne, zero);
187   Value ret = b.create<arith::AddFOp>(opType, fpFixedConvert, incrValue);
188   rewriter.replaceOp(op, ret);
189   return success();
190 }
191 
192 // Converts a ceilf() function to the following:
193 // ceilf(float x) ->
194 //      y = (float)(int) x
195 //      if (x > y) then incr = 1 else incr = 0
196 //      y = y + incr   <= replace this op with the ceilf op.
197 static LogicalResult convertCeilOp(math::CeilOp op, PatternRewriter &rewriter) {
198   ImplicitLocOpBuilder b(op->getLoc(), rewriter);
199   Value operand = op.getOperand();
200   Type opType = operand.getType();
201   Value fpFixedConvert = createTruncatedFPValue(operand, b);
202 
203   // Creating constants for later use.
204   Value zero = createFloatConst(op->getLoc(), opType, 0.00, rewriter);
205   Value one = createFloatConst(op->getLoc(), opType, 1.00, rewriter);
206 
207   Value gtCheck = b.create<arith::CmpFOp>(arith::CmpFPredicate::OGT, operand,
208                                           fpFixedConvert);
209   Value incrValue = b.create<arith::SelectOp>(op->getLoc(), gtCheck, one, zero);
210 
211   Value ret = b.create<arith::AddFOp>(opType, fpFixedConvert, incrValue);
212   rewriter.replaceOp(op, ret);
213   return success();
214 }
215 
216 // Convert `math.fpowi` to a series of `arith.mulf` operations.
217 // If the power is negative, we divide one by the result.
218 // If both the base and power are zero, the result is 1.
219 static LogicalResult convertFPowICstOp(math::FPowIOp op,
220                                        PatternRewriter &rewriter) {
221   ImplicitLocOpBuilder b(op->getLoc(), rewriter);
222   Value base = op.getOperand(0);
223   Value power = op.getOperand(1);
224   Type baseType = base.getType();
225 
226   Attribute cstAttr;
227   if (!matchPattern(power, m_Constant(&cstAttr)))
228     return failure();
229 
230   APInt value;
231   if (!matchPattern(cstAttr, m_ConstantInt(&value)))
232     return failure();
233 
234   int64_t powerInt = value.getSExtValue();
235   bool isNegative = powerInt < 0;
236   int64_t absPower = std::abs(powerInt);
237   Value one = createFloatConst(op->getLoc(), baseType, 1.00, rewriter);
238   Value res = createFloatConst(op->getLoc(), baseType, 1.00, rewriter);
239 
240   while (absPower > 0) {
241     if (absPower & 1)
242       res = b.create<arith::MulFOp>(baseType, base, res);
243     absPower >>= 1;
244     base = b.create<arith::MulFOp>(baseType, base, base);
245   }
246 
247   // Make sure not to introduce UB in case of negative power.
248   if (isNegative) {
249     auto &sem = dyn_cast<mlir::FloatType>(getElementTypeOrSelf(baseType))
250                     .getFloatSemantics();
251     Value zero =
252         createFloatConst(op->getLoc(), baseType,
253                          APFloat::getZero(sem, /*Negative=*/false), rewriter);
254     Value negZero =
255         createFloatConst(op->getLoc(), baseType,
256                          APFloat::getZero(sem, /*Negative=*/true), rewriter);
257     Value posInfinity =
258         createFloatConst(op->getLoc(), baseType,
259                          APFloat::getInf(sem, /*Negative=*/false), rewriter);
260     Value negInfinity =
261         createFloatConst(op->getLoc(), baseType,
262                          APFloat::getInf(sem, /*Negative=*/true), rewriter);
263     Value zeroEqCheck =
264         b.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, res, zero);
265     Value negZeroEqCheck =
266         b.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, res, negZero);
267     res = b.create<arith::DivFOp>(baseType, one, res);
268     res =
269         b.create<arith::SelectOp>(op->getLoc(), zeroEqCheck, posInfinity, res);
270     res = b.create<arith::SelectOp>(op->getLoc(), negZeroEqCheck, negInfinity,
271                                     res);
272   }
273 
274   rewriter.replaceOp(op, res);
275   return success();
276 }
277 
278 // Converts  Powf(float a, float b) (meaning a^b) to exp^(b * ln(a))
279 static LogicalResult convertPowfOp(math::PowFOp op, PatternRewriter &rewriter) {
280   ImplicitLocOpBuilder b(op->getLoc(), rewriter);
281   Value operandA = op.getOperand(0);
282   Value operandB = op.getOperand(1);
283   Type opType = operandA.getType();
284   Value zero = createFloatConst(op->getLoc(), opType, 0.00, rewriter);
285   Value two = createFloatConst(op->getLoc(), opType, 2.00, rewriter);
286   Value negOne = createFloatConst(op->getLoc(), opType, -1.00, rewriter);
287   Value opASquared = b.create<arith::MulFOp>(opType, operandA, operandA);
288   Value opBHalf = b.create<arith::DivFOp>(opType, operandB, two);
289 
290   Value logA = b.create<math::LogOp>(opType, opASquared);
291   Value mult = b.create<arith::MulFOp>(opType, opBHalf, logA);
292   Value expResult = b.create<math::ExpOp>(opType, mult);
293   Value negExpResult = b.create<arith::MulFOp>(opType, expResult, negOne);
294   Value remainder = b.create<arith::RemFOp>(opType, operandB, two);
295   Value negCheck =
296       b.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, operandA, zero);
297   Value oddPower =
298       b.create<arith::CmpFOp>(arith::CmpFPredicate::ONE, remainder, zero);
299   Value oddAndNeg = b.create<arith::AndIOp>(op->getLoc(), oddPower, negCheck);
300 
301   Value res = b.create<arith::SelectOp>(op->getLoc(), oddAndNeg, negExpResult,
302                                         expResult);
303   rewriter.replaceOp(op, res);
304   return success();
305 }
306 
307 // exp2f(float x) -> exp(x * ln(2))
308 //   Proof: Let's say 2^x = y
309 //   ln(2^x) = ln(y)
310 //   x * ln(2) = ln(y) => e ^(x*ln(2)) = y
311 static LogicalResult convertExp2fOp(math::Exp2Op op,
312                                     PatternRewriter &rewriter) {
313   ImplicitLocOpBuilder b(op->getLoc(), rewriter);
314   Value operand = op.getOperand();
315   Type opType = operand.getType();
316   Value ln2 = createFloatConst(op->getLoc(), opType, llvm::numbers::ln2, b);
317   Value mult = b.create<arith::MulFOp>(opType, operand, ln2);
318   Value exp = b.create<math::ExpOp>(op->getLoc(), mult);
319   rewriter.replaceOp(op, exp);
320   return success();
321 }
322 
323 static LogicalResult convertRoundOp(math::RoundOp op,
324                                     PatternRewriter &rewriter) {
325   Location loc = op.getLoc();
326   ImplicitLocOpBuilder b(loc, rewriter);
327   Value operand = op.getOperand();
328   Type opType = operand.getType();
329   Type opEType = getElementTypeOrSelf(opType);
330 
331   if (!opEType.isF32()) {
332     return rewriter.notifyMatchFailure(op, "not a round of f32.");
333   }
334 
335   Type i32Ty = b.getI32Type();
336   if (auto shapedTy = dyn_cast<ShapedType>(opType))
337     i32Ty = shapedTy.clone(i32Ty);
338 
339   Value half = createFloatConst(loc, opType, 0.5, b);
340   Value c23 = createIntConst(loc, i32Ty, 23, b);
341   Value c127 = createIntConst(loc, i32Ty, 127, b);
342   Value expMask = createIntConst(loc, i32Ty, (1 << 8) - 1, b);
343 
344   Value incrValue = b.create<math::CopySignOp>(half, operand);
345   Value add = b.create<arith::AddFOp>(opType, operand, incrValue);
346   Value fpFixedConvert = createTruncatedFPValue(add, b);
347 
348   // There are three cases where adding 0.5 to the value and truncating by
349   // converting to an i64 does not result in the correct behavior:
350   //
351   // 1. Special values: +-inf and +-nan
352   //     Casting these special values to i64 has undefined behavior. To identify
353   //     these values, we use the fact that these values are the only float
354   //     values with the maximum possible biased exponent.
355   //
356   // 2. Large values: 2^23 <= |x| <= INT_64_MAX
357   //     Adding 0.5 to a float larger than or equal to 2^23 results in precision
358   //     errors that sometimes round the value up and sometimes round the value
359   //     down. For example:
360   //         8388608.0 + 0.5 = 8388608.0
361   //         8388609.0 + 0.5 = 8388610.0
362   //
363   // 3. Very large values: |x| > INT_64_MAX
364   //     Casting to i64 a value greater than the max i64 value will overflow the
365   //     i64 leading to wrong outputs.
366   //
367   // All three cases satisfy the property `biasedExp >= 23`.
368   Value operandBitcast = b.create<arith::BitcastOp>(i32Ty, operand);
369   Value operandExp = b.create<arith::AndIOp>(
370       b.create<arith::ShRUIOp>(operandBitcast, c23), expMask);
371   Value operandBiasedExp = b.create<arith::SubIOp>(operandExp, c127);
372   Value isSpecialValOrLargeVal =
373       b.create<arith::CmpIOp>(arith::CmpIPredicate::sge, operandBiasedExp, c23);
374 
375   Value result = b.create<arith::SelectOp>(isSpecialValOrLargeVal, operand,
376                                            fpFixedConvert);
377   rewriter.replaceOp(op, result);
378   return success();
379 }
380 
381 // Converts math.ctlz to scf and arith operations. This is done
382 // by performing a binary search on the bits.
383 static LogicalResult convertCtlzOp(math::CountLeadingZerosOp op,
384                                    PatternRewriter &rewriter) {
385   auto operand = op.getOperand();
386   auto operandTy = operand.getType();
387   auto eTy = getElementTypeOrSelf(operandTy);
388   Location loc = op.getLoc();
389 
390   int32_t bitwidth = eTy.getIntOrFloatBitWidth();
391   if (bitwidth > 64)
392     return failure();
393 
394   uint64_t allbits = -1;
395   if (bitwidth < 64) {
396     allbits = allbits >> (64 - bitwidth);
397   }
398 
399   Value x = operand;
400   Value count = createIntConst(loc, operandTy, 0, rewriter);
401   for (int32_t bw = bitwidth; bw > 1; bw = bw / 2) {
402     auto half = bw / 2;
403     auto bits = createIntConst(loc, operandTy, half, rewriter);
404     auto mask = createIntConst(loc, operandTy, allbits >> half, rewriter);
405 
406     Value pred =
407         rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::ule, x, mask);
408     Value add = rewriter.create<arith::AddIOp>(loc, count, bits);
409     Value shift = rewriter.create<arith::ShLIOp>(loc, x, bits);
410 
411     x = rewriter.create<arith::SelectOp>(loc, pred, shift, x);
412     count = rewriter.create<arith::SelectOp>(loc, pred, add, count);
413   }
414 
415   Value zero = createIntConst(loc, operandTy, 0, rewriter);
416   Value pred = rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::eq,
417                                               operand, zero);
418 
419   Value bwval = createIntConst(loc, operandTy, bitwidth, rewriter);
420   Value sel = rewriter.create<arith::SelectOp>(loc, pred, bwval, count);
421   rewriter.replaceOp(op, sel);
422   return success();
423 }
424 
425 // Convert `math.roundeven` into `math.round` + arith ops
426 static LogicalResult convertRoundEvenOp(math::RoundEvenOp op,
427                                         PatternRewriter &rewriter) {
428   Location loc = op.getLoc();
429   ImplicitLocOpBuilder b(loc, rewriter);
430   auto operand = op.getOperand();
431   Type operandTy = operand.getType();
432   Type resultTy = op.getType();
433   Type operandETy = getElementTypeOrSelf(operandTy);
434   Type resultETy = getElementTypeOrSelf(resultTy);
435 
436   if (!isa<FloatType>(operandETy) || !isa<FloatType>(resultETy)) {
437     return rewriter.notifyMatchFailure(op, "not a roundeven of f16 or f32.");
438   }
439 
440   Type fTy = operandTy;
441   Type iTy = rewriter.getIntegerType(operandETy.getIntOrFloatBitWidth());
442   if (auto shapedTy = dyn_cast<ShapedType>(fTy)) {
443     iTy = shapedTy.clone(iTy);
444   }
445 
446   unsigned bitWidth = operandETy.getIntOrFloatBitWidth();
447   // The width returned by getFPMantissaWidth includes the integer bit.
448   unsigned mantissaWidth =
449       llvm::cast<FloatType>(operandETy).getFPMantissaWidth() - 1;
450   unsigned exponentWidth = bitWidth - mantissaWidth - 1;
451 
452   // The names of the variables correspond to f32.
453   // f64: 1 bit sign | 11 bits exponent | 52 bits mantissa.
454   // f32: 1 bit sign | 8 bits exponent  | 23 bits mantissa.
455   // f16: 1 bit sign | 5 bits exponent  | 10 bits mantissa.
456   Value c1Float = createFloatConst(loc, fTy, 1.0, b);
457   Value c0 = createIntConst(loc, iTy, 0, b);
458   Value c1 = createIntConst(loc, iTy, 1, b);
459   Value cNeg1 = createIntConst(loc, iTy, -1, b);
460   Value c23 = createIntConst(loc, iTy, mantissaWidth, b);
461   Value c31 = createIntConst(loc, iTy, bitWidth - 1, b);
462   Value c127 = createIntConst(loc, iTy, (1ull << (exponentWidth - 1)) - 1, b);
463   Value c2To22 = createIntConst(loc, iTy, 1ull << (mantissaWidth - 1), b);
464   Value c23Mask = createIntConst(loc, iTy, (1ull << mantissaWidth) - 1, b);
465   Value expMask = createIntConst(loc, iTy, (1ull << exponentWidth) - 1, b);
466 
467   Value operandBitcast = b.create<arith::BitcastOp>(iTy, operand);
468   Value round = b.create<math::RoundOp>(operand);
469   Value roundBitcast = b.create<arith::BitcastOp>(iTy, round);
470 
471   // Get biased exponents for operand and round(operand)
472   Value operandExp = b.create<arith::AndIOp>(
473       b.create<arith::ShRUIOp>(operandBitcast, c23), expMask);
474   Value operandBiasedExp = b.create<arith::SubIOp>(operandExp, c127);
475   Value roundExp = b.create<arith::AndIOp>(
476       b.create<arith::ShRUIOp>(roundBitcast, c23), expMask);
477   Value roundBiasedExp = b.create<arith::SubIOp>(roundExp, c127);
478 
479   auto safeShiftRight = [&](Value x, Value shift) -> Value {
480     // Clamp shift to valid range [0, bitwidth - 1] to avoid undefined behavior
481     Value clampedShift = b.create<arith::MaxSIOp>(shift, c0);
482     clampedShift = b.create<arith::MinSIOp>(clampedShift, c31);
483     return b.create<arith::ShRUIOp>(x, clampedShift);
484   };
485 
486   auto maskMantissa = [&](Value mantissa,
487                           Value mantissaMaskRightShift) -> Value {
488     Value shiftedMantissaMask = safeShiftRight(c23Mask, mantissaMaskRightShift);
489     return b.create<arith::AndIOp>(mantissa, shiftedMantissaMask);
490   };
491 
492   // A whole number `x`, such that `|x| != 1`, is even if the mantissa, ignoring
493   // the leftmost `clamp(biasedExp - 1, 0, 23)` bits, is zero. Large numbers
494   // with `biasedExp > 23` (numbers where there is not enough precision to store
495   // decimals) are always even, and they satisfy the even condition trivially
496   // since the mantissa without all its bits is zero. The even condition
497   // is also true for +-0, since they have `biasedExp = -127` and the entire
498   // mantissa is zero. The case of +-1 has to be handled separately. Here
499   // we identify these values by noting that +-1 are the only whole numbers with
500   // `biasedExp == 0`.
501   //
502   // The special values +-inf and +-nan also satisfy the same property that
503   // whole non-unit even numbers satisfy. In particular, the special values have
504   // `biasedExp > 23`, so they get treated as large numbers with no room for
505   // decimals, which are always even.
506   Value roundBiasedExpEq0 =
507       b.create<arith::CmpIOp>(arith::CmpIPredicate::eq, roundBiasedExp, c0);
508   Value roundBiasedExpMinus1 = b.create<arith::SubIOp>(roundBiasedExp, c1);
509   Value roundMaskedMantissa = maskMantissa(roundBitcast, roundBiasedExpMinus1);
510   Value roundIsNotEvenOrSpecialVal = b.create<arith::CmpIOp>(
511       arith::CmpIPredicate::ne, roundMaskedMantissa, c0);
512   roundIsNotEvenOrSpecialVal =
513       b.create<arith::OrIOp>(roundIsNotEvenOrSpecialVal, roundBiasedExpEq0);
514 
515   // A value `x` with `0 <= biasedExp < 23`, is halfway between two consecutive
516   // integers if the bit at index `biasedExp` starting from the left in the
517   // mantissa is 1 and all the bits to the right are zero. Values with
518   // `biasedExp >= 23` don't have decimals, so they are never halfway. The
519   // values +-0.5 are the only halfway values that have `biasedExp == -1 < 0`,
520   // so these are handled separately. In particular, if `biasedExp == -1`, the
521   // value is halfway if the entire mantissa is zero.
522   Value operandBiasedExpEqNeg1 = b.create<arith::CmpIOp>(
523       arith::CmpIPredicate::eq, operandBiasedExp, cNeg1);
524   Value expectedOperandMaskedMantissa = b.create<arith::SelectOp>(
525       operandBiasedExpEqNeg1, c0, safeShiftRight(c2To22, operandBiasedExp));
526   Value operandMaskedMantissa = maskMantissa(operandBitcast, operandBiasedExp);
527   Value operandIsHalfway =
528       b.create<arith::CmpIOp>(arith::CmpIPredicate::eq, operandMaskedMantissa,
529                               expectedOperandMaskedMantissa);
530   // Ensure `biasedExp` is in the valid range for half values.
531   Value operandBiasedExpGeNeg1 = b.create<arith::CmpIOp>(
532       arith::CmpIPredicate::sge, operandBiasedExp, cNeg1);
533   Value operandBiasedExpLt23 =
534       b.create<arith::CmpIOp>(arith::CmpIPredicate::slt, operandBiasedExp, c23);
535   operandIsHalfway =
536       b.create<arith::AndIOp>(operandIsHalfway, operandBiasedExpLt23);
537   operandIsHalfway =
538       b.create<arith::AndIOp>(operandIsHalfway, operandBiasedExpGeNeg1);
539 
540   // Adjust rounded operand with `round(operand) - sign(operand)` to correct the
541   // case where `round` rounded in the opposite direction of `roundeven`.
542   Value sign = b.create<math::CopySignOp>(c1Float, operand);
543   Value roundShifted = b.create<arith::SubFOp>(round, sign);
544   // If the rounded value is even or a special value, we default to the behavior
545   // of `math.round`.
546   Value needsShift =
547       b.create<arith::AndIOp>(roundIsNotEvenOrSpecialVal, operandIsHalfway);
548   Value result = b.create<arith::SelectOp>(needsShift, roundShifted, round);
549   // The `x - sign` adjustment does not preserve the sign when we are adjusting
550   // the value -1 to -0. So here the sign is copied again to ensure that -0.5 is
551   // rounded to -0.0.
552   result = b.create<math::CopySignOp>(result, operand);
553   rewriter.replaceOp(op, result);
554   return success();
555 }
556 
557 void mlir::populateExpandCtlzPattern(RewritePatternSet &patterns) {
558   patterns.add(convertCtlzOp);
559 }
560 
561 void mlir::populateExpandSinhPattern(RewritePatternSet &patterns) {
562   patterns.add(convertSinhOp);
563 }
564 
565 void mlir::populateExpandCoshPattern(RewritePatternSet &patterns) {
566   patterns.add(convertCoshOp);
567 }
568 
569 void mlir::populateExpandTanPattern(RewritePatternSet &patterns) {
570   patterns.add(convertTanOp);
571 }
572 
573 void mlir::populateExpandTanhPattern(RewritePatternSet &patterns) {
574   patterns.add(convertTanhOp);
575 }
576 
577 void mlir::populateExpandFmaFPattern(RewritePatternSet &patterns) {
578   patterns.add(convertFmaFOp);
579 }
580 
581 void mlir::populateExpandCeilFPattern(RewritePatternSet &patterns) {
582   patterns.add(convertCeilOp);
583 }
584 
585 void mlir::populateExpandExp2FPattern(RewritePatternSet &patterns) {
586   patterns.add(convertExp2fOp);
587 }
588 
589 void mlir::populateExpandPowFPattern(RewritePatternSet &patterns) {
590   patterns.add(convertPowfOp);
591 }
592 
593 void mlir::populateExpandFPowIPattern(RewritePatternSet &patterns) {
594   patterns.add(convertFPowICstOp);
595 }
596 
597 void mlir::populateExpandRoundFPattern(RewritePatternSet &patterns) {
598   patterns.add(convertRoundOp);
599 }
600 
601 void mlir::populateExpandFloorFPattern(RewritePatternSet &patterns) {
602   patterns.add(convertFloorOp);
603 }
604 
605 void mlir::populateExpandRoundEvenPattern(RewritePatternSet &patterns) {
606   patterns.add(convertRoundEvenOp);
607 }
608