1f99ccf65SEugene Zhulenev //===- PolynomialApproximation.cpp - Approximate math operations ----------===//
2f99ccf65SEugene Zhulenev //
3f99ccf65SEugene Zhulenev // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4f99ccf65SEugene Zhulenev // See https://llvm.org/LICENSE.txt for license information.
5f99ccf65SEugene Zhulenev // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6f99ccf65SEugene Zhulenev //
7f99ccf65SEugene Zhulenev //===----------------------------------------------------------------------===//
8f99ccf65SEugene Zhulenev //
9f99ccf65SEugene Zhulenev // This file implements expansion of math operations to fast approximations
10f99ccf65SEugene Zhulenev // that do not rely on any of the library functions.
11f99ccf65SEugene Zhulenev //
12f99ccf65SEugene Zhulenev //===----------------------------------------------------------------------===//
133a506b31SChris Lattner 
14ec32d540SEugene Zhulenev #include <climits>
15ec32d540SEugene Zhulenev #include <cstddef>
16ec32d540SEugene Zhulenev 
17a54f4eaeSMogball #include "mlir/Dialect/Arithmetic/IR/Arithmetic.h"
18f99ccf65SEugene Zhulenev #include "mlir/Dialect/Math/IR/Math.h"
19f1b92218SBoian Petkantchin #include "mlir/Dialect/Math/Transforms/Approximation.h"
20f99ccf65SEugene Zhulenev #include "mlir/Dialect/Math/Transforms/Passes.h"
21f99ccf65SEugene Zhulenev #include "mlir/Dialect/Vector/VectorOps.h"
22627fa0b9SEugene Zhulenev #include "mlir/Dialect/Vector/VectorUtils.h"
2335553d45SEmilio Cota #include "mlir/Dialect/X86Vector/X86VectorDialect.h"
24f99ccf65SEugene Zhulenev #include "mlir/IR/Builders.h"
25ce976d2dSEugene Zhulenev #include "mlir/IR/ImplicitLocOpBuilder.h"
26ec32d540SEugene Zhulenev #include "mlir/IR/TypeUtilities.h"
27f99ccf65SEugene Zhulenev #include "mlir/Transforms/DialectConversion.h"
28f99ccf65SEugene Zhulenev #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
29f1b92218SBoian Petkantchin #include "llvm/ADT/ArrayRef.h"
30f99ccf65SEugene Zhulenev 
31f99ccf65SEugene Zhulenev using namespace mlir;
32f1b92218SBoian Petkantchin using namespace mlir::math;
33f99ccf65SEugene Zhulenev using namespace mlir::vector;
34f99ccf65SEugene Zhulenev 
35ec32d540SEugene Zhulenev // Returns vector shape if the type is a vector. Returns an empty shape if it is
36ec32d540SEugene Zhulenev // not a vector.
37ec32d540SEugene Zhulenev static ArrayRef<int64_t> vectorShape(Type type) {
38ce976d2dSEugene Zhulenev   auto vectorType = type.dyn_cast<VectorType>();
39ec32d540SEugene Zhulenev   return vectorType ? vectorType.getShape() : ArrayRef<int64_t>();
40ce976d2dSEugene Zhulenev }
41ce976d2dSEugene Zhulenev 
42ec32d540SEugene Zhulenev static ArrayRef<int64_t> vectorShape(Value value) {
43ec32d540SEugene Zhulenev   return vectorShape(value.getType());
4439b2cd40SEugene Zhulenev }
4539b2cd40SEugene Zhulenev 
46f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
47ce976d2dSEugene Zhulenev // Broadcast scalar types and values into vector types and values.
48f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
49f99ccf65SEugene Zhulenev 
5096cee297SAlexander Belyaev // Broadcasts scalar type into vector type (iff shape is non-scalar).
5196cee297SAlexander Belyaev static Type broadcast(Type type, ArrayRef<int64_t> shape) {
5296cee297SAlexander Belyaev   assert(!type.isa<VectorType>() && "must be scalar type");
53ec32d540SEugene Zhulenev   return !shape.empty() ? VectorType::get(shape, type) : type;
5496cee297SAlexander Belyaev }
5596cee297SAlexander Belyaev 
5696cee297SAlexander Belyaev // Broadcasts scalar value into vector (iff shape is non-scalar).
5796cee297SAlexander Belyaev static Value broadcast(ImplicitLocOpBuilder &builder, Value value,
5896cee297SAlexander Belyaev                        ArrayRef<int64_t> shape) {
59ce976d2dSEugene Zhulenev   assert(!value.getType().isa<VectorType>() && "must be scalar value");
6096cee297SAlexander Belyaev   auto type = broadcast(value.getType(), shape);
61ec32d540SEugene Zhulenev   return !shape.empty() ? builder.create<BroadcastOp>(type, value) : value;
62ce976d2dSEugene Zhulenev }
63f99ccf65SEugene Zhulenev 
64ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
65627fa0b9SEugene Zhulenev // Helper function to handle n-D vectors with 1-D operations.
66627fa0b9SEugene Zhulenev //----------------------------------------------------------------------------//
67627fa0b9SEugene Zhulenev 
68627fa0b9SEugene Zhulenev // Expands and unrolls n-D vector operands into multiple fixed size 1-D vectors
69627fa0b9SEugene Zhulenev // and calls the compute function with 1-D vector operands. Stitches back all
70627fa0b9SEugene Zhulenev // results into the original n-D vector result.
71627fa0b9SEugene Zhulenev //
72627fa0b9SEugene Zhulenev // Examples: vectorWidth = 8
73627fa0b9SEugene Zhulenev //   - vector<4x8xf32> unrolled 4 times
74627fa0b9SEugene Zhulenev //   - vector<16xf32> expanded to vector<2x8xf32> and unrolled 2 times
75627fa0b9SEugene Zhulenev //   - vector<4x16xf32> expanded to vector<4x2x8xf32> and unrolled 4*2 times
76627fa0b9SEugene Zhulenev //
77627fa0b9SEugene Zhulenev // Some math approximations rely on ISA-specific operations that only accept
78627fa0b9SEugene Zhulenev // fixed size 1-D vectors (e.g. AVX expects vectors of width 8).
79627fa0b9SEugene Zhulenev //
80627fa0b9SEugene Zhulenev // It is the caller's responsibility to verify that the inner dimension is
81627fa0b9SEugene Zhulenev // divisible by the vectorWidth, and that all operands have the same vector
82627fa0b9SEugene Zhulenev // shape.
83627fa0b9SEugene Zhulenev static Value
84627fa0b9SEugene Zhulenev handleMultidimensionalVectors(ImplicitLocOpBuilder &builder,
85627fa0b9SEugene Zhulenev                               ValueRange operands, int64_t vectorWidth,
86627fa0b9SEugene Zhulenev                               std::function<Value(ValueRange)> compute) {
87627fa0b9SEugene Zhulenev   assert(!operands.empty() && "operands must be not empty");
88627fa0b9SEugene Zhulenev   assert(vectorWidth > 0 && "vector width must be larger than 0");
89627fa0b9SEugene Zhulenev 
90627fa0b9SEugene Zhulenev   VectorType inputType = operands[0].getType().cast<VectorType>();
91627fa0b9SEugene Zhulenev   ArrayRef<int64_t> inputShape = inputType.getShape();
92627fa0b9SEugene Zhulenev 
93627fa0b9SEugene Zhulenev   // If input shape matches target vector width, we can just call the
94627fa0b9SEugene Zhulenev   // user-provided compute function with the operands.
95627fa0b9SEugene Zhulenev   if (inputShape == llvm::makeArrayRef(vectorWidth))
96627fa0b9SEugene Zhulenev     return compute(operands);
97627fa0b9SEugene Zhulenev 
98627fa0b9SEugene Zhulenev   // Check if the inner dimension has to be expanded, or we can directly iterate
99627fa0b9SEugene Zhulenev   // over the outer dimensions of the vector.
100627fa0b9SEugene Zhulenev   int64_t innerDim = inputShape.back();
101627fa0b9SEugene Zhulenev   int64_t expansionDim = innerDim / vectorWidth;
102627fa0b9SEugene Zhulenev   assert((innerDim % vectorWidth == 0) && "invalid inner dimension size");
103627fa0b9SEugene Zhulenev 
104627fa0b9SEugene Zhulenev   // Maybe expand operands to the higher rank vector shape that we'll use to
105627fa0b9SEugene Zhulenev   // iterate over and extract one dimensional vectors.
106627fa0b9SEugene Zhulenev   SmallVector<int64_t> expandedShape(inputShape.begin(), inputShape.end());
107627fa0b9SEugene Zhulenev   SmallVector<Value> expandedOperands(operands);
108627fa0b9SEugene Zhulenev 
109627fa0b9SEugene Zhulenev   if (expansionDim > 1) {
110627fa0b9SEugene Zhulenev     // Expand shape from [..., innerDim] to [..., expansionDim, vectorWidth].
111627fa0b9SEugene Zhulenev     expandedShape.insert(expandedShape.end() - 1, expansionDim);
112627fa0b9SEugene Zhulenev     expandedShape.back() = vectorWidth;
113627fa0b9SEugene Zhulenev 
114627fa0b9SEugene Zhulenev     for (unsigned i = 0; i < operands.size(); ++i) {
115627fa0b9SEugene Zhulenev       auto operand = operands[i];
116627fa0b9SEugene Zhulenev       auto eltType = operand.getType().cast<VectorType>().getElementType();
117627fa0b9SEugene Zhulenev       auto expandedType = VectorType::get(expandedShape, eltType);
118627fa0b9SEugene Zhulenev       expandedOperands[i] =
119627fa0b9SEugene Zhulenev           builder.create<vector::ShapeCastOp>(expandedType, operand);
120627fa0b9SEugene Zhulenev     }
121627fa0b9SEugene Zhulenev   }
122627fa0b9SEugene Zhulenev 
123627fa0b9SEugene Zhulenev   // Iterate over all outer dimensions of the compute shape vector type.
124627fa0b9SEugene Zhulenev   auto iterationDims = ArrayRef<int64_t>(expandedShape).drop_back();
125627fa0b9SEugene Zhulenev   int64_t maxLinearIndex = computeMaxLinearIndex(iterationDims);
126627fa0b9SEugene Zhulenev 
127627fa0b9SEugene Zhulenev   SmallVector<int64_t> ones(iterationDims.size(), 1);
128627fa0b9SEugene Zhulenev   auto strides = computeStrides(iterationDims, ones);
129627fa0b9SEugene Zhulenev 
130627fa0b9SEugene Zhulenev   // Compute results for each one dimensional vector.
131627fa0b9SEugene Zhulenev   SmallVector<Value> results(maxLinearIndex);
132627fa0b9SEugene Zhulenev 
133627fa0b9SEugene Zhulenev   for (int64_t i = 0; i < maxLinearIndex; ++i) {
134627fa0b9SEugene Zhulenev     auto offsets = delinearize(strides, i);
135627fa0b9SEugene Zhulenev 
136627fa0b9SEugene Zhulenev     SmallVector<Value> extracted(expandedOperands.size());
137627fa0b9SEugene Zhulenev     for (auto tuple : llvm::enumerate(expandedOperands))
138627fa0b9SEugene Zhulenev       extracted[tuple.index()] =
139627fa0b9SEugene Zhulenev           builder.create<vector::ExtractOp>(tuple.value(), offsets);
140627fa0b9SEugene Zhulenev 
141627fa0b9SEugene Zhulenev     results[i] = compute(extracted);
142627fa0b9SEugene Zhulenev   }
143627fa0b9SEugene Zhulenev 
144627fa0b9SEugene Zhulenev   // Stitch results together into one large vector.
145627fa0b9SEugene Zhulenev   Type resultEltType = results[0].getType().cast<VectorType>().getElementType();
146627fa0b9SEugene Zhulenev   Type resultExpandedType = VectorType::get(expandedShape, resultEltType);
147627fa0b9SEugene Zhulenev   Value result = builder.create<ConstantOp>(
148627fa0b9SEugene Zhulenev       resultExpandedType, builder.getZeroAttr(resultExpandedType));
149627fa0b9SEugene Zhulenev 
150627fa0b9SEugene Zhulenev   for (int64_t i = 0; i < maxLinearIndex; ++i)
151627fa0b9SEugene Zhulenev     result = builder.create<vector::InsertOp>(results[i], result,
152627fa0b9SEugene Zhulenev                                               delinearize(strides, i));
153627fa0b9SEugene Zhulenev 
154627fa0b9SEugene Zhulenev   // Reshape back to the original vector shape.
155627fa0b9SEugene Zhulenev   return builder.create<vector::ShapeCastOp>(
156627fa0b9SEugene Zhulenev       VectorType::get(inputShape, resultEltType), result);
157627fa0b9SEugene Zhulenev }
158627fa0b9SEugene Zhulenev 
159627fa0b9SEugene Zhulenev //----------------------------------------------------------------------------//
160ce976d2dSEugene Zhulenev // Helper functions to create constants.
161ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
162f99ccf65SEugene Zhulenev 
163ce976d2dSEugene Zhulenev static Value f32Cst(ImplicitLocOpBuilder &builder, float value) {
164a54f4eaeSMogball   return builder.create<arith::ConstantOp>(builder.getF32FloatAttr(value));
165ce976d2dSEugene Zhulenev }
166f99ccf65SEugene Zhulenev 
167ce976d2dSEugene Zhulenev static Value i32Cst(ImplicitLocOpBuilder &builder, int32_t value) {
168a54f4eaeSMogball   return builder.create<arith::ConstantOp>(builder.getI32IntegerAttr(value));
169ce976d2dSEugene Zhulenev }
170f99ccf65SEugene Zhulenev 
171ce976d2dSEugene Zhulenev static Value f32FromBits(ImplicitLocOpBuilder &builder, uint32_t bits) {
172ce976d2dSEugene Zhulenev   Value i32Value = i32Cst(builder, static_cast<int32_t>(bits));
173a54f4eaeSMogball   return builder.create<arith::BitcastOp>(builder.getF32Type(), i32Value);
174ce976d2dSEugene Zhulenev }
175f99ccf65SEugene Zhulenev 
176ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
177ce976d2dSEugene Zhulenev // Helper functions to build math functions approximations.
178ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
179ce976d2dSEugene Zhulenev 
180ce976d2dSEugene Zhulenev static Value min(ImplicitLocOpBuilder &builder, Value a, Value b) {
181ce976d2dSEugene Zhulenev   return builder.create<SelectOp>(
182a54f4eaeSMogball       builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, a, b), a, b);
183ce976d2dSEugene Zhulenev }
184ce976d2dSEugene Zhulenev 
185ce976d2dSEugene Zhulenev static Value max(ImplicitLocOpBuilder &builder, Value a, Value b) {
186ce976d2dSEugene Zhulenev   return builder.create<SelectOp>(
187a54f4eaeSMogball       builder.create<arith::CmpFOp>(arith::CmpFPredicate::OGT, a, b), a, b);
188ce976d2dSEugene Zhulenev }
189ce976d2dSEugene Zhulenev 
190ce976d2dSEugene Zhulenev static Value clamp(ImplicitLocOpBuilder &builder, Value value, Value lowerBound,
191ce976d2dSEugene Zhulenev                    Value upperBound) {
192ce976d2dSEugene Zhulenev   return max(builder, min(builder, value, upperBound), lowerBound);
193ce976d2dSEugene Zhulenev }
194ce976d2dSEugene Zhulenev 
195ce976d2dSEugene Zhulenev // Decomposes given floating point value `arg` into a normalized fraction and
196ce976d2dSEugene Zhulenev // an integral power of two (see std::frexp). Returned values have float type.
197ce976d2dSEugene Zhulenev static std::pair<Value, Value> frexp(ImplicitLocOpBuilder &builder, Value arg,
19802b6fb21SMehdi Amini                                      bool isPositive = false) {
199ec32d540SEugene Zhulenev   assert(getElementTypeOrSelf(arg).isF32() && "arg must be f32 type");
200ec32d540SEugene Zhulenev   ArrayRef<int64_t> shape = vectorShape(arg);
201ce976d2dSEugene Zhulenev 
202ce976d2dSEugene Zhulenev   auto bcast = [&](Value value) -> Value {
20396cee297SAlexander Belyaev     return broadcast(builder, value, shape);
204f99ccf65SEugene Zhulenev   };
205f99ccf65SEugene Zhulenev 
206ce976d2dSEugene Zhulenev   auto i32 = builder.getIntegerType(32);
20796cee297SAlexander Belyaev   auto i32Vec = broadcast(i32, shape);
20896cee297SAlexander Belyaev   auto f32Vec = broadcast(builder.getF32Type(), shape);
209f99ccf65SEugene Zhulenev 
210ce976d2dSEugene Zhulenev   Value cst126f = f32Cst(builder, 126.0f);
211ce976d2dSEugene Zhulenev   Value cstHalf = f32Cst(builder, 0.5f);
212ce976d2dSEugene Zhulenev   Value cstInvMantMask = f32FromBits(builder, ~0x7f800000u);
213f99ccf65SEugene Zhulenev 
214ce976d2dSEugene Zhulenev   // Bitcast to i32 for bitwise operations.
215a54f4eaeSMogball   Value i32Half = builder.create<arith::BitcastOp>(i32, cstHalf);
216a54f4eaeSMogball   Value i32InvMantMask = builder.create<arith::BitcastOp>(i32, cstInvMantMask);
217a54f4eaeSMogball   Value i32Arg = builder.create<arith::BitcastOp>(i32Vec, arg);
218f99ccf65SEugene Zhulenev 
219ce976d2dSEugene Zhulenev   // Compute normalized fraction.
220a54f4eaeSMogball   Value tmp0 = builder.create<arith::AndIOp>(i32Arg, bcast(i32InvMantMask));
221a54f4eaeSMogball   Value tmp1 = builder.create<arith::OrIOp>(tmp0, bcast(i32Half));
222a54f4eaeSMogball   Value normalizedFraction = builder.create<arith::BitcastOp>(f32Vec, tmp1);
223f99ccf65SEugene Zhulenev 
224ce976d2dSEugene Zhulenev   // Compute exponent.
22502b6fb21SMehdi Amini   Value arg0 = isPositive ? arg : builder.create<math::AbsOp>(arg);
226a54f4eaeSMogball   Value biasedExponentBits = builder.create<arith::ShRUIOp>(
227a54f4eaeSMogball       builder.create<arith::BitcastOp>(i32Vec, arg0),
228a54f4eaeSMogball       bcast(i32Cst(builder, 23)));
229a54f4eaeSMogball   Value biasedExponent =
230a54f4eaeSMogball       builder.create<arith::SIToFPOp>(f32Vec, biasedExponentBits);
231a54f4eaeSMogball   Value exponent =
232a54f4eaeSMogball       builder.create<arith::SubFOp>(biasedExponent, bcast(cst126f));
233f99ccf65SEugene Zhulenev 
234ce976d2dSEugene Zhulenev   return {normalizedFraction, exponent};
235f99ccf65SEugene Zhulenev }
236f99ccf65SEugene Zhulenev 
237ea7f211bSAhmed Taei // Computes exp2 for an i32 argument.
238ea7f211bSAhmed Taei static Value exp2I32(ImplicitLocOpBuilder &builder, Value arg) {
239ec32d540SEugene Zhulenev   assert(getElementTypeOrSelf(arg).isInteger(32) && "arg must be i32 type");
240ec32d540SEugene Zhulenev   ArrayRef<int64_t> shape = vectorShape(arg);
241ea7f211bSAhmed Taei 
242ea7f211bSAhmed Taei   auto bcast = [&](Value value) -> Value {
24396cee297SAlexander Belyaev     return broadcast(builder, value, shape);
244ea7f211bSAhmed Taei   };
245ea7f211bSAhmed Taei 
24696cee297SAlexander Belyaev   auto f32Vec = broadcast(builder.getF32Type(), shape);
247ea7f211bSAhmed Taei   // The exponent of f32 located at 23-bit.
248ea7f211bSAhmed Taei   auto exponetBitLocation = bcast(i32Cst(builder, 23));
249ea7f211bSAhmed Taei   // Set the exponent bias to zero.
250ea7f211bSAhmed Taei   auto bias = bcast(i32Cst(builder, 127));
251ea7f211bSAhmed Taei 
252a54f4eaeSMogball   Value biasedArg = builder.create<arith::AddIOp>(arg, bias);
253ea7f211bSAhmed Taei   Value exp2ValueInt =
254a54f4eaeSMogball       builder.create<arith::ShLIOp>(biasedArg, exponetBitLocation);
255a54f4eaeSMogball   Value exp2ValueF32 = builder.create<arith::BitcastOp>(f32Vec, exp2ValueInt);
256ea7f211bSAhmed Taei 
257ea7f211bSAhmed Taei   return exp2ValueF32;
258ea7f211bSAhmed Taei }
259ea7f211bSAhmed Taei 
260f1b92218SBoian Petkantchin namespace {
261f1b92218SBoian Petkantchin Value makePolynomialCalculation(ImplicitLocOpBuilder &builder,
262f1b92218SBoian Petkantchin                                 llvm::ArrayRef<Value> coeffs, Value x) {
263ec32d540SEugene Zhulenev   assert(getElementTypeOrSelf(x).isF32() && "x must be f32 type");
264ec32d540SEugene Zhulenev   ArrayRef<int64_t> shape = vectorShape(x);
265ec32d540SEugene Zhulenev 
266ec32d540SEugene Zhulenev   if (coeffs.empty())
267ec32d540SEugene Zhulenev     return broadcast(builder, f32Cst(builder, 0.0f), shape);
268ec32d540SEugene Zhulenev 
269ec32d540SEugene Zhulenev   if (coeffs.size() == 1)
270f1b92218SBoian Petkantchin     return coeffs[0];
271ec32d540SEugene Zhulenev 
272f1b92218SBoian Petkantchin   Value res = builder.create<math::FmaOp>(x, coeffs[coeffs.size() - 1],
273f1b92218SBoian Petkantchin                                           coeffs[coeffs.size() - 2]);
274f1b92218SBoian Petkantchin   for (auto i = ptrdiff_t(coeffs.size()) - 3; i >= 0; --i) {
275f1b92218SBoian Petkantchin     res = builder.create<math::FmaOp>(x, res, coeffs[i]);
276f1b92218SBoian Petkantchin   }
277f1b92218SBoian Petkantchin   return res;
278f1b92218SBoian Petkantchin }
279f1b92218SBoian Petkantchin } // namespace
280f1b92218SBoian Petkantchin 
281f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
282f99ccf65SEugene Zhulenev // TanhOp approximation.
283f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
284f99ccf65SEugene Zhulenev 
285f99ccf65SEugene Zhulenev namespace {
286f99ccf65SEugene Zhulenev struct TanhApproximation : public OpRewritePattern<math::TanhOp> {
287f99ccf65SEugene Zhulenev public:
288f99ccf65SEugene Zhulenev   using OpRewritePattern::OpRewritePattern;
289f99ccf65SEugene Zhulenev 
290f99ccf65SEugene Zhulenev   LogicalResult matchAndRewrite(math::TanhOp op,
291f99ccf65SEugene Zhulenev                                 PatternRewriter &rewriter) const final;
292f99ccf65SEugene Zhulenev };
293f99ccf65SEugene Zhulenev } // namespace
294f99ccf65SEugene Zhulenev 
295f99ccf65SEugene Zhulenev LogicalResult
296f99ccf65SEugene Zhulenev TanhApproximation::matchAndRewrite(math::TanhOp op,
297f99ccf65SEugene Zhulenev                                    PatternRewriter &rewriter) const {
29862fea88bSJacques Pienaar   if (!getElementTypeOrSelf(op.getOperand()).isF32())
299f99ccf65SEugene Zhulenev     return rewriter.notifyMatchFailure(op, "unsupported operand type");
300f99ccf65SEugene Zhulenev 
30162fea88bSJacques Pienaar   ArrayRef<int64_t> shape = vectorShape(op.getOperand());
302ec32d540SEugene Zhulenev 
303ce976d2dSEugene Zhulenev   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
304ce976d2dSEugene Zhulenev   auto bcast = [&](Value value) -> Value {
305ec32d540SEugene Zhulenev     return broadcast(builder, value, shape);
306ce976d2dSEugene Zhulenev   };
307f99ccf65SEugene Zhulenev 
308f99ccf65SEugene Zhulenev   // Clamp operand into [plusClamp, minusClamp] range.
309bf32bb7eSEugene Zhulenev   Value minusClamp = bcast(f32Cst(builder, -7.99881172180175781f));
310bf32bb7eSEugene Zhulenev   Value plusClamp = bcast(f32Cst(builder, 7.99881172180175781f));
31162fea88bSJacques Pienaar   Value x = clamp(builder, op.getOperand(), minusClamp, plusClamp);
312f99ccf65SEugene Zhulenev 
313f99ccf65SEugene Zhulenev   // Mask for tiny values that are approximated with `operand`.
314ce976d2dSEugene Zhulenev   Value tiny = bcast(f32Cst(builder, 0.0004f));
315a54f4eaeSMogball   Value tinyMask = builder.create<arith::CmpFOp>(
31662fea88bSJacques Pienaar       arith::CmpFPredicate::OLT, builder.create<math::AbsOp>(op.getOperand()),
317a54f4eaeSMogball       tiny);
318f99ccf65SEugene Zhulenev 
319f99ccf65SEugene Zhulenev   // The monomial coefficients of the numerator polynomial (odd).
320ce976d2dSEugene Zhulenev   Value alpha1 = bcast(f32Cst(builder, 4.89352455891786e-03f));
321ce976d2dSEugene Zhulenev   Value alpha3 = bcast(f32Cst(builder, 6.37261928875436e-04f));
322ce976d2dSEugene Zhulenev   Value alpha5 = bcast(f32Cst(builder, 1.48572235717979e-05f));
323ce976d2dSEugene Zhulenev   Value alpha7 = bcast(f32Cst(builder, 5.12229709037114e-08f));
324ce976d2dSEugene Zhulenev   Value alpha9 = bcast(f32Cst(builder, -8.60467152213735e-11f));
325ce976d2dSEugene Zhulenev   Value alpha11 = bcast(f32Cst(builder, 2.00018790482477e-13f));
326ce976d2dSEugene Zhulenev   Value alpha13 = bcast(f32Cst(builder, -2.76076847742355e-16f));
327f99ccf65SEugene Zhulenev 
328f99ccf65SEugene Zhulenev   // The monomial coefficients of the denominator polynomial (even).
329ce976d2dSEugene Zhulenev   Value beta0 = bcast(f32Cst(builder, 4.89352518554385e-03f));
330ce976d2dSEugene Zhulenev   Value beta2 = bcast(f32Cst(builder, 2.26843463243900e-03f));
331ce976d2dSEugene Zhulenev   Value beta4 = bcast(f32Cst(builder, 1.18534705686654e-04f));
332ce976d2dSEugene Zhulenev   Value beta6 = bcast(f32Cst(builder, 1.19825839466702e-06f));
333f99ccf65SEugene Zhulenev 
334f99ccf65SEugene Zhulenev   // Since the polynomials are odd/even, we need x^2.
335a54f4eaeSMogball   Value x2 = builder.create<arith::MulFOp>(x, x);
336f99ccf65SEugene Zhulenev 
337f99ccf65SEugene Zhulenev   // Evaluate the numerator polynomial p.
338a54f4eaeSMogball   Value p = builder.create<math::FmaOp>(x2, alpha13, alpha11);
339a54f4eaeSMogball   p = builder.create<math::FmaOp>(x2, p, alpha9);
340a54f4eaeSMogball   p = builder.create<math::FmaOp>(x2, p, alpha7);
341a54f4eaeSMogball   p = builder.create<math::FmaOp>(x2, p, alpha5);
342a54f4eaeSMogball   p = builder.create<math::FmaOp>(x2, p, alpha3);
343a54f4eaeSMogball   p = builder.create<math::FmaOp>(x2, p, alpha1);
344a54f4eaeSMogball   p = builder.create<arith::MulFOp>(x, p);
345f99ccf65SEugene Zhulenev 
346f99ccf65SEugene Zhulenev   // Evaluate the denominator polynomial q.
347a54f4eaeSMogball   Value q = builder.create<math::FmaOp>(x2, beta6, beta4);
348a54f4eaeSMogball   q = builder.create<math::FmaOp>(x2, q, beta2);
349a54f4eaeSMogball   q = builder.create<math::FmaOp>(x2, q, beta0);
350f99ccf65SEugene Zhulenev 
351f99ccf65SEugene Zhulenev   // Divide the numerator by the denominator.
352a54f4eaeSMogball   Value res = builder.create<SelectOp>(tinyMask, x,
353a54f4eaeSMogball                                        builder.create<arith::DivFOp>(p, q));
354f99ccf65SEugene Zhulenev 
355f99ccf65SEugene Zhulenev   rewriter.replaceOp(op, res);
356f99ccf65SEugene Zhulenev 
357f99ccf65SEugene Zhulenev   return success();
358f99ccf65SEugene Zhulenev }
359f99ccf65SEugene Zhulenev 
360ea7f211bSAhmed Taei #define LN2_VALUE                                                              \
361ea7f211bSAhmed Taei   0.693147180559945309417232121458176568075500134360255254120680009493393621L
362c0891706SEmilio Cota #define LOG2E_VALUE                                                            \
363ea7f211bSAhmed Taei   1.442695040888963407359924681001892137426645954152985934135449406931109219L
364ea7f211bSAhmed Taei 
365f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------//
366c0891706SEmilio Cota // LogOp and Log2Op approximation.
367ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
368ce976d2dSEugene Zhulenev 
369ce976d2dSEugene Zhulenev namespace {
370c0891706SEmilio Cota template <typename Op>
371c0891706SEmilio Cota struct LogApproximationBase : public OpRewritePattern<Op> {
372c0891706SEmilio Cota   using OpRewritePattern<Op>::OpRewritePattern;
373ce976d2dSEugene Zhulenev 
374c0891706SEmilio Cota   /// Base 2 if 'base2' is set; natural logarithm (base e) otherwise.
375c0891706SEmilio Cota   LogicalResult logMatchAndRewrite(Op op, PatternRewriter &rewriter,
376c0891706SEmilio Cota                                    bool base2) const;
377ce976d2dSEugene Zhulenev };
378ce976d2dSEugene Zhulenev } // namespace
379ce976d2dSEugene Zhulenev 
380c0891706SEmilio Cota // This approximation comes from Julien Pommier's SSE math library.
381c0891706SEmilio Cota // Link: http://gruntthepeon.free.fr/ssemath
382c0891706SEmilio Cota template <typename Op>
383ce976d2dSEugene Zhulenev LogicalResult
384c0891706SEmilio Cota LogApproximationBase<Op>::logMatchAndRewrite(Op op, PatternRewriter &rewriter,
385c0891706SEmilio Cota                                              bool base2) const {
38662fea88bSJacques Pienaar   if (!getElementTypeOrSelf(op.getOperand()).isF32())
387ce976d2dSEugene Zhulenev     return rewriter.notifyMatchFailure(op, "unsupported operand type");
388ce976d2dSEugene Zhulenev 
38962fea88bSJacques Pienaar   ArrayRef<int64_t> shape = vectorShape(op.getOperand());
390ec32d540SEugene Zhulenev 
391ce976d2dSEugene Zhulenev   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
392ce976d2dSEugene Zhulenev   auto bcast = [&](Value value) -> Value {
393ec32d540SEugene Zhulenev     return broadcast(builder, value, shape);
394ce976d2dSEugene Zhulenev   };
395ce976d2dSEugene Zhulenev 
396ce976d2dSEugene Zhulenev   Value cstZero = bcast(f32Cst(builder, 0.0f));
397ce976d2dSEugene Zhulenev   Value cstOne = bcast(f32Cst(builder, 1.0f));
398ce976d2dSEugene Zhulenev   Value cstNegHalf = bcast(f32Cst(builder, -0.5f));
399ce976d2dSEugene Zhulenev 
400ce976d2dSEugene Zhulenev   // The smallest non denormalized float number.
401ce976d2dSEugene Zhulenev   Value cstMinNormPos = bcast(f32FromBits(builder, 0x00800000u));
402ce976d2dSEugene Zhulenev   Value cstMinusInf = bcast(f32FromBits(builder, 0xff800000u));
403ce976d2dSEugene Zhulenev   Value cstPosInf = bcast(f32FromBits(builder, 0x7f800000u));
404ce976d2dSEugene Zhulenev   Value cstNan = bcast(f32FromBits(builder, 0x7fc00000));
405ce976d2dSEugene Zhulenev 
406ce976d2dSEugene Zhulenev   // Polynomial coefficients.
407ce976d2dSEugene Zhulenev   Value cstCephesSQRTHF = bcast(f32Cst(builder, 0.707106781186547524f));
408ce976d2dSEugene Zhulenev   Value cstCephesLogP0 = bcast(f32Cst(builder, 7.0376836292E-2f));
409ce976d2dSEugene Zhulenev   Value cstCephesLogP1 = bcast(f32Cst(builder, -1.1514610310E-1f));
410ce976d2dSEugene Zhulenev   Value cstCephesLogP2 = bcast(f32Cst(builder, 1.1676998740E-1f));
411ce976d2dSEugene Zhulenev   Value cstCephesLogP3 = bcast(f32Cst(builder, -1.2420140846E-1f));
412ce976d2dSEugene Zhulenev   Value cstCephesLogP4 = bcast(f32Cst(builder, +1.4249322787E-1f));
413ce976d2dSEugene Zhulenev   Value cstCephesLogP5 = bcast(f32Cst(builder, -1.6668057665E-1f));
414ce976d2dSEugene Zhulenev   Value cstCephesLogP6 = bcast(f32Cst(builder, +2.0000714765E-1f));
415ce976d2dSEugene Zhulenev   Value cstCephesLogP7 = bcast(f32Cst(builder, -2.4999993993E-1f));
416ce976d2dSEugene Zhulenev   Value cstCephesLogP8 = bcast(f32Cst(builder, +3.3333331174E-1f));
417ce976d2dSEugene Zhulenev 
41862fea88bSJacques Pienaar   Value x = op.getOperand();
419ce976d2dSEugene Zhulenev 
420ce976d2dSEugene Zhulenev   // Truncate input values to the minimum positive normal.
421ce976d2dSEugene Zhulenev   x = max(builder, x, cstMinNormPos);
422ce976d2dSEugene Zhulenev 
423ce976d2dSEugene Zhulenev   // Extract significant in the range [0.5,1) and exponent.
424*ced8690dSMehdi Amini   std::pair<Value, Value> pair = frexp(builder, x, /*isPositive=*/true);
425ce976d2dSEugene Zhulenev   x = pair.first;
426ce976d2dSEugene Zhulenev   Value e = pair.second;
427ce976d2dSEugene Zhulenev 
428ce976d2dSEugene Zhulenev   // Shift the inputs from the range [0.5,1) to [sqrt(1/2), sqrt(2)) and shift
429ce976d2dSEugene Zhulenev   // by -1.0. The values are then centered around 0, which improves the
430ce976d2dSEugene Zhulenev   // stability of the polynomial evaluation:
431ce976d2dSEugene Zhulenev   //
432ce976d2dSEugene Zhulenev   //   if( x < SQRTHF ) {
433ce976d2dSEugene Zhulenev   //     e -= 1;
434ce976d2dSEugene Zhulenev   //     x = x + x - 1.0;
435ce976d2dSEugene Zhulenev   //   } else { x = x - 1.0; }
436a54f4eaeSMogball   Value mask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, x,
437a54f4eaeSMogball                                              cstCephesSQRTHF);
438ce976d2dSEugene Zhulenev   Value tmp = builder.create<SelectOp>(mask, x, cstZero);
439ce976d2dSEugene Zhulenev 
440a54f4eaeSMogball   x = builder.create<arith::SubFOp>(x, cstOne);
441a54f4eaeSMogball   e = builder.create<arith::SubFOp>(
442a54f4eaeSMogball       e, builder.create<SelectOp>(mask, cstOne, cstZero));
443a54f4eaeSMogball   x = builder.create<arith::AddFOp>(x, tmp);
444ce976d2dSEugene Zhulenev 
445a54f4eaeSMogball   Value x2 = builder.create<arith::MulFOp>(x, x);
446a54f4eaeSMogball   Value x3 = builder.create<arith::MulFOp>(x2, x);
447ce976d2dSEugene Zhulenev 
448ce976d2dSEugene Zhulenev   // Evaluate the polynomial approximant of degree 8 in three parts.
449ce976d2dSEugene Zhulenev   Value y0, y1, y2;
450a54f4eaeSMogball   y0 = builder.create<math::FmaOp>(cstCephesLogP0, x, cstCephesLogP1);
451a54f4eaeSMogball   y1 = builder.create<math::FmaOp>(cstCephesLogP3, x, cstCephesLogP4);
452a54f4eaeSMogball   y2 = builder.create<math::FmaOp>(cstCephesLogP6, x, cstCephesLogP7);
453a54f4eaeSMogball   y0 = builder.create<math::FmaOp>(y0, x, cstCephesLogP2);
454a54f4eaeSMogball   y1 = builder.create<math::FmaOp>(y1, x, cstCephesLogP5);
455a54f4eaeSMogball   y2 = builder.create<math::FmaOp>(y2, x, cstCephesLogP8);
456a54f4eaeSMogball   y0 = builder.create<math::FmaOp>(y0, x3, y1);
457a54f4eaeSMogball   y0 = builder.create<math::FmaOp>(y0, x3, y2);
458a54f4eaeSMogball   y0 = builder.create<arith::MulFOp>(y0, x3);
459ce976d2dSEugene Zhulenev 
460a54f4eaeSMogball   y0 = builder.create<math::FmaOp>(cstNegHalf, x2, y0);
461a54f4eaeSMogball   x = builder.create<arith::AddFOp>(x, y0);
462ce976d2dSEugene Zhulenev 
463c0891706SEmilio Cota   if (base2) {
464c0891706SEmilio Cota     Value cstLog2e = bcast(f32Cst(builder, static_cast<float>(LOG2E_VALUE)));
465a54f4eaeSMogball     x = builder.create<math::FmaOp>(x, cstLog2e, e);
466c0891706SEmilio Cota   } else {
467ce976d2dSEugene Zhulenev     Value cstLn2 = bcast(f32Cst(builder, static_cast<float>(LN2_VALUE)));
468a54f4eaeSMogball     x = builder.create<math::FmaOp>(e, cstLn2, x);
469c0891706SEmilio Cota   }
470ce976d2dSEugene Zhulenev 
471a54f4eaeSMogball   Value invalidMask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::ULT,
47262fea88bSJacques Pienaar                                                     op.getOperand(), cstZero);
473a54f4eaeSMogball   Value zeroMask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ,
47462fea88bSJacques Pienaar                                                  op.getOperand(), cstZero);
475a54f4eaeSMogball   Value posInfMask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ,
47662fea88bSJacques Pienaar                                                    op.getOperand(), cstPosInf);
477ce976d2dSEugene Zhulenev 
478ce976d2dSEugene Zhulenev   // Filter out invalid values:
479ce976d2dSEugene Zhulenev   //  • x == 0     -> -INF
480ce976d2dSEugene Zhulenev   //  • x < 0      ->  NAN
481ce976d2dSEugene Zhulenev   //  • x == +INF  -> +INF
482ce976d2dSEugene Zhulenev   Value aproximation = builder.create<SelectOp>(
483ce976d2dSEugene Zhulenev       zeroMask, cstMinusInf,
484ce976d2dSEugene Zhulenev       builder.create<SelectOp>(
485ce976d2dSEugene Zhulenev           invalidMask, cstNan,
486ce976d2dSEugene Zhulenev           builder.create<SelectOp>(posInfMask, cstPosInf, x)));
487ce976d2dSEugene Zhulenev 
488ce976d2dSEugene Zhulenev   rewriter.replaceOp(op, aproximation);
489ce976d2dSEugene Zhulenev 
490ce976d2dSEugene Zhulenev   return success();
491ce976d2dSEugene Zhulenev }
492ce976d2dSEugene Zhulenev 
493c0891706SEmilio Cota namespace {
494c0891706SEmilio Cota struct LogApproximation : public LogApproximationBase<math::LogOp> {
495c0891706SEmilio Cota   using LogApproximationBase::LogApproximationBase;
496c0891706SEmilio Cota 
497c0891706SEmilio Cota   LogicalResult matchAndRewrite(math::LogOp op,
498c0891706SEmilio Cota                                 PatternRewriter &rewriter) const final {
499c0891706SEmilio Cota     return logMatchAndRewrite(op, rewriter, /*base2=*/false);
500c0891706SEmilio Cota   }
501c0891706SEmilio Cota };
502c0891706SEmilio Cota } // namespace
503c0891706SEmilio Cota 
504c0891706SEmilio Cota namespace {
505c0891706SEmilio Cota struct Log2Approximation : public LogApproximationBase<math::Log2Op> {
506c0891706SEmilio Cota   using LogApproximationBase::LogApproximationBase;
507c0891706SEmilio Cota 
508c0891706SEmilio Cota   LogicalResult matchAndRewrite(math::Log2Op op,
509c0891706SEmilio Cota                                 PatternRewriter &rewriter) const final {
510c0891706SEmilio Cota     return logMatchAndRewrite(op, rewriter, /*base2=*/true);
511c0891706SEmilio Cota   }
512c0891706SEmilio Cota };
513c0891706SEmilio Cota } // namespace
514c0891706SEmilio Cota 
515ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------//
5161c0374e7SEmilio Cota // Log1p approximation.
5171c0374e7SEmilio Cota //----------------------------------------------------------------------------//
5181c0374e7SEmilio Cota 
5191c0374e7SEmilio Cota namespace {
5201c0374e7SEmilio Cota struct Log1pApproximation : public OpRewritePattern<math::Log1pOp> {
5211c0374e7SEmilio Cota public:
5221c0374e7SEmilio Cota   using OpRewritePattern::OpRewritePattern;
5231c0374e7SEmilio Cota 
5241c0374e7SEmilio Cota   LogicalResult matchAndRewrite(math::Log1pOp op,
5251c0374e7SEmilio Cota                                 PatternRewriter &rewriter) const final;
5261c0374e7SEmilio Cota };
5271c0374e7SEmilio Cota } // namespace
5281c0374e7SEmilio Cota 
5291c0374e7SEmilio Cota // Approximate log(1+x).
5301c0374e7SEmilio Cota LogicalResult
5311c0374e7SEmilio Cota Log1pApproximation::matchAndRewrite(math::Log1pOp op,
5321c0374e7SEmilio Cota                                     PatternRewriter &rewriter) const {
53362fea88bSJacques Pienaar   if (!getElementTypeOrSelf(op.getOperand()).isF32())
5341c0374e7SEmilio Cota     return rewriter.notifyMatchFailure(op, "unsupported operand type");
5351c0374e7SEmilio Cota 
53662fea88bSJacques Pienaar   ArrayRef<int64_t> shape = vectorShape(op.getOperand());
537ec32d540SEugene Zhulenev 
5381c0374e7SEmilio Cota   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
5391c0374e7SEmilio Cota   auto bcast = [&](Value value) -> Value {
540ec32d540SEugene Zhulenev     return broadcast(builder, value, shape);
5411c0374e7SEmilio Cota   };
5421c0374e7SEmilio Cota 
5431c0374e7SEmilio Cota   // Approximate log(1+x) using the following, due to W. Kahan:
5441c0374e7SEmilio Cota   //   u = x + 1.0;
5451c0374e7SEmilio Cota   //   if (u == 1.0 || u == inf) return x;
5461c0374e7SEmilio Cota   //   return x * log(u) / (u - 1.0);
5471c0374e7SEmilio Cota   //          ^^^^^^^^^^^^^^^^^^^^^^
5481c0374e7SEmilio Cota   //             "logLarge" below.
5491c0374e7SEmilio Cota   Value cstOne = bcast(f32Cst(builder, 1.0f));
55062fea88bSJacques Pienaar   Value x = op.getOperand();
551a54f4eaeSMogball   Value u = builder.create<arith::AddFOp>(x, cstOne);
552a54f4eaeSMogball   Value uSmall =
553a54f4eaeSMogball       builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, u, cstOne);
5541c0374e7SEmilio Cota   Value logU = builder.create<math::LogOp>(u);
555a54f4eaeSMogball   Value uInf =
556a54f4eaeSMogball       builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, u, logU);
557a54f4eaeSMogball   Value logLarge = builder.create<arith::MulFOp>(
558a54f4eaeSMogball       x, builder.create<arith::DivFOp>(
559a54f4eaeSMogball              logU, builder.create<arith::SubFOp>(u, cstOne)));
560a54f4eaeSMogball   Value approximation = builder.create<SelectOp>(
561a54f4eaeSMogball       builder.create<arith::OrIOp>(uSmall, uInf), x, logLarge);
5621c0374e7SEmilio Cota   rewriter.replaceOp(op, approximation);
5631c0374e7SEmilio Cota   return success();
5641c0374e7SEmilio Cota }
5651c0374e7SEmilio Cota 
5661c0374e7SEmilio Cota //----------------------------------------------------------------------------//
567f1b92218SBoian Petkantchin // Erf approximation.
568f1b92218SBoian Petkantchin //----------------------------------------------------------------------------//
569f1b92218SBoian Petkantchin 
570f1b92218SBoian Petkantchin // Approximates erf(x) with
571f1b92218SBoian Petkantchin // a - P(x)/Q(x)
572f1b92218SBoian Petkantchin // where P and Q are polynomials of degree 4.
573f1b92218SBoian Petkantchin // Different coefficients are chosen based on the value of x.
574f1b92218SBoian Petkantchin // The approximation error is ~2.5e-07.
575f1b92218SBoian Petkantchin // Boost's minimax tool that utilizes the Remez method was used to find the
576f1b92218SBoian Petkantchin // coefficients.
577f1b92218SBoian Petkantchin LogicalResult
578f1b92218SBoian Petkantchin ErfPolynomialApproximation::matchAndRewrite(math::ErfOp op,
579f1b92218SBoian Petkantchin                                             PatternRewriter &rewriter) const {
58062fea88bSJacques Pienaar   if (!getElementTypeOrSelf(op.getOperand()).isF32())
581f1b92218SBoian Petkantchin     return rewriter.notifyMatchFailure(op, "unsupported operand type");
582f1b92218SBoian Petkantchin 
58362fea88bSJacques Pienaar   ArrayRef<int64_t> shape = vectorShape(op.getOperand());
584ec32d540SEugene Zhulenev 
585f1b92218SBoian Petkantchin   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
586f1b92218SBoian Petkantchin   auto bcast = [&](Value value) -> Value {
587ec32d540SEugene Zhulenev     return broadcast(builder, value, shape);
588f1b92218SBoian Petkantchin   };
589f1b92218SBoian Petkantchin 
590f1b92218SBoian Petkantchin   const int intervalsCount = 3;
591f1b92218SBoian Petkantchin   const int polyDegree = 4;
592f1b92218SBoian Petkantchin 
593f1b92218SBoian Petkantchin   Value zero = bcast(f32Cst(builder, 0));
594f1b92218SBoian Petkantchin   Value one = bcast(f32Cst(builder, 1));
595f1b92218SBoian Petkantchin   Value pp[intervalsCount][polyDegree + 1];
5967d79a257SAlexander Belyaev   pp[0][0] = bcast(f32Cst(builder, +0.00000000000000000e+00f));
5977d79a257SAlexander Belyaev   pp[0][1] = bcast(f32Cst(builder, +1.12837916222975858e+00f));
5987d79a257SAlexander Belyaev   pp[0][2] = bcast(f32Cst(builder, -5.23018562988006470e-01f));
5997d79a257SAlexander Belyaev   pp[0][3] = bcast(f32Cst(builder, +2.09741709609267072e-01f));
6007d79a257SAlexander Belyaev   pp[0][4] = bcast(f32Cst(builder, +2.58146801602987875e-02f));
6017d79a257SAlexander Belyaev   pp[1][0] = bcast(f32Cst(builder, +0.00000000000000000e+00f));
6027d79a257SAlexander Belyaev   pp[1][1] = bcast(f32Cst(builder, +1.12750687816789140e+00f));
6037d79a257SAlexander Belyaev   pp[1][2] = bcast(f32Cst(builder, -3.64721408487825775e-01f));
6047d79a257SAlexander Belyaev   pp[1][3] = bcast(f32Cst(builder, +1.18407396425136952e-01f));
6057d79a257SAlexander Belyaev   pp[1][4] = bcast(f32Cst(builder, +3.70645533056476558e-02f));
6067d79a257SAlexander Belyaev   pp[2][0] = bcast(f32Cst(builder, -3.30093071049483172e-03f));
6077d79a257SAlexander Belyaev   pp[2][1] = bcast(f32Cst(builder, +3.51961938357697011e-03f));
6087d79a257SAlexander Belyaev   pp[2][2] = bcast(f32Cst(builder, -1.41373622814988039e-03f));
6097d79a257SAlexander Belyaev   pp[2][3] = bcast(f32Cst(builder, +2.53447094961941348e-04f));
6107d79a257SAlexander Belyaev   pp[2][4] = bcast(f32Cst(builder, -1.71048029455037401e-05f));
611f1b92218SBoian Petkantchin 
612f1b92218SBoian Petkantchin   Value qq[intervalsCount][polyDegree + 1];
6137d79a257SAlexander Belyaev   qq[0][0] = bcast(f32Cst(builder, +1.000000000000000000e+00f));
6147d79a257SAlexander Belyaev   qq[0][1] = bcast(f32Cst(builder, -4.635138185962547255e-01f));
6157d79a257SAlexander Belyaev   qq[0][2] = bcast(f32Cst(builder, +5.192301327279782447e-01f));
6167d79a257SAlexander Belyaev   qq[0][3] = bcast(f32Cst(builder, -1.318089722204810087e-01f));
6177d79a257SAlexander Belyaev   qq[0][4] = bcast(f32Cst(builder, +7.397964654672315005e-02f));
6187d79a257SAlexander Belyaev   qq[1][0] = bcast(f32Cst(builder, +1.00000000000000000e+00f));
6197d79a257SAlexander Belyaev   qq[1][1] = bcast(f32Cst(builder, -3.27607011824493086e-01f));
6207d79a257SAlexander Belyaev   qq[1][2] = bcast(f32Cst(builder, +4.48369090658821977e-01f));
6217d79a257SAlexander Belyaev   qq[1][3] = bcast(f32Cst(builder, -8.83462621207857930e-02f));
6227d79a257SAlexander Belyaev   qq[1][4] = bcast(f32Cst(builder, +5.72442770283176093e-02f));
6237d79a257SAlexander Belyaev   qq[2][0] = bcast(f32Cst(builder, +1.00000000000000000e+00f));
6247d79a257SAlexander Belyaev   qq[2][1] = bcast(f32Cst(builder, -2.06069165953913769e+00f));
6257d79a257SAlexander Belyaev   qq[2][2] = bcast(f32Cst(builder, +1.62705939945477759e+00f));
6267d79a257SAlexander Belyaev   qq[2][3] = bcast(f32Cst(builder, -5.83389859211130017e-01f));
6277d79a257SAlexander Belyaev   qq[2][4] = bcast(f32Cst(builder, +8.21908939856640930e-02f));
628f1b92218SBoian Petkantchin 
629f1b92218SBoian Petkantchin   Value offsets[intervalsCount];
6307d79a257SAlexander Belyaev   offsets[0] = bcast(f32Cst(builder, 0.0f));
6317d79a257SAlexander Belyaev   offsets[1] = bcast(f32Cst(builder, 0.0f));
6327d79a257SAlexander Belyaev   offsets[2] = bcast(f32Cst(builder, 1.0f));
633f1b92218SBoian Petkantchin 
634f1b92218SBoian Petkantchin   Value bounds[intervalsCount];
6357d79a257SAlexander Belyaev   bounds[0] = bcast(f32Cst(builder, 0.8f));
6367d79a257SAlexander Belyaev   bounds[1] = bcast(f32Cst(builder, 2.0f));
6377d79a257SAlexander Belyaev   bounds[2] = bcast(f32Cst(builder, 3.75f));
638f1b92218SBoian Petkantchin 
639f1b92218SBoian Petkantchin   Value isNegativeArg = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT,
64062fea88bSJacques Pienaar                                                       op.getOperand(), zero);
64162fea88bSJacques Pienaar   Value negArg = builder.create<arith::NegFOp>(op.getOperand());
64262fea88bSJacques Pienaar   Value x = builder.create<SelectOp>(isNegativeArg, negArg, op.getOperand());
643f1b92218SBoian Petkantchin 
644f1b92218SBoian Petkantchin   Value offset = offsets[0];
645f1b92218SBoian Petkantchin   Value p[polyDegree + 1];
646f1b92218SBoian Petkantchin   Value q[polyDegree + 1];
647f1b92218SBoian Petkantchin   for (int i = 0; i <= polyDegree; ++i) {
648f1b92218SBoian Petkantchin     p[i] = pp[0][i];
649f1b92218SBoian Petkantchin     q[i] = qq[0][i];
650f1b92218SBoian Petkantchin   }
651f1b92218SBoian Petkantchin 
652f1b92218SBoian Petkantchin   // TODO: maybe use vector stacking to reduce the number of selects.
653f1b92218SBoian Petkantchin   Value isLessThanBound[intervalsCount];
654f1b92218SBoian Petkantchin   for (int j = 0; j < intervalsCount - 1; ++j) {
655f1b92218SBoian Petkantchin     isLessThanBound[j] =
656f1b92218SBoian Petkantchin         builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, x, bounds[j]);
657f1b92218SBoian Petkantchin     for (int i = 0; i <= polyDegree; ++i) {
658f1b92218SBoian Petkantchin       p[i] = builder.create<SelectOp>(isLessThanBound[j], p[i], pp[j + 1][i]);
659f1b92218SBoian Petkantchin       q[i] = builder.create<SelectOp>(isLessThanBound[j], q[i], qq[j + 1][i]);
660f1b92218SBoian Petkantchin     }
661f1b92218SBoian Petkantchin     offset =
662f1b92218SBoian Petkantchin         builder.create<SelectOp>(isLessThanBound[j], offset, offsets[j + 1]);
663f1b92218SBoian Petkantchin   }
664f1b92218SBoian Petkantchin   isLessThanBound[intervalsCount - 1] = builder.create<arith::CmpFOp>(
665f1b92218SBoian Petkantchin       arith::CmpFPredicate::ULT, x, bounds[intervalsCount - 1]);
666f1b92218SBoian Petkantchin 
667f1b92218SBoian Petkantchin   Value pPoly = makePolynomialCalculation(builder, p, x);
668f1b92218SBoian Petkantchin   Value qPoly = makePolynomialCalculation(builder, q, x);
669f1b92218SBoian Petkantchin   Value rationalPoly = builder.create<arith::DivFOp>(pPoly, qPoly);
670f1b92218SBoian Petkantchin   Value formula = builder.create<arith::AddFOp>(offset, rationalPoly);
671f1b92218SBoian Petkantchin   formula = builder.create<SelectOp>(isLessThanBound[intervalsCount - 1],
672f1b92218SBoian Petkantchin                                      formula, one);
673f1b92218SBoian Petkantchin 
674f1b92218SBoian Petkantchin   // erf is odd function: erf(x) = -erf(-x).
675f1b92218SBoian Petkantchin   Value negFormula = builder.create<arith::NegFOp>(formula);
676f1b92218SBoian Petkantchin   Value res = builder.create<SelectOp>(isNegativeArg, negFormula, formula);
677f1b92218SBoian Petkantchin 
678f1b92218SBoian Petkantchin   rewriter.replaceOp(op, res);
679f1b92218SBoian Petkantchin 
680f1b92218SBoian Petkantchin   return success();
681f1b92218SBoian Petkantchin }
682f1b92218SBoian Petkantchin 
683f1b92218SBoian Petkantchin //----------------------------------------------------------------------------//
684ea7f211bSAhmed Taei // Exp approximation.
685ea7f211bSAhmed Taei //----------------------------------------------------------------------------//
686ea7f211bSAhmed Taei 
687ea7f211bSAhmed Taei namespace {
688ea7f211bSAhmed Taei 
689ea7f211bSAhmed Taei struct ExpApproximation : public OpRewritePattern<math::ExpOp> {
690ea7f211bSAhmed Taei public:
691ea7f211bSAhmed Taei   using OpRewritePattern::OpRewritePattern;
692ea7f211bSAhmed Taei 
693ea7f211bSAhmed Taei   LogicalResult matchAndRewrite(math::ExpOp op,
694ea7f211bSAhmed Taei                                 PatternRewriter &rewriter) const final;
695ea7f211bSAhmed Taei };
696ea7f211bSAhmed Taei } // namespace
697ea7f211bSAhmed Taei 
698ea7f211bSAhmed Taei // Approximate exp(x) using its reduced range exp(y) where y is in the range
699ea7f211bSAhmed Taei // [0, ln(2)], let y = x - floor(x / ln(2)) * ln(2) = x - k * ln(2), exp(x)
700ea7f211bSAhmed Taei // = exp(y) * 2^k. exp(y).
701ea7f211bSAhmed Taei LogicalResult
702ea7f211bSAhmed Taei ExpApproximation::matchAndRewrite(math::ExpOp op,
703ea7f211bSAhmed Taei                                   PatternRewriter &rewriter) const {
70462fea88bSJacques Pienaar   if (!getElementTypeOrSelf(op.getOperand()).isF32())
705ea7f211bSAhmed Taei     return rewriter.notifyMatchFailure(op, "unsupported operand type");
706ec32d540SEugene Zhulenev 
70762fea88bSJacques Pienaar   ArrayRef<int64_t> shape = vectorShape(op.getOperand());
708ec32d540SEugene Zhulenev 
709ea7f211bSAhmed Taei   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
710ea7f211bSAhmed Taei 
711ea7f211bSAhmed Taei   // TODO: Consider a common pattern rewriter with all methods below to
712ea7f211bSAhmed Taei   // write the approximations.
713ea7f211bSAhmed Taei   auto bcast = [&](Value value) -> Value {
714ec32d540SEugene Zhulenev     return broadcast(builder, value, shape);
715ea7f211bSAhmed Taei   };
716ea7f211bSAhmed Taei   auto fmla = [&](Value a, Value b, Value c) {
717a54f4eaeSMogball     return builder.create<math::FmaOp>(a, b, c);
718ea7f211bSAhmed Taei   };
719ea7f211bSAhmed Taei   auto mul = [&](Value a, Value b) -> Value {
720a54f4eaeSMogball     return builder.create<arith::MulFOp>(a, b);
721ea7f211bSAhmed Taei   };
722ea7f211bSAhmed Taei   auto sub = [&](Value a, Value b) -> Value {
723a54f4eaeSMogball     return builder.create<arith::SubFOp>(a, b);
724ea7f211bSAhmed Taei   };
725a54f4eaeSMogball   auto floor = [&](Value a) { return builder.create<math::FloorOp>(a); };
726ea7f211bSAhmed Taei 
727ea7f211bSAhmed Taei   Value cstLn2 = bcast(f32Cst(builder, static_cast<float>(LN2_VALUE)));
728c0891706SEmilio Cota   Value cstLog2E = bcast(f32Cst(builder, static_cast<float>(LOG2E_VALUE)));
729ea7f211bSAhmed Taei 
730ea7f211bSAhmed Taei   // Polynomial coefficients.
731ea7f211bSAhmed Taei   Value cstCephesExpP0 = bcast(f32Cst(builder, 1.0));
732ea7f211bSAhmed Taei   Value cstCephesExpP1 = bcast(f32Cst(builder, 1.0));
733ea7f211bSAhmed Taei   Value cstCephesExpP2 = bcast(f32Cst(builder, 0.49970514590562437052f));
734ea7f211bSAhmed Taei   Value cstCephesExpP3 = bcast(f32Cst(builder, 0.16873890085469545053f));
735ea7f211bSAhmed Taei   Value cstCephesExpP4 = bcast(f32Cst(builder, 0.03668965196652099192f));
736ea7f211bSAhmed Taei   Value cstCephesExpP5 = bcast(f32Cst(builder, 0.01314350012789660196f));
737ea7f211bSAhmed Taei 
73862fea88bSJacques Pienaar   Value x = op.getOperand();
739ea7f211bSAhmed Taei 
740ea7f211bSAhmed Taei   // Reduced y = x - floor(x / ln(2)) * ln(2) = x - k * ln(2)
741c0891706SEmilio Cota   Value xL2Inv = mul(x, cstLog2E);
742ea7f211bSAhmed Taei   Value kF32 = floor(xL2Inv);
743ea7f211bSAhmed Taei   Value kLn2 = mul(kF32, cstLn2);
744ea7f211bSAhmed Taei   Value y = sub(x, kLn2);
745ea7f211bSAhmed Taei 
746ea7f211bSAhmed Taei   // Use Estrin's evaluation scheme with 3 independent parts:
747ea7f211bSAhmed Taei   // P(y)^y : (c0 + c1 y) + (c2 + c3 y) y^2 + (c4 + c5 y) y^4
748ea7f211bSAhmed Taei   Value y2 = mul(y, y);
749ea7f211bSAhmed Taei   Value y4 = mul(y2, y2);
750ea7f211bSAhmed Taei 
751ea7f211bSAhmed Taei   Value q0 = fmla(cstCephesExpP1, y, cstCephesExpP0);
752ea7f211bSAhmed Taei   Value q1 = fmla(cstCephesExpP3, y, cstCephesExpP2);
753ea7f211bSAhmed Taei   Value q2 = fmla(cstCephesExpP5, y, cstCephesExpP4);
754ea7f211bSAhmed Taei   Value expY = fmla(q1, y2, q0);
755ea7f211bSAhmed Taei   expY = fmla(q2, y4, expY);
756ea7f211bSAhmed Taei 
757ec32d540SEugene Zhulenev   auto i32Vec = broadcast(builder.getI32Type(), shape);
758ea7f211bSAhmed Taei 
759ea7f211bSAhmed Taei   // exp2(k)
760a54f4eaeSMogball   Value k = builder.create<arith::FPToSIOp>(kF32, i32Vec);
761ea7f211bSAhmed Taei   Value exp2KValue = exp2I32(builder, k);
762ea7f211bSAhmed Taei 
763ea7f211bSAhmed Taei   // exp(x) = exp(y) * exp2(k)
764ea7f211bSAhmed Taei   expY = mul(expY, exp2KValue);
765ea7f211bSAhmed Taei 
766ea7f211bSAhmed Taei   // Handle overflow, inf and underflow of exp(x). exp(x) range is [0, inf], its
767ea7f211bSAhmed Taei   // partitioned as the following:
768ea7f211bSAhmed Taei   // exp(x) = 0, x <= -inf
769ea7f211bSAhmed Taei   // exp(x) = underflow (min_float), x <= -88
770ea7f211bSAhmed Taei   // exp(x) = inf (min_float), x >= 88
771ea7f211bSAhmed Taei   // Note: |k| = 127 is the value where the 8-bits exponent saturates.
772ea7f211bSAhmed Taei   Value zerof32Const = bcast(f32Cst(builder, 0));
773ea7f211bSAhmed Taei   auto constPosInfinity =
774ea7f211bSAhmed Taei       bcast(f32Cst(builder, std::numeric_limits<float>::infinity()));
775ea7f211bSAhmed Taei   auto constNegIfinity =
776ea7f211bSAhmed Taei       bcast(f32Cst(builder, -std::numeric_limits<float>::infinity()));
777ea7f211bSAhmed Taei   auto underflow = bcast(f32Cst(builder, std::numeric_limits<float>::min()));
778ea7f211bSAhmed Taei 
779ea7f211bSAhmed Taei   Value kMaxConst = bcast(i32Cst(builder, 127));
780ea7f211bSAhmed Taei   Value kMaxNegConst = bcast(i32Cst(builder, -127));
781a54f4eaeSMogball   Value rightBound =
782a54f4eaeSMogball       builder.create<arith::CmpIOp>(arith::CmpIPredicate::sle, k, kMaxConst);
783a54f4eaeSMogball   Value leftBound =
784a54f4eaeSMogball       builder.create<arith::CmpIOp>(arith::CmpIPredicate::sge, k, kMaxNegConst);
785ea7f211bSAhmed Taei 
786a54f4eaeSMogball   Value isNegInfinityX = builder.create<arith::CmpFOp>(
787a54f4eaeSMogball       arith::CmpFPredicate::OEQ, x, constNegIfinity);
78821f9e4a1SAhmed Taei   Value isPosInfinityX = builder.create<arith::CmpFOp>(
78921f9e4a1SAhmed Taei       arith::CmpFPredicate::OEQ, x, constPosInfinity);
790ea7f211bSAhmed Taei   Value isPostiveX =
791a54f4eaeSMogball       builder.create<arith::CmpFOp>(arith::CmpFPredicate::OGT, x, zerof32Const);
792a54f4eaeSMogball   Value isComputable = builder.create<arith::AndIOp>(rightBound, leftBound);
793ea7f211bSAhmed Taei 
794ea7f211bSAhmed Taei   expY = builder.create<SelectOp>(
79521f9e4a1SAhmed Taei       isNegInfinityX, zerof32Const,
796ea7f211bSAhmed Taei       builder.create<SelectOp>(
79721f9e4a1SAhmed Taei           isPosInfinityX, constPosInfinity,
79821f9e4a1SAhmed Taei           builder.create<SelectOp>(isComputable, expY,
79921f9e4a1SAhmed Taei                                    builder.create<SelectOp>(isPostiveX,
80021f9e4a1SAhmed Taei                                                             constPosInfinity,
80121f9e4a1SAhmed Taei                                                             underflow))));
802ea7f211bSAhmed Taei 
803ea7f211bSAhmed Taei   rewriter.replaceOp(op, expY);
804ea7f211bSAhmed Taei 
805ea7f211bSAhmed Taei   return success();
806ea7f211bSAhmed Taei }
807ea7f211bSAhmed Taei 
808ea7f211bSAhmed Taei //----------------------------------------------------------------------------//
8090edc4bc8SEmilio Cota // ExpM1 approximation.
8100edc4bc8SEmilio Cota //----------------------------------------------------------------------------//
8110edc4bc8SEmilio Cota 
8120edc4bc8SEmilio Cota namespace {
8130edc4bc8SEmilio Cota 
8140edc4bc8SEmilio Cota struct ExpM1Approximation : public OpRewritePattern<math::ExpM1Op> {
8150edc4bc8SEmilio Cota public:
8160edc4bc8SEmilio Cota   using OpRewritePattern::OpRewritePattern;
8170edc4bc8SEmilio Cota 
8180edc4bc8SEmilio Cota   LogicalResult matchAndRewrite(math::ExpM1Op op,
8190edc4bc8SEmilio Cota                                 PatternRewriter &rewriter) const final;
8200edc4bc8SEmilio Cota };
8210edc4bc8SEmilio Cota } // namespace
8220edc4bc8SEmilio Cota 
8230edc4bc8SEmilio Cota LogicalResult
8240edc4bc8SEmilio Cota ExpM1Approximation::matchAndRewrite(math::ExpM1Op op,
8250edc4bc8SEmilio Cota                                     PatternRewriter &rewriter) const {
82662fea88bSJacques Pienaar   if (!getElementTypeOrSelf(op.getOperand()).isF32())
8270edc4bc8SEmilio Cota     return rewriter.notifyMatchFailure(op, "unsupported operand type");
8280edc4bc8SEmilio Cota 
82962fea88bSJacques Pienaar   ArrayRef<int64_t> shape = vectorShape(op.getOperand());
830ec32d540SEugene Zhulenev 
8310edc4bc8SEmilio Cota   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
8320edc4bc8SEmilio Cota   auto bcast = [&](Value value) -> Value {
833ec32d540SEugene Zhulenev     return broadcast(builder, value, shape);
8340edc4bc8SEmilio Cota   };
8350edc4bc8SEmilio Cota 
8360edc4bc8SEmilio Cota   // expm1(x) = exp(x) - 1 = u - 1.
8370edc4bc8SEmilio Cota   // We have to handle it carefully when x is near 0, i.e. u ~= 1,
8380edc4bc8SEmilio Cota   // and when the input is ~= -inf, i.e. u - 1 ~= -1.
8390edc4bc8SEmilio Cota   Value cstOne = bcast(f32Cst(builder, 1.0f));
8400edc4bc8SEmilio Cota   Value cstNegOne = bcast(f32Cst(builder, -1.0f));
84162fea88bSJacques Pienaar   Value x = op.getOperand();
8420edc4bc8SEmilio Cota   Value u = builder.create<math::ExpOp>(x);
843a54f4eaeSMogball   Value uEqOne =
844a54f4eaeSMogball       builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, u, cstOne);
845a54f4eaeSMogball   Value uMinusOne = builder.create<arith::SubFOp>(u, cstOne);
846a54f4eaeSMogball   Value uMinusOneEqNegOne = builder.create<arith::CmpFOp>(
847a54f4eaeSMogball       arith::CmpFPredicate::OEQ, uMinusOne, cstNegOne);
8480edc4bc8SEmilio Cota   // logU = log(u) ~= x
8490edc4bc8SEmilio Cota   Value logU = builder.create<math::LogOp>(u);
8500edc4bc8SEmilio Cota 
8510edc4bc8SEmilio Cota   // Detect exp(x) = +inf; written this way to avoid having to form +inf.
852a54f4eaeSMogball   Value isInf =
853a54f4eaeSMogball       builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, logU, u);
8540edc4bc8SEmilio Cota 
8550edc4bc8SEmilio Cota   // (u - 1) * (x / ~x)
856a54f4eaeSMogball   Value expm1 = builder.create<arith::MulFOp>(
857a54f4eaeSMogball       uMinusOne, builder.create<arith::DivFOp>(x, logU));
8580edc4bc8SEmilio Cota   expm1 = builder.create<SelectOp>(isInf, u, expm1);
8590edc4bc8SEmilio Cota   Value approximation = builder.create<SelectOp>(
8600edc4bc8SEmilio Cota       uEqOne, x, builder.create<SelectOp>(uMinusOneEqNegOne, cstNegOne, expm1));
8610edc4bc8SEmilio Cota   rewriter.replaceOp(op, approximation);
8620edc4bc8SEmilio Cota   return success();
8630edc4bc8SEmilio Cota }
8640edc4bc8SEmilio Cota 
8650edc4bc8SEmilio Cota //----------------------------------------------------------------------------//
8667e2d672aSAhmed S. Taei // Sin and Cos approximation.
8677e2d672aSAhmed S. Taei //----------------------------------------------------------------------------//
8687e2d672aSAhmed S. Taei 
8697e2d672aSAhmed S. Taei namespace {
8707e2d672aSAhmed S. Taei 
8717e2d672aSAhmed S. Taei template <bool isSine, typename OpTy>
8727e2d672aSAhmed S. Taei struct SinAndCosApproximation : public OpRewritePattern<OpTy> {
8737e2d672aSAhmed S. Taei public:
8747e2d672aSAhmed S. Taei   using OpRewritePattern<OpTy>::OpRewritePattern;
8757e2d672aSAhmed S. Taei 
8767e2d672aSAhmed S. Taei   LogicalResult matchAndRewrite(OpTy op, PatternRewriter &rewriter) const final;
8777e2d672aSAhmed S. Taei };
8787e2d672aSAhmed S. Taei } // namespace
8797e2d672aSAhmed S. Taei 
8807e2d672aSAhmed S. Taei #define TWO_OVER_PI                                                            \
8817e2d672aSAhmed S. Taei   0.6366197723675813430755350534900574481378385829618257949906693762L
8827e2d672aSAhmed S. Taei #define PI_OVER_2                                                              \
8837e2d672aSAhmed S. Taei   1.5707963267948966192313216916397514420985846996875529104874722961L
8847e2d672aSAhmed S. Taei 
8857e2d672aSAhmed S. Taei // Approximates sin(x) or cos(x) by finding the best approximation polynomial in
8867e2d672aSAhmed S. Taei // the reduced range [0, pi/2] for both sin(x) and cos(x). Then given y in the
8877e2d672aSAhmed S. Taei // reduced range sin(x) will be computed as sin(y), -sin(y), cos(y) or -cos(y).
8887e2d672aSAhmed S. Taei template <bool isSine, typename OpTy>
8897e2d672aSAhmed S. Taei LogicalResult SinAndCosApproximation<isSine, OpTy>::matchAndRewrite(
8907e2d672aSAhmed S. Taei     OpTy op, PatternRewriter &rewriter) const {
8917e2d672aSAhmed S. Taei   static_assert(
8927e2d672aSAhmed S. Taei       llvm::is_one_of<OpTy, math::SinOp, math::CosOp>::value,
8937e2d672aSAhmed S. Taei       "SinAndCosApproximation pattern expects math::SinOp or math::CosOp");
894ec32d540SEugene Zhulenev 
89562fea88bSJacques Pienaar   if (!getElementTypeOrSelf(op.getOperand()).isF32())
8967e2d672aSAhmed S. Taei     return rewriter.notifyMatchFailure(op, "unsupported operand type");
8977e2d672aSAhmed S. Taei 
89862fea88bSJacques Pienaar   ArrayRef<int64_t> shape = vectorShape(op.getOperand());
899ec32d540SEugene Zhulenev 
9007e2d672aSAhmed S. Taei   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
9017e2d672aSAhmed S. Taei   auto bcast = [&](Value value) -> Value {
902ec32d540SEugene Zhulenev     return broadcast(builder, value, shape);
9037e2d672aSAhmed S. Taei   };
9047e2d672aSAhmed S. Taei   auto mul = [&](Value a, Value b) -> Value {
905a54f4eaeSMogball     return builder.create<arith::MulFOp>(a, b);
9067e2d672aSAhmed S. Taei   };
9077e2d672aSAhmed S. Taei   auto sub = [&](Value a, Value b) -> Value {
908a54f4eaeSMogball     return builder.create<arith::SubFOp>(a, b);
9097e2d672aSAhmed S. Taei   };
910a54f4eaeSMogball   auto floor = [&](Value a) { return builder.create<math::FloorOp>(a); };
9117e2d672aSAhmed S. Taei 
912ec32d540SEugene Zhulenev   auto i32Vec = broadcast(builder.getI32Type(), shape);
9137e2d672aSAhmed S. Taei   auto fPToSingedInteger = [&](Value a) -> Value {
914a54f4eaeSMogball     return builder.create<arith::FPToSIOp>(a, i32Vec);
9157e2d672aSAhmed S. Taei   };
9167e2d672aSAhmed S. Taei 
9177e2d672aSAhmed S. Taei   auto modulo4 = [&](Value a) -> Value {
918a54f4eaeSMogball     return builder.create<arith::AndIOp>(a, bcast(i32Cst(builder, 3)));
9197e2d672aSAhmed S. Taei   };
9207e2d672aSAhmed S. Taei 
9217e2d672aSAhmed S. Taei   auto isEqualTo = [&](Value a, Value b) -> Value {
922a54f4eaeSMogball     return builder.create<arith::CmpIOp>(arith::CmpIPredicate::eq, a, b);
9237e2d672aSAhmed S. Taei   };
9247e2d672aSAhmed S. Taei 
9257e2d672aSAhmed S. Taei   auto isGreaterThan = [&](Value a, Value b) -> Value {
926a54f4eaeSMogball     return builder.create<arith::CmpIOp>(arith::CmpIPredicate::sgt, a, b);
9277e2d672aSAhmed S. Taei   };
9287e2d672aSAhmed S. Taei 
9297e2d672aSAhmed S. Taei   auto select = [&](Value cond, Value t, Value f) -> Value {
9307e2d672aSAhmed S. Taei     return builder.create<SelectOp>(cond, t, f);
9317e2d672aSAhmed S. Taei   };
9327e2d672aSAhmed S. Taei 
9337e2d672aSAhmed S. Taei   auto fmla = [&](Value a, Value b, Value c) {
934a54f4eaeSMogball     return builder.create<math::FmaOp>(a, b, c);
9357e2d672aSAhmed S. Taei   };
9367e2d672aSAhmed S. Taei 
937a54f4eaeSMogball   auto bitwiseOr = [&](Value a, Value b) {
938a54f4eaeSMogball     return builder.create<arith::OrIOp>(a, b);
939a54f4eaeSMogball   };
9407e2d672aSAhmed S. Taei 
9417e2d672aSAhmed S. Taei   Value twoOverPi = bcast(f32Cst(builder, TWO_OVER_PI));
9427e2d672aSAhmed S. Taei   Value piOverTwo = bcast(f32Cst(builder, PI_OVER_2));
9437e2d672aSAhmed S. Taei 
94462fea88bSJacques Pienaar   Value x = op.getOperand();
9457e2d672aSAhmed S. Taei 
9467e2d672aSAhmed S. Taei   Value k = floor(mul(x, twoOverPi));
9477e2d672aSAhmed S. Taei 
9487e2d672aSAhmed S. Taei   Value y = sub(x, mul(k, piOverTwo));
9497e2d672aSAhmed S. Taei 
9507e2d672aSAhmed S. Taei   Value cstOne = bcast(f32Cst(builder, 1.0));
9517e2d672aSAhmed S. Taei   Value cstNegativeOne = bcast(f32Cst(builder, -1.0));
9527e2d672aSAhmed S. Taei 
9537e2d672aSAhmed S. Taei   Value cstSC2 = bcast(f32Cst(builder, -0.16666667163372039794921875f));
9547e2d672aSAhmed S. Taei   Value cstSC4 = bcast(f32Cst(builder, 8.333347737789154052734375e-3f));
9557e2d672aSAhmed S. Taei   Value cstSC6 = bcast(f32Cst(builder, -1.9842604524455964565277099609375e-4f));
9567e2d672aSAhmed S. Taei   Value cstSC8 =
9577e2d672aSAhmed S. Taei       bcast(f32Cst(builder, 2.760012648650445044040679931640625e-6f));
9587e2d672aSAhmed S. Taei   Value cstSC10 =
9597e2d672aSAhmed S. Taei       bcast(f32Cst(builder, -2.50293279435709337121807038784027099609375e-8f));
9607e2d672aSAhmed S. Taei 
9617e2d672aSAhmed S. Taei   Value cstCC2 = bcast(f32Cst(builder, -0.5f));
9627e2d672aSAhmed S. Taei   Value cstCC4 = bcast(f32Cst(builder, 4.166664183139801025390625e-2f));
9637e2d672aSAhmed S. Taei   Value cstCC6 = bcast(f32Cst(builder, -1.388833043165504932403564453125e-3f));
9647e2d672aSAhmed S. Taei   Value cstCC8 = bcast(f32Cst(builder, 2.47562347794882953166961669921875e-5f));
9657e2d672aSAhmed S. Taei   Value cstCC10 =
9667e2d672aSAhmed S. Taei       bcast(f32Cst(builder, -2.59630184018533327616751194000244140625e-7f));
9677e2d672aSAhmed S. Taei 
9687e2d672aSAhmed S. Taei   Value kMod4 = modulo4(fPToSingedInteger(k));
9697e2d672aSAhmed S. Taei 
9707e2d672aSAhmed S. Taei   Value kR0 = isEqualTo(kMod4, bcast(i32Cst(builder, 0)));
9717e2d672aSAhmed S. Taei   Value kR1 = isEqualTo(kMod4, bcast(i32Cst(builder, 1)));
9727e2d672aSAhmed S. Taei   Value kR2 = isEqualTo(kMod4, bcast(i32Cst(builder, 2)));
9737e2d672aSAhmed S. Taei   Value kR3 = isEqualTo(kMod4, bcast(i32Cst(builder, 3)));
9747e2d672aSAhmed S. Taei 
9757e2d672aSAhmed S. Taei   Value sinuseCos = isSine ? bitwiseOr(kR1, kR3) : bitwiseOr(kR0, kR2);
9767e2d672aSAhmed S. Taei   Value negativeRange = isSine ? isGreaterThan(kMod4, bcast(i32Cst(builder, 1)))
9777e2d672aSAhmed S. Taei                                : bitwiseOr(kR1, kR2);
9787e2d672aSAhmed S. Taei 
9797e2d672aSAhmed S. Taei   Value y2 = mul(y, y);
9807e2d672aSAhmed S. Taei 
9817e2d672aSAhmed S. Taei   Value base = select(sinuseCos, cstOne, y);
9827e2d672aSAhmed S. Taei   Value cstC2 = select(sinuseCos, cstCC2, cstSC2);
9837e2d672aSAhmed S. Taei   Value cstC4 = select(sinuseCos, cstCC4, cstSC4);
9847e2d672aSAhmed S. Taei   Value cstC6 = select(sinuseCos, cstCC6, cstSC6);
9857e2d672aSAhmed S. Taei   Value cstC8 = select(sinuseCos, cstCC8, cstSC8);
9867e2d672aSAhmed S. Taei   Value cstC10 = select(sinuseCos, cstCC10, cstSC10);
9877e2d672aSAhmed S. Taei 
9887e2d672aSAhmed S. Taei   Value v1 = fmla(y2, cstC10, cstC8);
9897e2d672aSAhmed S. Taei   Value v2 = fmla(y2, v1, cstC6);
9907e2d672aSAhmed S. Taei   Value v3 = fmla(y2, v2, cstC4);
9917e2d672aSAhmed S. Taei   Value v4 = fmla(y2, v3, cstC2);
9927e2d672aSAhmed S. Taei   Value v5 = fmla(y2, v4, cstOne);
9937e2d672aSAhmed S. Taei   Value v6 = mul(base, v5);
9947e2d672aSAhmed S. Taei 
9957e2d672aSAhmed S. Taei   Value approximation = select(negativeRange, mul(cstNegativeOne, v6), v6);
9967e2d672aSAhmed S. Taei 
9977e2d672aSAhmed S. Taei   rewriter.replaceOp(op, approximation);
9987e2d672aSAhmed S. Taei 
9997e2d672aSAhmed S. Taei   return success();
10007e2d672aSAhmed S. Taei }
10017e2d672aSAhmed S. Taei 
10027e2d672aSAhmed S. Taei //----------------------------------------------------------------------------//
100335553d45SEmilio Cota // Rsqrt approximation.
100435553d45SEmilio Cota //----------------------------------------------------------------------------//
100535553d45SEmilio Cota 
100635553d45SEmilio Cota namespace {
100735553d45SEmilio Cota struct RsqrtApproximation : public OpRewritePattern<math::RsqrtOp> {
100835553d45SEmilio Cota   using OpRewritePattern::OpRewritePattern;
100935553d45SEmilio Cota 
101035553d45SEmilio Cota   LogicalResult matchAndRewrite(math::RsqrtOp op,
101135553d45SEmilio Cota                                 PatternRewriter &rewriter) const final;
101235553d45SEmilio Cota };
101335553d45SEmilio Cota } // namespace
101435553d45SEmilio Cota 
101535553d45SEmilio Cota LogicalResult
101635553d45SEmilio Cota RsqrtApproximation::matchAndRewrite(math::RsqrtOp op,
101735553d45SEmilio Cota                                     PatternRewriter &rewriter) const {
101862fea88bSJacques Pienaar   if (!getElementTypeOrSelf(op.getOperand()).isF32())
1019ec32d540SEugene Zhulenev     return rewriter.notifyMatchFailure(op, "unsupported operand type");
1020ec32d540SEugene Zhulenev 
102162fea88bSJacques Pienaar   ArrayRef<int64_t> shape = vectorShape(op.getOperand());
1022ec32d540SEugene Zhulenev 
102335553d45SEmilio Cota   // Only support already-vectorized rsqrt's.
1024ec32d540SEugene Zhulenev   if (shape.empty() || shape.back() % 8 != 0)
102535553d45SEmilio Cota     return rewriter.notifyMatchFailure(op, "unsupported operand type");
102635553d45SEmilio Cota 
102735553d45SEmilio Cota   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
102835553d45SEmilio Cota   auto bcast = [&](Value value) -> Value {
1029ec32d540SEugene Zhulenev     return broadcast(builder, value, shape);
103035553d45SEmilio Cota   };
103135553d45SEmilio Cota 
103235553d45SEmilio Cota   Value cstPosInf = bcast(f32FromBits(builder, 0x7f800000u));
103335553d45SEmilio Cota   Value cstOnePointFive = bcast(f32Cst(builder, 1.5f));
103435553d45SEmilio Cota   Value cstNegHalf = bcast(f32Cst(builder, -0.5f));
103535553d45SEmilio Cota   Value cstMinNormPos = bcast(f32FromBits(builder, 0x00800000u));
103635553d45SEmilio Cota 
103762fea88bSJacques Pienaar   Value negHalf = builder.create<arith::MulFOp>(op.getOperand(), cstNegHalf);
103835553d45SEmilio Cota 
103935553d45SEmilio Cota   // Select only the inverse sqrt of positive normals (denormals are
104035553d45SEmilio Cota   // flushed to zero).
104162fea88bSJacques Pienaar   Value ltMinMask = builder.create<arith::CmpFOp>(
104262fea88bSJacques Pienaar       arith::CmpFPredicate::OLT, op.getOperand(), cstMinNormPos);
104335553d45SEmilio Cota   Value infMask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ,
104462fea88bSJacques Pienaar                                                 op.getOperand(), cstPosInf);
104535553d45SEmilio Cota   Value notNormalFiniteMask = builder.create<arith::OrIOp>(ltMinMask, infMask);
104635553d45SEmilio Cota 
104735553d45SEmilio Cota   // Compute an approximate result.
1048627fa0b9SEugene Zhulenev   Value yApprox = handleMultidimensionalVectors(
1049627fa0b9SEugene Zhulenev       builder, op->getOperands(), 8, [&builder](ValueRange operands) -> Value {
1050627fa0b9SEugene Zhulenev         return builder.create<x86vector::RsqrtOp>(operands);
1051627fa0b9SEugene Zhulenev       });
105235553d45SEmilio Cota 
105335553d45SEmilio Cota   // Do a single step of Newton-Raphson iteration to improve the approximation.
105435553d45SEmilio Cota   // This uses the formula y_{n+1} = y_n * (1.5 - y_n * (0.5 * x) * y_n).
105535553d45SEmilio Cota   // It is essential to evaluate the inner term like this because forming
105635553d45SEmilio Cota   // y_n^2 may over- or underflow.
105735553d45SEmilio Cota   Value inner = builder.create<arith::MulFOp>(negHalf, yApprox);
105835553d45SEmilio Cota   Value fma = builder.create<math::FmaOp>(yApprox, inner, cstOnePointFive);
105935553d45SEmilio Cota   Value yNewton = builder.create<arith::MulFOp>(yApprox, fma);
106035553d45SEmilio Cota 
106135553d45SEmilio Cota   // Select the result of the Newton-Raphson step for positive normal arguments.
106235553d45SEmilio Cota   // For other arguments, choose the output of the intrinsic. This will
106335553d45SEmilio Cota   // return rsqrt(+inf) = 0, rsqrt(x) = NaN if x < 0, and rsqrt(x) = +inf if
106435553d45SEmilio Cota   // x is zero or a positive denormalized float (equivalent to flushing positive
106535553d45SEmilio Cota   // denormalized inputs to zero).
106635553d45SEmilio Cota   Value res = builder.create<SelectOp>(notNormalFiniteMask, yApprox, yNewton);
106735553d45SEmilio Cota   rewriter.replaceOp(op, res);
106835553d45SEmilio Cota 
106935553d45SEmilio Cota   return success();
107035553d45SEmilio Cota }
107135553d45SEmilio Cota 
107235553d45SEmilio Cota //----------------------------------------------------------------------------//
1073f99ccf65SEugene Zhulenev 
1074f99ccf65SEugene Zhulenev void mlir::populateMathPolynomialApproximationPatterns(
107535553d45SEmilio Cota     RewritePatternSet &patterns,
107635553d45SEmilio Cota     const MathPolynomialApproximationOptions &options) {
1077dc4e913bSChris Lattner   patterns.add<TanhApproximation, LogApproximation, Log2Approximation,
1078f1b92218SBoian Petkantchin                Log1pApproximation, ErfPolynomialApproximation, ExpApproximation,
1079f1b92218SBoian Petkantchin                ExpM1Approximation, SinAndCosApproximation<true, math::SinOp>,
10807e2d672aSAhmed S. Taei                SinAndCosApproximation<false, math::CosOp>>(
10810edc4bc8SEmilio Cota       patterns.getContext());
108235553d45SEmilio Cota   if (options.enableAvx2)
108335553d45SEmilio Cota     patterns.add<RsqrtApproximation>(patterns.getContext());
1084f99ccf65SEugene Zhulenev }
1085