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