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" 2199ef9eebSMatthias Springer #include "mlir/Dialect/Utils/IndexingUtils.h" 2299ef9eebSMatthias Springer #include "mlir/Dialect/Vector/IR/VectorOps.h" 2399ef9eebSMatthias Springer #include "mlir/Dialect/Vector/Utils/VectorUtils.h" 2435553d45SEmilio Cota #include "mlir/Dialect/X86Vector/X86VectorDialect.h" 25f99ccf65SEugene Zhulenev #include "mlir/IR/Builders.h" 26*bbddd19eSJacques Pienaar #include "mlir/IR/BuiltinTypes.h" 27ce976d2dSEugene Zhulenev #include "mlir/IR/ImplicitLocOpBuilder.h" 28*bbddd19eSJacques Pienaar #include "mlir/IR/OpDefinition.h" 29*bbddd19eSJacques Pienaar #include "mlir/IR/PatternMatch.h" 30ec32d540SEugene Zhulenev #include "mlir/IR/TypeUtilities.h" 31f99ccf65SEugene Zhulenev #include "mlir/Transforms/DialectConversion.h" 32f99ccf65SEugene Zhulenev #include "mlir/Transforms/GreedyPatternRewriteDriver.h" 33f1b92218SBoian Petkantchin #include "llvm/ADT/ArrayRef.h" 34*bbddd19eSJacques Pienaar #include "llvm/ADT/STLExtras.h" 35f99ccf65SEugene Zhulenev 36f99ccf65SEugene Zhulenev using namespace mlir; 37f1b92218SBoian Petkantchin using namespace mlir::math; 38f99ccf65SEugene Zhulenev using namespace mlir::vector; 39f99ccf65SEugene Zhulenev 40ec32d540SEugene Zhulenev // Returns vector shape if the type is a vector. Returns an empty shape if it is 41ec32d540SEugene Zhulenev // not a vector. 42ec32d540SEugene Zhulenev static ArrayRef<int64_t> vectorShape(Type type) { 43ce976d2dSEugene Zhulenev auto vectorType = type.dyn_cast<VectorType>(); 44ec32d540SEugene Zhulenev return vectorType ? vectorType.getShape() : ArrayRef<int64_t>(); 45ce976d2dSEugene Zhulenev } 46ce976d2dSEugene Zhulenev 47ec32d540SEugene Zhulenev static ArrayRef<int64_t> vectorShape(Value value) { 48ec32d540SEugene Zhulenev return vectorShape(value.getType()); 4939b2cd40SEugene Zhulenev } 5039b2cd40SEugene Zhulenev 51f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------// 52ce976d2dSEugene Zhulenev // Broadcast scalar types and values into vector types and values. 53f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------// 54f99ccf65SEugene Zhulenev 5596cee297SAlexander Belyaev // Broadcasts scalar type into vector type (iff shape is non-scalar). 5696cee297SAlexander Belyaev static Type broadcast(Type type, ArrayRef<int64_t> shape) { 5796cee297SAlexander Belyaev assert(!type.isa<VectorType>() && "must be scalar type"); 58ec32d540SEugene Zhulenev return !shape.empty() ? VectorType::get(shape, type) : type; 5996cee297SAlexander Belyaev } 6096cee297SAlexander Belyaev 6196cee297SAlexander Belyaev // Broadcasts scalar value into vector (iff shape is non-scalar). 6296cee297SAlexander Belyaev static Value broadcast(ImplicitLocOpBuilder &builder, Value value, 6396cee297SAlexander Belyaev ArrayRef<int64_t> shape) { 64ce976d2dSEugene Zhulenev assert(!value.getType().isa<VectorType>() && "must be scalar value"); 6596cee297SAlexander Belyaev auto type = broadcast(value.getType(), shape); 66ec32d540SEugene Zhulenev return !shape.empty() ? builder.create<BroadcastOp>(type, value) : value; 67ce976d2dSEugene Zhulenev } 68f99ccf65SEugene Zhulenev 69ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------// 70627fa0b9SEugene Zhulenev // Helper function to handle n-D vectors with 1-D operations. 71627fa0b9SEugene Zhulenev //----------------------------------------------------------------------------// 72627fa0b9SEugene Zhulenev 73627fa0b9SEugene Zhulenev // Expands and unrolls n-D vector operands into multiple fixed size 1-D vectors 74627fa0b9SEugene Zhulenev // and calls the compute function with 1-D vector operands. Stitches back all 75627fa0b9SEugene Zhulenev // results into the original n-D vector result. 76627fa0b9SEugene Zhulenev // 77627fa0b9SEugene Zhulenev // Examples: vectorWidth = 8 78627fa0b9SEugene Zhulenev // - vector<4x8xf32> unrolled 4 times 79627fa0b9SEugene Zhulenev // - vector<16xf32> expanded to vector<2x8xf32> and unrolled 2 times 80627fa0b9SEugene Zhulenev // - vector<4x16xf32> expanded to vector<4x2x8xf32> and unrolled 4*2 times 81627fa0b9SEugene Zhulenev // 82627fa0b9SEugene Zhulenev // Some math approximations rely on ISA-specific operations that only accept 83627fa0b9SEugene Zhulenev // fixed size 1-D vectors (e.g. AVX expects vectors of width 8). 84627fa0b9SEugene Zhulenev // 85627fa0b9SEugene Zhulenev // It is the caller's responsibility to verify that the inner dimension is 86627fa0b9SEugene Zhulenev // divisible by the vectorWidth, and that all operands have the same vector 87627fa0b9SEugene Zhulenev // shape. 88627fa0b9SEugene Zhulenev static Value 89627fa0b9SEugene Zhulenev handleMultidimensionalVectors(ImplicitLocOpBuilder &builder, 90627fa0b9SEugene Zhulenev ValueRange operands, int64_t vectorWidth, 911fc096afSMehdi Amini llvm::function_ref<Value(ValueRange)> compute) { 92627fa0b9SEugene Zhulenev assert(!operands.empty() && "operands must be not empty"); 93627fa0b9SEugene Zhulenev assert(vectorWidth > 0 && "vector width must be larger than 0"); 94627fa0b9SEugene Zhulenev 95627fa0b9SEugene Zhulenev VectorType inputType = operands[0].getType().cast<VectorType>(); 96627fa0b9SEugene Zhulenev ArrayRef<int64_t> inputShape = inputType.getShape(); 97627fa0b9SEugene Zhulenev 98627fa0b9SEugene Zhulenev // If input shape matches target vector width, we can just call the 99627fa0b9SEugene Zhulenev // user-provided compute function with the operands. 100627fa0b9SEugene Zhulenev if (inputShape == llvm::makeArrayRef(vectorWidth)) 101627fa0b9SEugene Zhulenev return compute(operands); 102627fa0b9SEugene Zhulenev 103627fa0b9SEugene Zhulenev // Check if the inner dimension has to be expanded, or we can directly iterate 104627fa0b9SEugene Zhulenev // over the outer dimensions of the vector. 105627fa0b9SEugene Zhulenev int64_t innerDim = inputShape.back(); 106627fa0b9SEugene Zhulenev int64_t expansionDim = innerDim / vectorWidth; 107627fa0b9SEugene Zhulenev assert((innerDim % vectorWidth == 0) && "invalid inner dimension size"); 108627fa0b9SEugene Zhulenev 109627fa0b9SEugene Zhulenev // Maybe expand operands to the higher rank vector shape that we'll use to 110627fa0b9SEugene Zhulenev // iterate over and extract one dimensional vectors. 111627fa0b9SEugene Zhulenev SmallVector<int64_t> expandedShape(inputShape.begin(), inputShape.end()); 112627fa0b9SEugene Zhulenev SmallVector<Value> expandedOperands(operands); 113627fa0b9SEugene Zhulenev 114627fa0b9SEugene Zhulenev if (expansionDim > 1) { 115627fa0b9SEugene Zhulenev // Expand shape from [..., innerDim] to [..., expansionDim, vectorWidth]. 116627fa0b9SEugene Zhulenev expandedShape.insert(expandedShape.end() - 1, expansionDim); 117627fa0b9SEugene Zhulenev expandedShape.back() = vectorWidth; 118627fa0b9SEugene Zhulenev 119627fa0b9SEugene Zhulenev for (unsigned i = 0; i < operands.size(); ++i) { 120627fa0b9SEugene Zhulenev auto operand = operands[i]; 121627fa0b9SEugene Zhulenev auto eltType = operand.getType().cast<VectorType>().getElementType(); 122627fa0b9SEugene Zhulenev auto expandedType = VectorType::get(expandedShape, eltType); 123627fa0b9SEugene Zhulenev expandedOperands[i] = 124627fa0b9SEugene Zhulenev builder.create<vector::ShapeCastOp>(expandedType, operand); 125627fa0b9SEugene Zhulenev } 126627fa0b9SEugene Zhulenev } 127627fa0b9SEugene Zhulenev 128627fa0b9SEugene Zhulenev // Iterate over all outer dimensions of the compute shape vector type. 129627fa0b9SEugene Zhulenev auto iterationDims = ArrayRef<int64_t>(expandedShape).drop_back(); 130627fa0b9SEugene Zhulenev int64_t maxLinearIndex = computeMaxLinearIndex(iterationDims); 131627fa0b9SEugene Zhulenev 132627fa0b9SEugene Zhulenev SmallVector<int64_t> ones(iterationDims.size(), 1); 133627fa0b9SEugene Zhulenev auto strides = computeStrides(iterationDims, ones); 134627fa0b9SEugene Zhulenev 135627fa0b9SEugene Zhulenev // Compute results for each one dimensional vector. 136627fa0b9SEugene Zhulenev SmallVector<Value> results(maxLinearIndex); 137627fa0b9SEugene Zhulenev 138627fa0b9SEugene Zhulenev for (int64_t i = 0; i < maxLinearIndex; ++i) { 139627fa0b9SEugene Zhulenev auto offsets = delinearize(strides, i); 140627fa0b9SEugene Zhulenev 141627fa0b9SEugene Zhulenev SmallVector<Value> extracted(expandedOperands.size()); 14289de9cc8SMehdi Amini for (const auto &tuple : llvm::enumerate(expandedOperands)) 143627fa0b9SEugene Zhulenev extracted[tuple.index()] = 144627fa0b9SEugene Zhulenev builder.create<vector::ExtractOp>(tuple.value(), offsets); 145627fa0b9SEugene Zhulenev 146627fa0b9SEugene Zhulenev results[i] = compute(extracted); 147627fa0b9SEugene Zhulenev } 148627fa0b9SEugene Zhulenev 149627fa0b9SEugene Zhulenev // Stitch results together into one large vector. 150627fa0b9SEugene Zhulenev Type resultEltType = results[0].getType().cast<VectorType>().getElementType(); 151627fa0b9SEugene Zhulenev Type resultExpandedType = VectorType::get(expandedShape, resultEltType); 1528e123ca6SRiver Riddle Value result = builder.create<arith::ConstantOp>( 153627fa0b9SEugene Zhulenev resultExpandedType, builder.getZeroAttr(resultExpandedType)); 154627fa0b9SEugene Zhulenev 155627fa0b9SEugene Zhulenev for (int64_t i = 0; i < maxLinearIndex; ++i) 156627fa0b9SEugene Zhulenev result = builder.create<vector::InsertOp>(results[i], result, 157627fa0b9SEugene Zhulenev delinearize(strides, i)); 158627fa0b9SEugene Zhulenev 159627fa0b9SEugene Zhulenev // Reshape back to the original vector shape. 160627fa0b9SEugene Zhulenev return builder.create<vector::ShapeCastOp>( 161627fa0b9SEugene Zhulenev VectorType::get(inputShape, resultEltType), result); 162627fa0b9SEugene Zhulenev } 163627fa0b9SEugene Zhulenev 164627fa0b9SEugene Zhulenev //----------------------------------------------------------------------------// 165ce976d2dSEugene Zhulenev // Helper functions to create constants. 166ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------// 167f99ccf65SEugene Zhulenev 168ce976d2dSEugene Zhulenev static Value f32Cst(ImplicitLocOpBuilder &builder, float value) { 169a54f4eaeSMogball return builder.create<arith::ConstantOp>(builder.getF32FloatAttr(value)); 170ce976d2dSEugene Zhulenev } 171f99ccf65SEugene Zhulenev 172ce976d2dSEugene Zhulenev static Value i32Cst(ImplicitLocOpBuilder &builder, int32_t value) { 173a54f4eaeSMogball return builder.create<arith::ConstantOp>(builder.getI32IntegerAttr(value)); 174ce976d2dSEugene Zhulenev } 175f99ccf65SEugene Zhulenev 176ce976d2dSEugene Zhulenev static Value f32FromBits(ImplicitLocOpBuilder &builder, uint32_t bits) { 177ce976d2dSEugene Zhulenev Value i32Value = i32Cst(builder, static_cast<int32_t>(bits)); 178a54f4eaeSMogball return builder.create<arith::BitcastOp>(builder.getF32Type(), i32Value); 179ce976d2dSEugene Zhulenev } 180f99ccf65SEugene Zhulenev 181ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------// 182ce976d2dSEugene Zhulenev // Helper functions to build math functions approximations. 183ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------// 184ce976d2dSEugene Zhulenev 185ce976d2dSEugene Zhulenev static Value min(ImplicitLocOpBuilder &builder, Value a, Value b) { 186dec8af70SRiver Riddle return builder.create<arith::SelectOp>( 187a54f4eaeSMogball builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, a, b), a, b); 188ce976d2dSEugene Zhulenev } 189ce976d2dSEugene Zhulenev 190ce976d2dSEugene Zhulenev static Value max(ImplicitLocOpBuilder &builder, Value a, Value b) { 191dec8af70SRiver Riddle return builder.create<arith::SelectOp>( 192a54f4eaeSMogball builder.create<arith::CmpFOp>(arith::CmpFPredicate::OGT, a, b), a, b); 193ce976d2dSEugene Zhulenev } 194ce976d2dSEugene Zhulenev 195ce976d2dSEugene Zhulenev static Value clamp(ImplicitLocOpBuilder &builder, Value value, Value lowerBound, 196ce976d2dSEugene Zhulenev Value upperBound) { 197ce976d2dSEugene Zhulenev return max(builder, min(builder, value, upperBound), lowerBound); 198ce976d2dSEugene Zhulenev } 199ce976d2dSEugene Zhulenev 200ce976d2dSEugene Zhulenev // Decomposes given floating point value `arg` into a normalized fraction and 201ce976d2dSEugene Zhulenev // an integral power of two (see std::frexp). Returned values have float type. 202ce976d2dSEugene Zhulenev static std::pair<Value, Value> frexp(ImplicitLocOpBuilder &builder, Value arg, 20302b6fb21SMehdi Amini bool isPositive = false) { 204ec32d540SEugene Zhulenev assert(getElementTypeOrSelf(arg).isF32() && "arg must be f32 type"); 205ec32d540SEugene Zhulenev ArrayRef<int64_t> shape = vectorShape(arg); 206ce976d2dSEugene Zhulenev 207ce976d2dSEugene Zhulenev auto bcast = [&](Value value) -> Value { 20896cee297SAlexander Belyaev return broadcast(builder, value, shape); 209f99ccf65SEugene Zhulenev }; 210f99ccf65SEugene Zhulenev 211ce976d2dSEugene Zhulenev auto i32 = builder.getIntegerType(32); 21296cee297SAlexander Belyaev auto i32Vec = broadcast(i32, shape); 21396cee297SAlexander Belyaev auto f32Vec = broadcast(builder.getF32Type(), shape); 214f99ccf65SEugene Zhulenev 215ce976d2dSEugene Zhulenev Value cst126f = f32Cst(builder, 126.0f); 216ce976d2dSEugene Zhulenev Value cstHalf = f32Cst(builder, 0.5f); 217ce976d2dSEugene Zhulenev Value cstInvMantMask = f32FromBits(builder, ~0x7f800000u); 218f99ccf65SEugene Zhulenev 219ce976d2dSEugene Zhulenev // Bitcast to i32 for bitwise operations. 220a54f4eaeSMogball Value i32Half = builder.create<arith::BitcastOp>(i32, cstHalf); 221a54f4eaeSMogball Value i32InvMantMask = builder.create<arith::BitcastOp>(i32, cstInvMantMask); 222a54f4eaeSMogball Value i32Arg = builder.create<arith::BitcastOp>(i32Vec, arg); 223f99ccf65SEugene Zhulenev 224ce976d2dSEugene Zhulenev // Compute normalized fraction. 225a54f4eaeSMogball Value tmp0 = builder.create<arith::AndIOp>(i32Arg, bcast(i32InvMantMask)); 226a54f4eaeSMogball Value tmp1 = builder.create<arith::OrIOp>(tmp0, bcast(i32Half)); 227a54f4eaeSMogball Value normalizedFraction = builder.create<arith::BitcastOp>(f32Vec, tmp1); 228f99ccf65SEugene Zhulenev 229ce976d2dSEugene Zhulenev // Compute exponent. 23002b6fb21SMehdi Amini Value arg0 = isPositive ? arg : builder.create<math::AbsOp>(arg); 231a54f4eaeSMogball Value biasedExponentBits = builder.create<arith::ShRUIOp>( 232a54f4eaeSMogball builder.create<arith::BitcastOp>(i32Vec, arg0), 233a54f4eaeSMogball bcast(i32Cst(builder, 23))); 234a54f4eaeSMogball Value biasedExponent = 235a54f4eaeSMogball builder.create<arith::SIToFPOp>(f32Vec, biasedExponentBits); 236a54f4eaeSMogball Value exponent = 237a54f4eaeSMogball builder.create<arith::SubFOp>(biasedExponent, bcast(cst126f)); 238f99ccf65SEugene Zhulenev 239ce976d2dSEugene Zhulenev return {normalizedFraction, exponent}; 240f99ccf65SEugene Zhulenev } 241f99ccf65SEugene Zhulenev 242ea7f211bSAhmed Taei // Computes exp2 for an i32 argument. 243ea7f211bSAhmed Taei static Value exp2I32(ImplicitLocOpBuilder &builder, Value arg) { 244ec32d540SEugene Zhulenev assert(getElementTypeOrSelf(arg).isInteger(32) && "arg must be i32 type"); 245ec32d540SEugene Zhulenev ArrayRef<int64_t> shape = vectorShape(arg); 246ea7f211bSAhmed Taei 247ea7f211bSAhmed Taei auto bcast = [&](Value value) -> Value { 24896cee297SAlexander Belyaev return broadcast(builder, value, shape); 249ea7f211bSAhmed Taei }; 250ea7f211bSAhmed Taei 25196cee297SAlexander Belyaev auto f32Vec = broadcast(builder.getF32Type(), shape); 252ea7f211bSAhmed Taei // The exponent of f32 located at 23-bit. 253ea7f211bSAhmed Taei auto exponetBitLocation = bcast(i32Cst(builder, 23)); 254ea7f211bSAhmed Taei // Set the exponent bias to zero. 255ea7f211bSAhmed Taei auto bias = bcast(i32Cst(builder, 127)); 256ea7f211bSAhmed Taei 257a54f4eaeSMogball Value biasedArg = builder.create<arith::AddIOp>(arg, bias); 258ea7f211bSAhmed Taei Value exp2ValueInt = 259a54f4eaeSMogball builder.create<arith::ShLIOp>(biasedArg, exponetBitLocation); 260a54f4eaeSMogball Value exp2ValueF32 = builder.create<arith::BitcastOp>(f32Vec, exp2ValueInt); 261ea7f211bSAhmed Taei 262ea7f211bSAhmed Taei return exp2ValueF32; 263ea7f211bSAhmed Taei } 264ea7f211bSAhmed Taei 265f1b92218SBoian Petkantchin namespace { 266f1b92218SBoian Petkantchin Value makePolynomialCalculation(ImplicitLocOpBuilder &builder, 267f1b92218SBoian Petkantchin llvm::ArrayRef<Value> coeffs, Value x) { 268ec32d540SEugene Zhulenev assert(getElementTypeOrSelf(x).isF32() && "x must be f32 type"); 269ec32d540SEugene Zhulenev ArrayRef<int64_t> shape = vectorShape(x); 270ec32d540SEugene Zhulenev 271ec32d540SEugene Zhulenev if (coeffs.empty()) 272ec32d540SEugene Zhulenev return broadcast(builder, f32Cst(builder, 0.0f), shape); 273ec32d540SEugene Zhulenev 274ec32d540SEugene Zhulenev if (coeffs.size() == 1) 275f1b92218SBoian Petkantchin return coeffs[0]; 276ec32d540SEugene Zhulenev 277f1b92218SBoian Petkantchin Value res = builder.create<math::FmaOp>(x, coeffs[coeffs.size() - 1], 278f1b92218SBoian Petkantchin coeffs[coeffs.size() - 2]); 279f1b92218SBoian Petkantchin for (auto i = ptrdiff_t(coeffs.size()) - 3; i >= 0; --i) { 280f1b92218SBoian Petkantchin res = builder.create<math::FmaOp>(x, res, coeffs[i]); 281f1b92218SBoian Petkantchin } 282f1b92218SBoian Petkantchin return res; 283f1b92218SBoian Petkantchin } 284f1b92218SBoian Petkantchin } // namespace 285f1b92218SBoian Petkantchin 286f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------// 287*bbddd19eSJacques Pienaar // Helper function/pattern to insert casts for reusing F32 bit expansion. 288*bbddd19eSJacques Pienaar //----------------------------------------------------------------------------// 289*bbddd19eSJacques Pienaar 290*bbddd19eSJacques Pienaar template <typename T> 291*bbddd19eSJacques Pienaar LogicalResult insertCasts(Operation *op, PatternRewriter &rewriter) { 292*bbddd19eSJacques Pienaar // Conservatively only allow where the operand and result types are exactly 1. 293*bbddd19eSJacques Pienaar Type origType = op->getResultTypes().front(); 294*bbddd19eSJacques Pienaar for (Type t : llvm::drop_begin(op->getResultTypes())) 295*bbddd19eSJacques Pienaar if (origType != t) 296*bbddd19eSJacques Pienaar return rewriter.notifyMatchFailure(op, "required all types to match"); 297*bbddd19eSJacques Pienaar for (Type t : op->getOperandTypes()) 298*bbddd19eSJacques Pienaar if (origType != t) 299*bbddd19eSJacques Pienaar return rewriter.notifyMatchFailure(op, "required all types to match"); 300*bbddd19eSJacques Pienaar 301*bbddd19eSJacques Pienaar // Skip if already F32 or larger than 32 bits. 302*bbddd19eSJacques Pienaar if (getElementTypeOrSelf(origType).isF32() || 303*bbddd19eSJacques Pienaar getElementTypeOrSelf(origType).getIntOrFloatBitWidth() > 32) 304*bbddd19eSJacques Pienaar return failure(); 305*bbddd19eSJacques Pienaar 306*bbddd19eSJacques Pienaar // Create F32 equivalent type. 307*bbddd19eSJacques Pienaar Type newType; 308*bbddd19eSJacques Pienaar if (auto shaped = origType.dyn_cast<ShapedType>()) { 309*bbddd19eSJacques Pienaar newType = shaped.clone(rewriter.getF32Type()); 310*bbddd19eSJacques Pienaar } else if (origType.isa<FloatType>()) { 311*bbddd19eSJacques Pienaar newType = rewriter.getF32Type(); 312*bbddd19eSJacques Pienaar } else { 313*bbddd19eSJacques Pienaar return rewriter.notifyMatchFailure(op, 314*bbddd19eSJacques Pienaar "unable to find F32 equivalent type"); 315*bbddd19eSJacques Pienaar } 316*bbddd19eSJacques Pienaar 317*bbddd19eSJacques Pienaar Location loc = op->getLoc(); 318*bbddd19eSJacques Pienaar SmallVector<Value> operands; 319*bbddd19eSJacques Pienaar for (auto operand : op->getOperands()) 320*bbddd19eSJacques Pienaar operands.push_back(rewriter.create<arith::ExtFOp>(loc, newType, operand)); 321*bbddd19eSJacques Pienaar auto result = rewriter.create<math::Atan2Op>(loc, newType, operands); 322*bbddd19eSJacques Pienaar rewriter.replaceOpWithNewOp<arith::TruncFOp>(op, origType, result); 323*bbddd19eSJacques Pienaar return success(); 324*bbddd19eSJacques Pienaar } 325*bbddd19eSJacques Pienaar 326*bbddd19eSJacques Pienaar namespace { 327*bbddd19eSJacques Pienaar // Pattern to cast to F32 to reuse F32 expansion as fallback for single-result 328*bbddd19eSJacques Pienaar // op. 329*bbddd19eSJacques Pienaar // TODO: Consider revising to avoid adding multiple casts for a subgraph that is 330*bbddd19eSJacques Pienaar // all in lower precision. Currently this is only fallback support and performs 331*bbddd19eSJacques Pienaar // simplistic casting. 332*bbddd19eSJacques Pienaar template <typename T> 333*bbddd19eSJacques Pienaar struct ReuseF32Expansion : public OpRewritePattern<T> { 334*bbddd19eSJacques Pienaar public: 335*bbddd19eSJacques Pienaar using OpRewritePattern<T>::OpRewritePattern; 336*bbddd19eSJacques Pienaar LogicalResult matchAndRewrite(T op, PatternRewriter &rewriter) const final { 337*bbddd19eSJacques Pienaar static_assert( 338*bbddd19eSJacques Pienaar T::template hasTrait<mlir::OpTrait::SameOperandsAndResultType>(), 339*bbddd19eSJacques Pienaar "requires same operands and result types"); 340*bbddd19eSJacques Pienaar return insertCasts<T>(op, rewriter); 341*bbddd19eSJacques Pienaar } 342*bbddd19eSJacques Pienaar }; 343*bbddd19eSJacques Pienaar } // namespace 344*bbddd19eSJacques Pienaar 345*bbddd19eSJacques Pienaar //----------------------------------------------------------------------------// 3462f9f9afaSRob Suderman // AtanOp approximation. 3472f9f9afaSRob Suderman //----------------------------------------------------------------------------// 3482f9f9afaSRob Suderman 3492f9f9afaSRob Suderman namespace { 3502f9f9afaSRob Suderman struct AtanApproximation : public OpRewritePattern<math::AtanOp> { 3512f9f9afaSRob Suderman public: 3522f9f9afaSRob Suderman using OpRewritePattern::OpRewritePattern; 3532f9f9afaSRob Suderman 3542f9f9afaSRob Suderman LogicalResult matchAndRewrite(math::AtanOp op, 3552f9f9afaSRob Suderman PatternRewriter &rewriter) const final; 3562f9f9afaSRob Suderman }; 3572f9f9afaSRob Suderman } // namespace 3582f9f9afaSRob Suderman 3592f9f9afaSRob Suderman LogicalResult 3602f9f9afaSRob Suderman AtanApproximation::matchAndRewrite(math::AtanOp op, 3612f9f9afaSRob Suderman PatternRewriter &rewriter) const { 3622f9f9afaSRob Suderman auto operand = op.getOperand(); 3632f9f9afaSRob Suderman if (!getElementTypeOrSelf(operand).isF32()) 3642f9f9afaSRob Suderman return rewriter.notifyMatchFailure(op, "unsupported operand type"); 3652f9f9afaSRob Suderman 3662f9f9afaSRob Suderman ArrayRef<int64_t> shape = vectorShape(op.getOperand()); 3672f9f9afaSRob Suderman 3682f9f9afaSRob Suderman ImplicitLocOpBuilder builder(op->getLoc(), rewriter); 3692f9f9afaSRob Suderman auto one = broadcast(builder, f32Cst(builder, 1.0f), shape); 3702f9f9afaSRob Suderman 3712f9f9afaSRob Suderman // Remap the problem over [0.0, 1.0] by looking at the absolute value and the 3722f9f9afaSRob Suderman // handling symmetry. 3732f9f9afaSRob Suderman Value abs = builder.create<math::AbsOp>(operand); 3742f9f9afaSRob Suderman Value reciprocal = builder.create<arith::DivFOp>(one, abs); 3752f9f9afaSRob Suderman Value compare = 3762f9f9afaSRob Suderman builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, abs, reciprocal); 377dec8af70SRiver Riddle Value x = builder.create<arith::SelectOp>(compare, abs, reciprocal); 3782f9f9afaSRob Suderman 3792f9f9afaSRob Suderman // Perform the Taylor series approximation for atan over the range 3802f9f9afaSRob Suderman // [-1.0, 1.0]. 381dc3b9365SAlexandre Ganea auto n1 = broadcast(builder, f32Cst(builder, 0.14418283f), shape); 382dc3b9365SAlexandre Ganea auto n2 = broadcast(builder, f32Cst(builder, -0.34999234f), shape); 383dc3b9365SAlexandre Ganea auto n3 = broadcast(builder, f32Cst(builder, -0.01067831f), shape); 384dc3b9365SAlexandre Ganea auto n4 = broadcast(builder, f32Cst(builder, 1.00209986f), shape); 3852f9f9afaSRob Suderman 3862f9f9afaSRob Suderman Value p = builder.create<math::FmaOp>(x, n1, n2); 3872f9f9afaSRob Suderman p = builder.create<math::FmaOp>(x, p, n3); 3882f9f9afaSRob Suderman p = builder.create<math::FmaOp>(x, p, n4); 3892f9f9afaSRob Suderman p = builder.create<arith::MulFOp>(x, p); 3902f9f9afaSRob Suderman 3912f9f9afaSRob Suderman // Remap the solution for over [0.0, 1.0] to [0.0, inf] 39270ed93ecSMehdi Amini auto halfPi = broadcast(builder, f32Cst(builder, 1.57079632679f), shape); 39370ed93ecSMehdi Amini Value sub = builder.create<arith::SubFOp>(halfPi, p); 394dec8af70SRiver Riddle Value select = builder.create<arith::SelectOp>(compare, p, sub); 3952f9f9afaSRob Suderman 3962f9f9afaSRob Suderman // Correct for signing of the input. 3972f9f9afaSRob Suderman rewriter.replaceOpWithNewOp<math::CopySignOp>(op, select, operand); 3982f9f9afaSRob Suderman return success(); 3992f9f9afaSRob Suderman } 4002f9f9afaSRob Suderman 4012f9f9afaSRob Suderman //----------------------------------------------------------------------------// 4022f9f9afaSRob Suderman // AtanOp approximation. 4032f9f9afaSRob Suderman //----------------------------------------------------------------------------// 4042f9f9afaSRob Suderman 4052f9f9afaSRob Suderman namespace { 4062f9f9afaSRob Suderman struct Atan2Approximation : public OpRewritePattern<math::Atan2Op> { 4072f9f9afaSRob Suderman public: 4082f9f9afaSRob Suderman using OpRewritePattern::OpRewritePattern; 4092f9f9afaSRob Suderman 4102f9f9afaSRob Suderman LogicalResult matchAndRewrite(math::Atan2Op op, 4112f9f9afaSRob Suderman PatternRewriter &rewriter) const final; 4122f9f9afaSRob Suderman }; 4132f9f9afaSRob Suderman } // namespace 4142f9f9afaSRob Suderman 4152f9f9afaSRob Suderman LogicalResult 4162f9f9afaSRob Suderman Atan2Approximation::matchAndRewrite(math::Atan2Op op, 4172f9f9afaSRob Suderman PatternRewriter &rewriter) const { 4182f9f9afaSRob Suderman auto y = op.getOperand(0); 4192f9f9afaSRob Suderman auto x = op.getOperand(1); 4202f9f9afaSRob Suderman if (!getElementTypeOrSelf(x).isF32()) 4212f9f9afaSRob Suderman return rewriter.notifyMatchFailure(op, "unsupported operand type"); 4222f9f9afaSRob Suderman 4232f9f9afaSRob Suderman ImplicitLocOpBuilder builder(op->getLoc(), rewriter); 4242f9f9afaSRob Suderman ArrayRef<int64_t> shape = vectorShape(op.getResult()); 4252f9f9afaSRob Suderman 4262f9f9afaSRob Suderman // Compute atan in the valid range. 4272f9f9afaSRob Suderman auto div = builder.create<arith::DivFOp>(y, x); 4282f9f9afaSRob Suderman auto atan = builder.create<math::AtanOp>(div); 4292f9f9afaSRob Suderman 4302f9f9afaSRob Suderman // Determine what the atan would be for a 180 degree rotation. 4312f9f9afaSRob Suderman auto zero = broadcast(builder, f32Cst(builder, 0.0f), shape); 4322f9f9afaSRob Suderman auto pi = broadcast(builder, f32Cst(builder, 3.14159265359f), shape); 43370ed93ecSMehdi Amini auto addPi = builder.create<arith::AddFOp>(atan, pi); 43470ed93ecSMehdi Amini auto subPi = builder.create<arith::SubFOp>(atan, pi); 43570ed93ecSMehdi Amini auto atanGt = 4362f9f9afaSRob Suderman builder.create<arith::CmpFOp>(arith::CmpFPredicate::OGT, atan, zero); 437dec8af70SRiver Riddle auto flippedAtan = builder.create<arith::SelectOp>(atanGt, subPi, addPi); 4382f9f9afaSRob Suderman 4392f9f9afaSRob Suderman // Determine whether to directly use atan or use the 180 degree flip 44070ed93ecSMehdi Amini auto xGt = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OGT, x, zero); 441dec8af70SRiver Riddle Value result = builder.create<arith::SelectOp>(xGt, atan, flippedAtan); 4422f9f9afaSRob Suderman 4432f9f9afaSRob Suderman // Handle x = 0, y > 0 44470ed93ecSMehdi Amini Value xZero = 4452f9f9afaSRob Suderman builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, x, zero); 44670ed93ecSMehdi Amini Value yGt = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OGT, y, zero); 44770ed93ecSMehdi Amini Value isHalfPi = builder.create<arith::AndIOp>(xZero, yGt); 44870ed93ecSMehdi Amini auto halfPi = broadcast(builder, f32Cst(builder, 1.57079632679f), shape); 449dec8af70SRiver Riddle result = builder.create<arith::SelectOp>(isHalfPi, halfPi, result); 4502f9f9afaSRob Suderman 4512f9f9afaSRob Suderman // Handle x = 0, y < 0 45270ed93ecSMehdi Amini Value yLt = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, y, zero); 45370ed93ecSMehdi Amini Value isNegativeHalfPiPi = builder.create<arith::AndIOp>(xZero, yLt); 45470ed93ecSMehdi Amini auto negativeHalfPiPi = 455dc3b9365SAlexandre Ganea broadcast(builder, f32Cst(builder, -1.57079632679f), shape); 456dec8af70SRiver Riddle result = builder.create<arith::SelectOp>(isNegativeHalfPiPi, negativeHalfPiPi, 457dec8af70SRiver Riddle result); 4582f9f9afaSRob Suderman 4592f9f9afaSRob Suderman // Handle x = 0, y = 0; 46070ed93ecSMehdi Amini Value yZero = 4612f9f9afaSRob Suderman builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, y, zero); 46270ed93ecSMehdi Amini Value isNan = builder.create<arith::AndIOp>(xZero, yZero); 46370ed93ecSMehdi Amini Value cstNan = broadcast(builder, f32FromBits(builder, 0x7fc00000), shape); 464dec8af70SRiver Riddle result = builder.create<arith::SelectOp>(isNan, cstNan, result); 4652f9f9afaSRob Suderman 4662f9f9afaSRob Suderman rewriter.replaceOp(op, result); 4672f9f9afaSRob Suderman return success(); 4682f9f9afaSRob Suderman } 4692f9f9afaSRob Suderman 4702f9f9afaSRob Suderman //----------------------------------------------------------------------------// 471f99ccf65SEugene Zhulenev // TanhOp approximation. 472f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------// 473f99ccf65SEugene Zhulenev 474f99ccf65SEugene Zhulenev namespace { 475f99ccf65SEugene Zhulenev struct TanhApproximation : public OpRewritePattern<math::TanhOp> { 476f99ccf65SEugene Zhulenev public: 477f99ccf65SEugene Zhulenev using OpRewritePattern::OpRewritePattern; 478f99ccf65SEugene Zhulenev 479f99ccf65SEugene Zhulenev LogicalResult matchAndRewrite(math::TanhOp op, 480f99ccf65SEugene Zhulenev PatternRewriter &rewriter) const final; 481f99ccf65SEugene Zhulenev }; 482f99ccf65SEugene Zhulenev } // namespace 483f99ccf65SEugene Zhulenev 484f99ccf65SEugene Zhulenev LogicalResult 485f99ccf65SEugene Zhulenev TanhApproximation::matchAndRewrite(math::TanhOp op, 486f99ccf65SEugene Zhulenev PatternRewriter &rewriter) const { 48762fea88bSJacques Pienaar if (!getElementTypeOrSelf(op.getOperand()).isF32()) 488f99ccf65SEugene Zhulenev return rewriter.notifyMatchFailure(op, "unsupported operand type"); 489f99ccf65SEugene Zhulenev 49062fea88bSJacques Pienaar ArrayRef<int64_t> shape = vectorShape(op.getOperand()); 491ec32d540SEugene Zhulenev 492ce976d2dSEugene Zhulenev ImplicitLocOpBuilder builder(op->getLoc(), rewriter); 493ce976d2dSEugene Zhulenev auto bcast = [&](Value value) -> Value { 494ec32d540SEugene Zhulenev return broadcast(builder, value, shape); 495ce976d2dSEugene Zhulenev }; 496f99ccf65SEugene Zhulenev 497f99ccf65SEugene Zhulenev // Clamp operand into [plusClamp, minusClamp] range. 498bf32bb7eSEugene Zhulenev Value minusClamp = bcast(f32Cst(builder, -7.99881172180175781f)); 499bf32bb7eSEugene Zhulenev Value plusClamp = bcast(f32Cst(builder, 7.99881172180175781f)); 50062fea88bSJacques Pienaar Value x = clamp(builder, op.getOperand(), minusClamp, plusClamp); 501f99ccf65SEugene Zhulenev 502f99ccf65SEugene Zhulenev // Mask for tiny values that are approximated with `operand`. 503ce976d2dSEugene Zhulenev Value tiny = bcast(f32Cst(builder, 0.0004f)); 504a54f4eaeSMogball Value tinyMask = builder.create<arith::CmpFOp>( 50562fea88bSJacques Pienaar arith::CmpFPredicate::OLT, builder.create<math::AbsOp>(op.getOperand()), 506a54f4eaeSMogball tiny); 507f99ccf65SEugene Zhulenev 508f99ccf65SEugene Zhulenev // The monomial coefficients of the numerator polynomial (odd). 509ce976d2dSEugene Zhulenev Value alpha1 = bcast(f32Cst(builder, 4.89352455891786e-03f)); 510ce976d2dSEugene Zhulenev Value alpha3 = bcast(f32Cst(builder, 6.37261928875436e-04f)); 511ce976d2dSEugene Zhulenev Value alpha5 = bcast(f32Cst(builder, 1.48572235717979e-05f)); 512ce976d2dSEugene Zhulenev Value alpha7 = bcast(f32Cst(builder, 5.12229709037114e-08f)); 513ce976d2dSEugene Zhulenev Value alpha9 = bcast(f32Cst(builder, -8.60467152213735e-11f)); 514ce976d2dSEugene Zhulenev Value alpha11 = bcast(f32Cst(builder, 2.00018790482477e-13f)); 515ce976d2dSEugene Zhulenev Value alpha13 = bcast(f32Cst(builder, -2.76076847742355e-16f)); 516f99ccf65SEugene Zhulenev 517f99ccf65SEugene Zhulenev // The monomial coefficients of the denominator polynomial (even). 518ce976d2dSEugene Zhulenev Value beta0 = bcast(f32Cst(builder, 4.89352518554385e-03f)); 519ce976d2dSEugene Zhulenev Value beta2 = bcast(f32Cst(builder, 2.26843463243900e-03f)); 520ce976d2dSEugene Zhulenev Value beta4 = bcast(f32Cst(builder, 1.18534705686654e-04f)); 521ce976d2dSEugene Zhulenev Value beta6 = bcast(f32Cst(builder, 1.19825839466702e-06f)); 522f99ccf65SEugene Zhulenev 523f99ccf65SEugene Zhulenev // Since the polynomials are odd/even, we need x^2. 524a54f4eaeSMogball Value x2 = builder.create<arith::MulFOp>(x, x); 525f99ccf65SEugene Zhulenev 526f99ccf65SEugene Zhulenev // Evaluate the numerator polynomial p. 527a54f4eaeSMogball Value p = builder.create<math::FmaOp>(x2, alpha13, alpha11); 528a54f4eaeSMogball p = builder.create<math::FmaOp>(x2, p, alpha9); 529a54f4eaeSMogball p = builder.create<math::FmaOp>(x2, p, alpha7); 530a54f4eaeSMogball p = builder.create<math::FmaOp>(x2, p, alpha5); 531a54f4eaeSMogball p = builder.create<math::FmaOp>(x2, p, alpha3); 532a54f4eaeSMogball p = builder.create<math::FmaOp>(x2, p, alpha1); 533a54f4eaeSMogball p = builder.create<arith::MulFOp>(x, p); 534f99ccf65SEugene Zhulenev 535f99ccf65SEugene Zhulenev // Evaluate the denominator polynomial q. 536a54f4eaeSMogball Value q = builder.create<math::FmaOp>(x2, beta6, beta4); 537a54f4eaeSMogball q = builder.create<math::FmaOp>(x2, q, beta2); 538a54f4eaeSMogball q = builder.create<math::FmaOp>(x2, q, beta0); 539f99ccf65SEugene Zhulenev 540f99ccf65SEugene Zhulenev // Divide the numerator by the denominator. 541dec8af70SRiver Riddle Value res = builder.create<arith::SelectOp>( 542dec8af70SRiver Riddle tinyMask, x, builder.create<arith::DivFOp>(p, q)); 543f99ccf65SEugene Zhulenev 544f99ccf65SEugene Zhulenev rewriter.replaceOp(op, res); 545f99ccf65SEugene Zhulenev 546f99ccf65SEugene Zhulenev return success(); 547f99ccf65SEugene Zhulenev } 548f99ccf65SEugene Zhulenev 549ea7f211bSAhmed Taei #define LN2_VALUE \ 550ea7f211bSAhmed Taei 0.693147180559945309417232121458176568075500134360255254120680009493393621L 551c0891706SEmilio Cota #define LOG2E_VALUE \ 552ea7f211bSAhmed Taei 1.442695040888963407359924681001892137426645954152985934135449406931109219L 553ea7f211bSAhmed Taei 554f99ccf65SEugene Zhulenev //----------------------------------------------------------------------------// 555c0891706SEmilio Cota // LogOp and Log2Op approximation. 556ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------// 557ce976d2dSEugene Zhulenev 558ce976d2dSEugene Zhulenev namespace { 559c0891706SEmilio Cota template <typename Op> 560c0891706SEmilio Cota struct LogApproximationBase : public OpRewritePattern<Op> { 561c0891706SEmilio Cota using OpRewritePattern<Op>::OpRewritePattern; 562ce976d2dSEugene Zhulenev 563c0891706SEmilio Cota /// Base 2 if 'base2' is set; natural logarithm (base e) otherwise. 564c0891706SEmilio Cota LogicalResult logMatchAndRewrite(Op op, PatternRewriter &rewriter, 565c0891706SEmilio Cota bool base2) const; 566ce976d2dSEugene Zhulenev }; 567ce976d2dSEugene Zhulenev } // namespace 568ce976d2dSEugene Zhulenev 569c0891706SEmilio Cota // This approximation comes from Julien Pommier's SSE math library. 570c0891706SEmilio Cota // Link: http://gruntthepeon.free.fr/ssemath 571c0891706SEmilio Cota template <typename Op> 572ce976d2dSEugene Zhulenev LogicalResult 573c0891706SEmilio Cota LogApproximationBase<Op>::logMatchAndRewrite(Op op, PatternRewriter &rewriter, 574c0891706SEmilio Cota bool base2) const { 57562fea88bSJacques Pienaar if (!getElementTypeOrSelf(op.getOperand()).isF32()) 576ce976d2dSEugene Zhulenev return rewriter.notifyMatchFailure(op, "unsupported operand type"); 577ce976d2dSEugene Zhulenev 57862fea88bSJacques Pienaar ArrayRef<int64_t> shape = vectorShape(op.getOperand()); 579ec32d540SEugene Zhulenev 580ce976d2dSEugene Zhulenev ImplicitLocOpBuilder builder(op->getLoc(), rewriter); 581ce976d2dSEugene Zhulenev auto bcast = [&](Value value) -> Value { 582ec32d540SEugene Zhulenev return broadcast(builder, value, shape); 583ce976d2dSEugene Zhulenev }; 584ce976d2dSEugene Zhulenev 585ce976d2dSEugene Zhulenev Value cstZero = bcast(f32Cst(builder, 0.0f)); 586ce976d2dSEugene Zhulenev Value cstOne = bcast(f32Cst(builder, 1.0f)); 587ce976d2dSEugene Zhulenev Value cstNegHalf = bcast(f32Cst(builder, -0.5f)); 588ce976d2dSEugene Zhulenev 589ce976d2dSEugene Zhulenev // The smallest non denormalized float number. 590ce976d2dSEugene Zhulenev Value cstMinNormPos = bcast(f32FromBits(builder, 0x00800000u)); 591ce976d2dSEugene Zhulenev Value cstMinusInf = bcast(f32FromBits(builder, 0xff800000u)); 592ce976d2dSEugene Zhulenev Value cstPosInf = bcast(f32FromBits(builder, 0x7f800000u)); 593ce976d2dSEugene Zhulenev Value cstNan = bcast(f32FromBits(builder, 0x7fc00000)); 594ce976d2dSEugene Zhulenev 595ce976d2dSEugene Zhulenev // Polynomial coefficients. 596ce976d2dSEugene Zhulenev Value cstCephesSQRTHF = bcast(f32Cst(builder, 0.707106781186547524f)); 597ce976d2dSEugene Zhulenev Value cstCephesLogP0 = bcast(f32Cst(builder, 7.0376836292E-2f)); 598ce976d2dSEugene Zhulenev Value cstCephesLogP1 = bcast(f32Cst(builder, -1.1514610310E-1f)); 599ce976d2dSEugene Zhulenev Value cstCephesLogP2 = bcast(f32Cst(builder, 1.1676998740E-1f)); 600ce976d2dSEugene Zhulenev Value cstCephesLogP3 = bcast(f32Cst(builder, -1.2420140846E-1f)); 601ce976d2dSEugene Zhulenev Value cstCephesLogP4 = bcast(f32Cst(builder, +1.4249322787E-1f)); 602ce976d2dSEugene Zhulenev Value cstCephesLogP5 = bcast(f32Cst(builder, -1.6668057665E-1f)); 603ce976d2dSEugene Zhulenev Value cstCephesLogP6 = bcast(f32Cst(builder, +2.0000714765E-1f)); 604ce976d2dSEugene Zhulenev Value cstCephesLogP7 = bcast(f32Cst(builder, -2.4999993993E-1f)); 605ce976d2dSEugene Zhulenev Value cstCephesLogP8 = bcast(f32Cst(builder, +3.3333331174E-1f)); 606ce976d2dSEugene Zhulenev 60762fea88bSJacques Pienaar Value x = op.getOperand(); 608ce976d2dSEugene Zhulenev 609ce976d2dSEugene Zhulenev // Truncate input values to the minimum positive normal. 610ce976d2dSEugene Zhulenev x = max(builder, x, cstMinNormPos); 611ce976d2dSEugene Zhulenev 612ce976d2dSEugene Zhulenev // Extract significant in the range [0.5,1) and exponent. 613ced8690dSMehdi Amini std::pair<Value, Value> pair = frexp(builder, x, /*isPositive=*/true); 614ce976d2dSEugene Zhulenev x = pair.first; 615ce976d2dSEugene Zhulenev Value e = pair.second; 616ce976d2dSEugene Zhulenev 617ce976d2dSEugene Zhulenev // Shift the inputs from the range [0.5,1) to [sqrt(1/2), sqrt(2)) and shift 618ce976d2dSEugene Zhulenev // by -1.0. The values are then centered around 0, which improves the 619ce976d2dSEugene Zhulenev // stability of the polynomial evaluation: 620ce976d2dSEugene Zhulenev // 621ce976d2dSEugene Zhulenev // if( x < SQRTHF ) { 622ce976d2dSEugene Zhulenev // e -= 1; 623ce976d2dSEugene Zhulenev // x = x + x - 1.0; 624ce976d2dSEugene Zhulenev // } else { x = x - 1.0; } 625a54f4eaeSMogball Value mask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, x, 626a54f4eaeSMogball cstCephesSQRTHF); 627dec8af70SRiver Riddle Value tmp = builder.create<arith::SelectOp>(mask, x, cstZero); 628ce976d2dSEugene Zhulenev 629a54f4eaeSMogball x = builder.create<arith::SubFOp>(x, cstOne); 630a54f4eaeSMogball e = builder.create<arith::SubFOp>( 631dec8af70SRiver Riddle e, builder.create<arith::SelectOp>(mask, cstOne, cstZero)); 632a54f4eaeSMogball x = builder.create<arith::AddFOp>(x, tmp); 633ce976d2dSEugene Zhulenev 634a54f4eaeSMogball Value x2 = builder.create<arith::MulFOp>(x, x); 635a54f4eaeSMogball Value x3 = builder.create<arith::MulFOp>(x2, x); 636ce976d2dSEugene Zhulenev 637ce976d2dSEugene Zhulenev // Evaluate the polynomial approximant of degree 8 in three parts. 638ce976d2dSEugene Zhulenev Value y0, y1, y2; 639a54f4eaeSMogball y0 = builder.create<math::FmaOp>(cstCephesLogP0, x, cstCephesLogP1); 640a54f4eaeSMogball y1 = builder.create<math::FmaOp>(cstCephesLogP3, x, cstCephesLogP4); 641a54f4eaeSMogball y2 = builder.create<math::FmaOp>(cstCephesLogP6, x, cstCephesLogP7); 642a54f4eaeSMogball y0 = builder.create<math::FmaOp>(y0, x, cstCephesLogP2); 643a54f4eaeSMogball y1 = builder.create<math::FmaOp>(y1, x, cstCephesLogP5); 644a54f4eaeSMogball y2 = builder.create<math::FmaOp>(y2, x, cstCephesLogP8); 645a54f4eaeSMogball y0 = builder.create<math::FmaOp>(y0, x3, y1); 646a54f4eaeSMogball y0 = builder.create<math::FmaOp>(y0, x3, y2); 647a54f4eaeSMogball y0 = builder.create<arith::MulFOp>(y0, x3); 648ce976d2dSEugene Zhulenev 649a54f4eaeSMogball y0 = builder.create<math::FmaOp>(cstNegHalf, x2, y0); 650a54f4eaeSMogball x = builder.create<arith::AddFOp>(x, y0); 651ce976d2dSEugene Zhulenev 652c0891706SEmilio Cota if (base2) { 653c0891706SEmilio Cota Value cstLog2e = bcast(f32Cst(builder, static_cast<float>(LOG2E_VALUE))); 654a54f4eaeSMogball x = builder.create<math::FmaOp>(x, cstLog2e, e); 655c0891706SEmilio Cota } else { 656ce976d2dSEugene Zhulenev Value cstLn2 = bcast(f32Cst(builder, static_cast<float>(LN2_VALUE))); 657a54f4eaeSMogball x = builder.create<math::FmaOp>(e, cstLn2, x); 658c0891706SEmilio Cota } 659ce976d2dSEugene Zhulenev 660a54f4eaeSMogball Value invalidMask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::ULT, 66162fea88bSJacques Pienaar op.getOperand(), cstZero); 662a54f4eaeSMogball Value zeroMask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, 66362fea88bSJacques Pienaar op.getOperand(), cstZero); 664a54f4eaeSMogball Value posInfMask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, 66562fea88bSJacques Pienaar op.getOperand(), cstPosInf); 666ce976d2dSEugene Zhulenev 667ce976d2dSEugene Zhulenev // Filter out invalid values: 668ce976d2dSEugene Zhulenev // • x == 0 -> -INF 669ce976d2dSEugene Zhulenev // • x < 0 -> NAN 670ce976d2dSEugene Zhulenev // • x == +INF -> +INF 671dec8af70SRiver Riddle Value aproximation = builder.create<arith::SelectOp>( 672ce976d2dSEugene Zhulenev zeroMask, cstMinusInf, 673dec8af70SRiver Riddle builder.create<arith::SelectOp>( 674ce976d2dSEugene Zhulenev invalidMask, cstNan, 675dec8af70SRiver Riddle builder.create<arith::SelectOp>(posInfMask, cstPosInf, x))); 676ce976d2dSEugene Zhulenev 677ce976d2dSEugene Zhulenev rewriter.replaceOp(op, aproximation); 678ce976d2dSEugene Zhulenev 679ce976d2dSEugene Zhulenev return success(); 680ce976d2dSEugene Zhulenev } 681ce976d2dSEugene Zhulenev 682c0891706SEmilio Cota namespace { 683c0891706SEmilio Cota struct LogApproximation : public LogApproximationBase<math::LogOp> { 684c0891706SEmilio Cota using LogApproximationBase::LogApproximationBase; 685c0891706SEmilio Cota 686c0891706SEmilio Cota LogicalResult matchAndRewrite(math::LogOp op, 687c0891706SEmilio Cota PatternRewriter &rewriter) const final { 688c0891706SEmilio Cota return logMatchAndRewrite(op, rewriter, /*base2=*/false); 689c0891706SEmilio Cota } 690c0891706SEmilio Cota }; 691c0891706SEmilio Cota } // namespace 692c0891706SEmilio Cota 693c0891706SEmilio Cota namespace { 694c0891706SEmilio Cota struct Log2Approximation : public LogApproximationBase<math::Log2Op> { 695c0891706SEmilio Cota using LogApproximationBase::LogApproximationBase; 696c0891706SEmilio Cota 697c0891706SEmilio Cota LogicalResult matchAndRewrite(math::Log2Op op, 698c0891706SEmilio Cota PatternRewriter &rewriter) const final { 699c0891706SEmilio Cota return logMatchAndRewrite(op, rewriter, /*base2=*/true); 700c0891706SEmilio Cota } 701c0891706SEmilio Cota }; 702c0891706SEmilio Cota } // namespace 703c0891706SEmilio Cota 704ce976d2dSEugene Zhulenev //----------------------------------------------------------------------------// 7051c0374e7SEmilio Cota // Log1p approximation. 7061c0374e7SEmilio Cota //----------------------------------------------------------------------------// 7071c0374e7SEmilio Cota 7081c0374e7SEmilio Cota namespace { 7091c0374e7SEmilio Cota struct Log1pApproximation : public OpRewritePattern<math::Log1pOp> { 7101c0374e7SEmilio Cota public: 7111c0374e7SEmilio Cota using OpRewritePattern::OpRewritePattern; 7121c0374e7SEmilio Cota 7131c0374e7SEmilio Cota LogicalResult matchAndRewrite(math::Log1pOp op, 7141c0374e7SEmilio Cota PatternRewriter &rewriter) const final; 7151c0374e7SEmilio Cota }; 7161c0374e7SEmilio Cota } // namespace 7171c0374e7SEmilio Cota 7181c0374e7SEmilio Cota // Approximate log(1+x). 7191c0374e7SEmilio Cota LogicalResult 7201c0374e7SEmilio Cota Log1pApproximation::matchAndRewrite(math::Log1pOp op, 7211c0374e7SEmilio Cota PatternRewriter &rewriter) const { 72262fea88bSJacques Pienaar if (!getElementTypeOrSelf(op.getOperand()).isF32()) 7231c0374e7SEmilio Cota return rewriter.notifyMatchFailure(op, "unsupported operand type"); 7241c0374e7SEmilio Cota 72562fea88bSJacques Pienaar ArrayRef<int64_t> shape = vectorShape(op.getOperand()); 726ec32d540SEugene Zhulenev 7271c0374e7SEmilio Cota ImplicitLocOpBuilder builder(op->getLoc(), rewriter); 7281c0374e7SEmilio Cota auto bcast = [&](Value value) -> Value { 729ec32d540SEugene Zhulenev return broadcast(builder, value, shape); 7301c0374e7SEmilio Cota }; 7311c0374e7SEmilio Cota 7321c0374e7SEmilio Cota // Approximate log(1+x) using the following, due to W. Kahan: 7331c0374e7SEmilio Cota // u = x + 1.0; 7341c0374e7SEmilio Cota // if (u == 1.0 || u == inf) return x; 7351c0374e7SEmilio Cota // return x * log(u) / (u - 1.0); 7361c0374e7SEmilio Cota // ^^^^^^^^^^^^^^^^^^^^^^ 7371c0374e7SEmilio Cota // "logLarge" below. 7381c0374e7SEmilio Cota Value cstOne = bcast(f32Cst(builder, 1.0f)); 73962fea88bSJacques Pienaar Value x = op.getOperand(); 740a54f4eaeSMogball Value u = builder.create<arith::AddFOp>(x, cstOne); 741a54f4eaeSMogball Value uSmall = 742a54f4eaeSMogball builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, u, cstOne); 7431c0374e7SEmilio Cota Value logU = builder.create<math::LogOp>(u); 744a54f4eaeSMogball Value uInf = 745a54f4eaeSMogball builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, u, logU); 746a54f4eaeSMogball Value logLarge = builder.create<arith::MulFOp>( 747a54f4eaeSMogball x, builder.create<arith::DivFOp>( 748a54f4eaeSMogball logU, builder.create<arith::SubFOp>(u, cstOne))); 749dec8af70SRiver Riddle Value approximation = builder.create<arith::SelectOp>( 750a54f4eaeSMogball builder.create<arith::OrIOp>(uSmall, uInf), x, logLarge); 7511c0374e7SEmilio Cota rewriter.replaceOp(op, approximation); 7521c0374e7SEmilio Cota return success(); 7531c0374e7SEmilio Cota } 7541c0374e7SEmilio Cota 7551c0374e7SEmilio Cota //----------------------------------------------------------------------------// 756f1b92218SBoian Petkantchin // Erf approximation. 757f1b92218SBoian Petkantchin //----------------------------------------------------------------------------// 758f1b92218SBoian Petkantchin 759f1b92218SBoian Petkantchin // Approximates erf(x) with 760f1b92218SBoian Petkantchin // a - P(x)/Q(x) 761f1b92218SBoian Petkantchin // where P and Q are polynomials of degree 4. 762f1b92218SBoian Petkantchin // Different coefficients are chosen based on the value of x. 763f1b92218SBoian Petkantchin // The approximation error is ~2.5e-07. 764f1b92218SBoian Petkantchin // Boost's minimax tool that utilizes the Remez method was used to find the 765f1b92218SBoian Petkantchin // coefficients. 766f1b92218SBoian Petkantchin LogicalResult 767f1b92218SBoian Petkantchin ErfPolynomialApproximation::matchAndRewrite(math::ErfOp op, 768f1b92218SBoian Petkantchin PatternRewriter &rewriter) const { 76962fea88bSJacques Pienaar if (!getElementTypeOrSelf(op.getOperand()).isF32()) 770f1b92218SBoian Petkantchin return rewriter.notifyMatchFailure(op, "unsupported operand type"); 771f1b92218SBoian Petkantchin 77262fea88bSJacques Pienaar ArrayRef<int64_t> shape = vectorShape(op.getOperand()); 773ec32d540SEugene Zhulenev 774f1b92218SBoian Petkantchin ImplicitLocOpBuilder builder(op->getLoc(), rewriter); 775f1b92218SBoian Petkantchin auto bcast = [&](Value value) -> Value { 776ec32d540SEugene Zhulenev return broadcast(builder, value, shape); 777f1b92218SBoian Petkantchin }; 778f1b92218SBoian Petkantchin 779f1b92218SBoian Petkantchin const int intervalsCount = 3; 780f1b92218SBoian Petkantchin const int polyDegree = 4; 781f1b92218SBoian Petkantchin 782f1b92218SBoian Petkantchin Value zero = bcast(f32Cst(builder, 0)); 783f1b92218SBoian Petkantchin Value one = bcast(f32Cst(builder, 1)); 784f1b92218SBoian Petkantchin Value pp[intervalsCount][polyDegree + 1]; 7857d79a257SAlexander Belyaev pp[0][0] = bcast(f32Cst(builder, +0.00000000000000000e+00f)); 7867d79a257SAlexander Belyaev pp[0][1] = bcast(f32Cst(builder, +1.12837916222975858e+00f)); 7877d79a257SAlexander Belyaev pp[0][2] = bcast(f32Cst(builder, -5.23018562988006470e-01f)); 7887d79a257SAlexander Belyaev pp[0][3] = bcast(f32Cst(builder, +2.09741709609267072e-01f)); 7897d79a257SAlexander Belyaev pp[0][4] = bcast(f32Cst(builder, +2.58146801602987875e-02f)); 7907d79a257SAlexander Belyaev pp[1][0] = bcast(f32Cst(builder, +0.00000000000000000e+00f)); 7917d79a257SAlexander Belyaev pp[1][1] = bcast(f32Cst(builder, +1.12750687816789140e+00f)); 7927d79a257SAlexander Belyaev pp[1][2] = bcast(f32Cst(builder, -3.64721408487825775e-01f)); 7937d79a257SAlexander Belyaev pp[1][3] = bcast(f32Cst(builder, +1.18407396425136952e-01f)); 7947d79a257SAlexander Belyaev pp[1][4] = bcast(f32Cst(builder, +3.70645533056476558e-02f)); 7957d79a257SAlexander Belyaev pp[2][0] = bcast(f32Cst(builder, -3.30093071049483172e-03f)); 7967d79a257SAlexander Belyaev pp[2][1] = bcast(f32Cst(builder, +3.51961938357697011e-03f)); 7977d79a257SAlexander Belyaev pp[2][2] = bcast(f32Cst(builder, -1.41373622814988039e-03f)); 7987d79a257SAlexander Belyaev pp[2][3] = bcast(f32Cst(builder, +2.53447094961941348e-04f)); 7997d79a257SAlexander Belyaev pp[2][4] = bcast(f32Cst(builder, -1.71048029455037401e-05f)); 800f1b92218SBoian Petkantchin 801f1b92218SBoian Petkantchin Value qq[intervalsCount][polyDegree + 1]; 8027d79a257SAlexander Belyaev qq[0][0] = bcast(f32Cst(builder, +1.000000000000000000e+00f)); 8037d79a257SAlexander Belyaev qq[0][1] = bcast(f32Cst(builder, -4.635138185962547255e-01f)); 8047d79a257SAlexander Belyaev qq[0][2] = bcast(f32Cst(builder, +5.192301327279782447e-01f)); 8057d79a257SAlexander Belyaev qq[0][3] = bcast(f32Cst(builder, -1.318089722204810087e-01f)); 8067d79a257SAlexander Belyaev qq[0][4] = bcast(f32Cst(builder, +7.397964654672315005e-02f)); 8077d79a257SAlexander Belyaev qq[1][0] = bcast(f32Cst(builder, +1.00000000000000000e+00f)); 8087d79a257SAlexander Belyaev qq[1][1] = bcast(f32Cst(builder, -3.27607011824493086e-01f)); 8097d79a257SAlexander Belyaev qq[1][2] = bcast(f32Cst(builder, +4.48369090658821977e-01f)); 8107d79a257SAlexander Belyaev qq[1][3] = bcast(f32Cst(builder, -8.83462621207857930e-02f)); 8117d79a257SAlexander Belyaev qq[1][4] = bcast(f32Cst(builder, +5.72442770283176093e-02f)); 8127d79a257SAlexander Belyaev qq[2][0] = bcast(f32Cst(builder, +1.00000000000000000e+00f)); 8137d79a257SAlexander Belyaev qq[2][1] = bcast(f32Cst(builder, -2.06069165953913769e+00f)); 8147d79a257SAlexander Belyaev qq[2][2] = bcast(f32Cst(builder, +1.62705939945477759e+00f)); 8157d79a257SAlexander Belyaev qq[2][3] = bcast(f32Cst(builder, -5.83389859211130017e-01f)); 8167d79a257SAlexander Belyaev qq[2][4] = bcast(f32Cst(builder, +8.21908939856640930e-02f)); 817f1b92218SBoian Petkantchin 818f1b92218SBoian Petkantchin Value offsets[intervalsCount]; 8197d79a257SAlexander Belyaev offsets[0] = bcast(f32Cst(builder, 0.0f)); 8207d79a257SAlexander Belyaev offsets[1] = bcast(f32Cst(builder, 0.0f)); 8217d79a257SAlexander Belyaev offsets[2] = bcast(f32Cst(builder, 1.0f)); 822f1b92218SBoian Petkantchin 823f1b92218SBoian Petkantchin Value bounds[intervalsCount]; 8247d79a257SAlexander Belyaev bounds[0] = bcast(f32Cst(builder, 0.8f)); 8257d79a257SAlexander Belyaev bounds[1] = bcast(f32Cst(builder, 2.0f)); 8267d79a257SAlexander Belyaev bounds[2] = bcast(f32Cst(builder, 3.75f)); 827f1b92218SBoian Petkantchin 828f1b92218SBoian Petkantchin Value isNegativeArg = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, 82962fea88bSJacques Pienaar op.getOperand(), zero); 83062fea88bSJacques Pienaar Value negArg = builder.create<arith::NegFOp>(op.getOperand()); 831dec8af70SRiver Riddle Value x = 832dec8af70SRiver Riddle builder.create<arith::SelectOp>(isNegativeArg, negArg, op.getOperand()); 833f1b92218SBoian Petkantchin 834f1b92218SBoian Petkantchin Value offset = offsets[0]; 835f1b92218SBoian Petkantchin Value p[polyDegree + 1]; 836f1b92218SBoian Petkantchin Value q[polyDegree + 1]; 837f1b92218SBoian Petkantchin for (int i = 0; i <= polyDegree; ++i) { 838f1b92218SBoian Petkantchin p[i] = pp[0][i]; 839f1b92218SBoian Petkantchin q[i] = qq[0][i]; 840f1b92218SBoian Petkantchin } 841f1b92218SBoian Petkantchin 842f1b92218SBoian Petkantchin // TODO: maybe use vector stacking to reduce the number of selects. 843f1b92218SBoian Petkantchin Value isLessThanBound[intervalsCount]; 844f1b92218SBoian Petkantchin for (int j = 0; j < intervalsCount - 1; ++j) { 845f1b92218SBoian Petkantchin isLessThanBound[j] = 846f1b92218SBoian Petkantchin builder.create<arith::CmpFOp>(arith::CmpFPredicate::OLT, x, bounds[j]); 847f1b92218SBoian Petkantchin for (int i = 0; i <= polyDegree; ++i) { 848dec8af70SRiver Riddle p[i] = builder.create<arith::SelectOp>(isLessThanBound[j], p[i], 849dec8af70SRiver Riddle pp[j + 1][i]); 850dec8af70SRiver Riddle q[i] = builder.create<arith::SelectOp>(isLessThanBound[j], q[i], 851dec8af70SRiver Riddle qq[j + 1][i]); 852f1b92218SBoian Petkantchin } 853dec8af70SRiver Riddle offset = builder.create<arith::SelectOp>(isLessThanBound[j], offset, 854dec8af70SRiver Riddle offsets[j + 1]); 855f1b92218SBoian Petkantchin } 856f1b92218SBoian Petkantchin isLessThanBound[intervalsCount - 1] = builder.create<arith::CmpFOp>( 857f1b92218SBoian Petkantchin arith::CmpFPredicate::ULT, x, bounds[intervalsCount - 1]); 858f1b92218SBoian Petkantchin 859f1b92218SBoian Petkantchin Value pPoly = makePolynomialCalculation(builder, p, x); 860f1b92218SBoian Petkantchin Value qPoly = makePolynomialCalculation(builder, q, x); 861f1b92218SBoian Petkantchin Value rationalPoly = builder.create<arith::DivFOp>(pPoly, qPoly); 862f1b92218SBoian Petkantchin Value formula = builder.create<arith::AddFOp>(offset, rationalPoly); 863dec8af70SRiver Riddle formula = builder.create<arith::SelectOp>(isLessThanBound[intervalsCount - 1], 864f1b92218SBoian Petkantchin formula, one); 865f1b92218SBoian Petkantchin 866f1b92218SBoian Petkantchin // erf is odd function: erf(x) = -erf(-x). 867f1b92218SBoian Petkantchin Value negFormula = builder.create<arith::NegFOp>(formula); 868dec8af70SRiver Riddle Value res = 869dec8af70SRiver Riddle builder.create<arith::SelectOp>(isNegativeArg, negFormula, formula); 870f1b92218SBoian Petkantchin 871f1b92218SBoian Petkantchin rewriter.replaceOp(op, res); 872f1b92218SBoian Petkantchin 873f1b92218SBoian Petkantchin return success(); 874f1b92218SBoian Petkantchin } 875f1b92218SBoian Petkantchin 876f1b92218SBoian Petkantchin //----------------------------------------------------------------------------// 877ea7f211bSAhmed Taei // Exp approximation. 878ea7f211bSAhmed Taei //----------------------------------------------------------------------------// 879ea7f211bSAhmed Taei 880ea7f211bSAhmed Taei namespace { 881ea7f211bSAhmed Taei 882ea7f211bSAhmed Taei struct ExpApproximation : public OpRewritePattern<math::ExpOp> { 883ea7f211bSAhmed Taei public: 884ea7f211bSAhmed Taei using OpRewritePattern::OpRewritePattern; 885ea7f211bSAhmed Taei 886ea7f211bSAhmed Taei LogicalResult matchAndRewrite(math::ExpOp op, 887ea7f211bSAhmed Taei PatternRewriter &rewriter) const final; 888ea7f211bSAhmed Taei }; 889ea7f211bSAhmed Taei } // namespace 890ea7f211bSAhmed Taei 891ea7f211bSAhmed Taei // Approximate exp(x) using its reduced range exp(y) where y is in the range 892ea7f211bSAhmed Taei // [0, ln(2)], let y = x - floor(x / ln(2)) * ln(2) = x - k * ln(2), exp(x) 893ea7f211bSAhmed Taei // = exp(y) * 2^k. exp(y). 894ea7f211bSAhmed Taei LogicalResult 895ea7f211bSAhmed Taei ExpApproximation::matchAndRewrite(math::ExpOp op, 896ea7f211bSAhmed Taei PatternRewriter &rewriter) const { 89762fea88bSJacques Pienaar if (!getElementTypeOrSelf(op.getOperand()).isF32()) 898ea7f211bSAhmed Taei return rewriter.notifyMatchFailure(op, "unsupported operand type"); 899ec32d540SEugene Zhulenev 90062fea88bSJacques Pienaar ArrayRef<int64_t> shape = vectorShape(op.getOperand()); 901ec32d540SEugene Zhulenev 902ea7f211bSAhmed Taei ImplicitLocOpBuilder builder(op->getLoc(), rewriter); 903ea7f211bSAhmed Taei 904ea7f211bSAhmed Taei // TODO: Consider a common pattern rewriter with all methods below to 905ea7f211bSAhmed Taei // write the approximations. 906ea7f211bSAhmed Taei auto bcast = [&](Value value) -> Value { 907ec32d540SEugene Zhulenev return broadcast(builder, value, shape); 908ea7f211bSAhmed Taei }; 909ea7f211bSAhmed Taei auto fmla = [&](Value a, Value b, Value c) { 910a54f4eaeSMogball return builder.create<math::FmaOp>(a, b, c); 911ea7f211bSAhmed Taei }; 912ea7f211bSAhmed Taei auto mul = [&](Value a, Value b) -> Value { 913a54f4eaeSMogball return builder.create<arith::MulFOp>(a, b); 914ea7f211bSAhmed Taei }; 915ea7f211bSAhmed Taei auto sub = [&](Value a, Value b) -> Value { 916a54f4eaeSMogball return builder.create<arith::SubFOp>(a, b); 917ea7f211bSAhmed Taei }; 918a54f4eaeSMogball auto floor = [&](Value a) { return builder.create<math::FloorOp>(a); }; 919ea7f211bSAhmed Taei 920ea7f211bSAhmed Taei Value cstLn2 = bcast(f32Cst(builder, static_cast<float>(LN2_VALUE))); 921c0891706SEmilio Cota Value cstLog2E = bcast(f32Cst(builder, static_cast<float>(LOG2E_VALUE))); 922ea7f211bSAhmed Taei 923ea7f211bSAhmed Taei // Polynomial coefficients. 924ea7f211bSAhmed Taei Value cstCephesExpP0 = bcast(f32Cst(builder, 1.0)); 925ea7f211bSAhmed Taei Value cstCephesExpP1 = bcast(f32Cst(builder, 1.0)); 926ea7f211bSAhmed Taei Value cstCephesExpP2 = bcast(f32Cst(builder, 0.49970514590562437052f)); 927ea7f211bSAhmed Taei Value cstCephesExpP3 = bcast(f32Cst(builder, 0.16873890085469545053f)); 928ea7f211bSAhmed Taei Value cstCephesExpP4 = bcast(f32Cst(builder, 0.03668965196652099192f)); 929ea7f211bSAhmed Taei Value cstCephesExpP5 = bcast(f32Cst(builder, 0.01314350012789660196f)); 930ea7f211bSAhmed Taei 93162fea88bSJacques Pienaar Value x = op.getOperand(); 932ea7f211bSAhmed Taei 933ea7f211bSAhmed Taei // Reduced y = x - floor(x / ln(2)) * ln(2) = x - k * ln(2) 934c0891706SEmilio Cota Value xL2Inv = mul(x, cstLog2E); 935ea7f211bSAhmed Taei Value kF32 = floor(xL2Inv); 936ea7f211bSAhmed Taei Value kLn2 = mul(kF32, cstLn2); 937ea7f211bSAhmed Taei Value y = sub(x, kLn2); 938ea7f211bSAhmed Taei 939ea7f211bSAhmed Taei // Use Estrin's evaluation scheme with 3 independent parts: 940ea7f211bSAhmed Taei // P(y)^y : (c0 + c1 y) + (c2 + c3 y) y^2 + (c4 + c5 y) y^4 941ea7f211bSAhmed Taei Value y2 = mul(y, y); 942ea7f211bSAhmed Taei Value y4 = mul(y2, y2); 943ea7f211bSAhmed Taei 944ea7f211bSAhmed Taei Value q0 = fmla(cstCephesExpP1, y, cstCephesExpP0); 945ea7f211bSAhmed Taei Value q1 = fmla(cstCephesExpP3, y, cstCephesExpP2); 946ea7f211bSAhmed Taei Value q2 = fmla(cstCephesExpP5, y, cstCephesExpP4); 947ea7f211bSAhmed Taei Value expY = fmla(q1, y2, q0); 948ea7f211bSAhmed Taei expY = fmla(q2, y4, expY); 949ea7f211bSAhmed Taei 950ec32d540SEugene Zhulenev auto i32Vec = broadcast(builder.getI32Type(), shape); 951ea7f211bSAhmed Taei 952ea7f211bSAhmed Taei // exp2(k) 9533c69bc4dSRiver Riddle Value k = builder.create<arith::FPToSIOp>(i32Vec, kF32); 954ea7f211bSAhmed Taei Value exp2KValue = exp2I32(builder, k); 955ea7f211bSAhmed Taei 956ea7f211bSAhmed Taei // exp(x) = exp(y) * exp2(k) 957ea7f211bSAhmed Taei expY = mul(expY, exp2KValue); 958ea7f211bSAhmed Taei 959ea7f211bSAhmed Taei // Handle overflow, inf and underflow of exp(x). exp(x) range is [0, inf], its 960ea7f211bSAhmed Taei // partitioned as the following: 961ea7f211bSAhmed Taei // exp(x) = 0, x <= -inf 962ea7f211bSAhmed Taei // exp(x) = underflow (min_float), x <= -88 963ea7f211bSAhmed Taei // exp(x) = inf (min_float), x >= 88 964ea7f211bSAhmed Taei // Note: |k| = 127 is the value where the 8-bits exponent saturates. 965ea7f211bSAhmed Taei Value zerof32Const = bcast(f32Cst(builder, 0)); 966ea7f211bSAhmed Taei auto constPosInfinity = 967ea7f211bSAhmed Taei bcast(f32Cst(builder, std::numeric_limits<float>::infinity())); 968ea7f211bSAhmed Taei auto constNegIfinity = 969ea7f211bSAhmed Taei bcast(f32Cst(builder, -std::numeric_limits<float>::infinity())); 970ea7f211bSAhmed Taei auto underflow = bcast(f32Cst(builder, std::numeric_limits<float>::min())); 971ea7f211bSAhmed Taei 972ea7f211bSAhmed Taei Value kMaxConst = bcast(i32Cst(builder, 127)); 973ea7f211bSAhmed Taei Value kMaxNegConst = bcast(i32Cst(builder, -127)); 974a54f4eaeSMogball Value rightBound = 975a54f4eaeSMogball builder.create<arith::CmpIOp>(arith::CmpIPredicate::sle, k, kMaxConst); 976a54f4eaeSMogball Value leftBound = 977a54f4eaeSMogball builder.create<arith::CmpIOp>(arith::CmpIPredicate::sge, k, kMaxNegConst); 978ea7f211bSAhmed Taei 979a54f4eaeSMogball Value isNegInfinityX = builder.create<arith::CmpFOp>( 980a54f4eaeSMogball arith::CmpFPredicate::OEQ, x, constNegIfinity); 98121f9e4a1SAhmed Taei Value isPosInfinityX = builder.create<arith::CmpFOp>( 98221f9e4a1SAhmed Taei arith::CmpFPredicate::OEQ, x, constPosInfinity); 983ea7f211bSAhmed Taei Value isPostiveX = 984a54f4eaeSMogball builder.create<arith::CmpFOp>(arith::CmpFPredicate::OGT, x, zerof32Const); 985a54f4eaeSMogball Value isComputable = builder.create<arith::AndIOp>(rightBound, leftBound); 986ea7f211bSAhmed Taei 987dec8af70SRiver Riddle expY = builder.create<arith::SelectOp>( 98821f9e4a1SAhmed Taei isNegInfinityX, zerof32Const, 989dec8af70SRiver Riddle builder.create<arith::SelectOp>( 99021f9e4a1SAhmed Taei isPosInfinityX, constPosInfinity, 991dec8af70SRiver Riddle builder.create<arith::SelectOp>( 992dec8af70SRiver Riddle isComputable, expY, 993dec8af70SRiver Riddle builder.create<arith::SelectOp>(isPostiveX, constPosInfinity, 99421f9e4a1SAhmed Taei underflow)))); 995ea7f211bSAhmed Taei 996ea7f211bSAhmed Taei rewriter.replaceOp(op, expY); 997ea7f211bSAhmed Taei 998ea7f211bSAhmed Taei return success(); 999ea7f211bSAhmed Taei } 1000ea7f211bSAhmed Taei 1001ea7f211bSAhmed Taei //----------------------------------------------------------------------------// 10020edc4bc8SEmilio Cota // ExpM1 approximation. 10030edc4bc8SEmilio Cota //----------------------------------------------------------------------------// 10040edc4bc8SEmilio Cota 10050edc4bc8SEmilio Cota namespace { 10060edc4bc8SEmilio Cota 10070edc4bc8SEmilio Cota struct ExpM1Approximation : public OpRewritePattern<math::ExpM1Op> { 10080edc4bc8SEmilio Cota public: 10090edc4bc8SEmilio Cota using OpRewritePattern::OpRewritePattern; 10100edc4bc8SEmilio Cota 10110edc4bc8SEmilio Cota LogicalResult matchAndRewrite(math::ExpM1Op op, 10120edc4bc8SEmilio Cota PatternRewriter &rewriter) const final; 10130edc4bc8SEmilio Cota }; 10140edc4bc8SEmilio Cota } // namespace 10150edc4bc8SEmilio Cota 10160edc4bc8SEmilio Cota LogicalResult 10170edc4bc8SEmilio Cota ExpM1Approximation::matchAndRewrite(math::ExpM1Op op, 10180edc4bc8SEmilio Cota PatternRewriter &rewriter) const { 101962fea88bSJacques Pienaar if (!getElementTypeOrSelf(op.getOperand()).isF32()) 10200edc4bc8SEmilio Cota return rewriter.notifyMatchFailure(op, "unsupported operand type"); 10210edc4bc8SEmilio Cota 102262fea88bSJacques Pienaar ArrayRef<int64_t> shape = vectorShape(op.getOperand()); 1023ec32d540SEugene Zhulenev 10240edc4bc8SEmilio Cota ImplicitLocOpBuilder builder(op->getLoc(), rewriter); 10250edc4bc8SEmilio Cota auto bcast = [&](Value value) -> Value { 1026ec32d540SEugene Zhulenev return broadcast(builder, value, shape); 10270edc4bc8SEmilio Cota }; 10280edc4bc8SEmilio Cota 10290edc4bc8SEmilio Cota // expm1(x) = exp(x) - 1 = u - 1. 10300edc4bc8SEmilio Cota // We have to handle it carefully when x is near 0, i.e. u ~= 1, 10310edc4bc8SEmilio Cota // and when the input is ~= -inf, i.e. u - 1 ~= -1. 10320edc4bc8SEmilio Cota Value cstOne = bcast(f32Cst(builder, 1.0f)); 10330edc4bc8SEmilio Cota Value cstNegOne = bcast(f32Cst(builder, -1.0f)); 103462fea88bSJacques Pienaar Value x = op.getOperand(); 10350edc4bc8SEmilio Cota Value u = builder.create<math::ExpOp>(x); 1036a54f4eaeSMogball Value uEqOne = 1037a54f4eaeSMogball builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, u, cstOne); 1038a54f4eaeSMogball Value uMinusOne = builder.create<arith::SubFOp>(u, cstOne); 1039a54f4eaeSMogball Value uMinusOneEqNegOne = builder.create<arith::CmpFOp>( 1040a54f4eaeSMogball arith::CmpFPredicate::OEQ, uMinusOne, cstNegOne); 10410edc4bc8SEmilio Cota // logU = log(u) ~= x 10420edc4bc8SEmilio Cota Value logU = builder.create<math::LogOp>(u); 10430edc4bc8SEmilio Cota 10440edc4bc8SEmilio Cota // Detect exp(x) = +inf; written this way to avoid having to form +inf. 1045a54f4eaeSMogball Value isInf = 1046a54f4eaeSMogball builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, logU, u); 10470edc4bc8SEmilio Cota 10480edc4bc8SEmilio Cota // (u - 1) * (x / ~x) 1049a54f4eaeSMogball Value expm1 = builder.create<arith::MulFOp>( 1050a54f4eaeSMogball uMinusOne, builder.create<arith::DivFOp>(x, logU)); 1051dec8af70SRiver Riddle expm1 = builder.create<arith::SelectOp>(isInf, u, expm1); 1052dec8af70SRiver Riddle Value approximation = builder.create<arith::SelectOp>( 1053dec8af70SRiver Riddle uEqOne, x, 1054dec8af70SRiver Riddle builder.create<arith::SelectOp>(uMinusOneEqNegOne, cstNegOne, expm1)); 10550edc4bc8SEmilio Cota rewriter.replaceOp(op, approximation); 10560edc4bc8SEmilio Cota return success(); 10570edc4bc8SEmilio Cota } 10580edc4bc8SEmilio Cota 10590edc4bc8SEmilio Cota //----------------------------------------------------------------------------// 10607e2d672aSAhmed S. Taei // Sin and Cos approximation. 10617e2d672aSAhmed S. Taei //----------------------------------------------------------------------------// 10627e2d672aSAhmed S. Taei 10637e2d672aSAhmed S. Taei namespace { 10647e2d672aSAhmed S. Taei 10657e2d672aSAhmed S. Taei template <bool isSine, typename OpTy> 10667e2d672aSAhmed S. Taei struct SinAndCosApproximation : public OpRewritePattern<OpTy> { 10677e2d672aSAhmed S. Taei public: 10687e2d672aSAhmed S. Taei using OpRewritePattern<OpTy>::OpRewritePattern; 10697e2d672aSAhmed S. Taei 10707e2d672aSAhmed S. Taei LogicalResult matchAndRewrite(OpTy op, PatternRewriter &rewriter) const final; 10717e2d672aSAhmed S. Taei }; 10727e2d672aSAhmed S. Taei } // namespace 10737e2d672aSAhmed S. Taei 10747e2d672aSAhmed S. Taei #define TWO_OVER_PI \ 10757e2d672aSAhmed S. Taei 0.6366197723675813430755350534900574481378385829618257949906693762L 10767e2d672aSAhmed S. Taei #define PI_OVER_2 \ 10777e2d672aSAhmed S. Taei 1.5707963267948966192313216916397514420985846996875529104874722961L 10787e2d672aSAhmed S. Taei 10797e2d672aSAhmed S. Taei // Approximates sin(x) or cos(x) by finding the best approximation polynomial in 10807e2d672aSAhmed S. Taei // the reduced range [0, pi/2] for both sin(x) and cos(x). Then given y in the 10817e2d672aSAhmed S. Taei // reduced range sin(x) will be computed as sin(y), -sin(y), cos(y) or -cos(y). 10827e2d672aSAhmed S. Taei template <bool isSine, typename OpTy> 10837e2d672aSAhmed S. Taei LogicalResult SinAndCosApproximation<isSine, OpTy>::matchAndRewrite( 10847e2d672aSAhmed S. Taei OpTy op, PatternRewriter &rewriter) const { 10857e2d672aSAhmed S. Taei static_assert( 10867e2d672aSAhmed S. Taei llvm::is_one_of<OpTy, math::SinOp, math::CosOp>::value, 10877e2d672aSAhmed S. Taei "SinAndCosApproximation pattern expects math::SinOp or math::CosOp"); 1088ec32d540SEugene Zhulenev 108962fea88bSJacques Pienaar if (!getElementTypeOrSelf(op.getOperand()).isF32()) 10907e2d672aSAhmed S. Taei return rewriter.notifyMatchFailure(op, "unsupported operand type"); 10917e2d672aSAhmed S. Taei 109262fea88bSJacques Pienaar ArrayRef<int64_t> shape = vectorShape(op.getOperand()); 1093ec32d540SEugene Zhulenev 10947e2d672aSAhmed S. Taei ImplicitLocOpBuilder builder(op->getLoc(), rewriter); 10957e2d672aSAhmed S. Taei auto bcast = [&](Value value) -> Value { 1096ec32d540SEugene Zhulenev return broadcast(builder, value, shape); 10977e2d672aSAhmed S. Taei }; 10987e2d672aSAhmed S. Taei auto mul = [&](Value a, Value b) -> Value { 1099a54f4eaeSMogball return builder.create<arith::MulFOp>(a, b); 11007e2d672aSAhmed S. Taei }; 11017e2d672aSAhmed S. Taei auto sub = [&](Value a, Value b) -> Value { 1102a54f4eaeSMogball return builder.create<arith::SubFOp>(a, b); 11037e2d672aSAhmed S. Taei }; 1104a54f4eaeSMogball auto floor = [&](Value a) { return builder.create<math::FloorOp>(a); }; 11057e2d672aSAhmed S. Taei 1106ec32d540SEugene Zhulenev auto i32Vec = broadcast(builder.getI32Type(), shape); 11077e2d672aSAhmed S. Taei auto fPToSingedInteger = [&](Value a) -> Value { 11083c69bc4dSRiver Riddle return builder.create<arith::FPToSIOp>(i32Vec, a); 11097e2d672aSAhmed S. Taei }; 11107e2d672aSAhmed S. Taei 11117e2d672aSAhmed S. Taei auto modulo4 = [&](Value a) -> Value { 1112a54f4eaeSMogball return builder.create<arith::AndIOp>(a, bcast(i32Cst(builder, 3))); 11137e2d672aSAhmed S. Taei }; 11147e2d672aSAhmed S. Taei 11157e2d672aSAhmed S. Taei auto isEqualTo = [&](Value a, Value b) -> Value { 1116a54f4eaeSMogball return builder.create<arith::CmpIOp>(arith::CmpIPredicate::eq, a, b); 11177e2d672aSAhmed S. Taei }; 11187e2d672aSAhmed S. Taei 11197e2d672aSAhmed S. Taei auto isGreaterThan = [&](Value a, Value b) -> Value { 1120a54f4eaeSMogball return builder.create<arith::CmpIOp>(arith::CmpIPredicate::sgt, a, b); 11217e2d672aSAhmed S. Taei }; 11227e2d672aSAhmed S. Taei 11237e2d672aSAhmed S. Taei auto select = [&](Value cond, Value t, Value f) -> Value { 1124dec8af70SRiver Riddle return builder.create<arith::SelectOp>(cond, t, f); 11257e2d672aSAhmed S. Taei }; 11267e2d672aSAhmed S. Taei 11277e2d672aSAhmed S. Taei auto fmla = [&](Value a, Value b, Value c) { 1128a54f4eaeSMogball return builder.create<math::FmaOp>(a, b, c); 11297e2d672aSAhmed S. Taei }; 11307e2d672aSAhmed S. Taei 1131a54f4eaeSMogball auto bitwiseOr = [&](Value a, Value b) { 1132a54f4eaeSMogball return builder.create<arith::OrIOp>(a, b); 1133a54f4eaeSMogball }; 11347e2d672aSAhmed S. Taei 1135dc3b9365SAlexandre Ganea Value twoOverPi = bcast(f32Cst(builder, (float)TWO_OVER_PI)); 1136dc3b9365SAlexandre Ganea Value piOverTwo = bcast(f32Cst(builder, (float)PI_OVER_2)); 11377e2d672aSAhmed S. Taei 113862fea88bSJacques Pienaar Value x = op.getOperand(); 11397e2d672aSAhmed S. Taei 11407e2d672aSAhmed S. Taei Value k = floor(mul(x, twoOverPi)); 11417e2d672aSAhmed S. Taei 11427e2d672aSAhmed S. Taei Value y = sub(x, mul(k, piOverTwo)); 11437e2d672aSAhmed S. Taei 11447e2d672aSAhmed S. Taei Value cstOne = bcast(f32Cst(builder, 1.0)); 11457e2d672aSAhmed S. Taei Value cstNegativeOne = bcast(f32Cst(builder, -1.0)); 11467e2d672aSAhmed S. Taei 11477e2d672aSAhmed S. Taei Value cstSC2 = bcast(f32Cst(builder, -0.16666667163372039794921875f)); 11487e2d672aSAhmed S. Taei Value cstSC4 = bcast(f32Cst(builder, 8.333347737789154052734375e-3f)); 11497e2d672aSAhmed S. Taei Value cstSC6 = bcast(f32Cst(builder, -1.9842604524455964565277099609375e-4f)); 11507e2d672aSAhmed S. Taei Value cstSC8 = 11517e2d672aSAhmed S. Taei bcast(f32Cst(builder, 2.760012648650445044040679931640625e-6f)); 11527e2d672aSAhmed S. Taei Value cstSC10 = 11537e2d672aSAhmed S. Taei bcast(f32Cst(builder, -2.50293279435709337121807038784027099609375e-8f)); 11547e2d672aSAhmed S. Taei 11557e2d672aSAhmed S. Taei Value cstCC2 = bcast(f32Cst(builder, -0.5f)); 11567e2d672aSAhmed S. Taei Value cstCC4 = bcast(f32Cst(builder, 4.166664183139801025390625e-2f)); 11577e2d672aSAhmed S. Taei Value cstCC6 = bcast(f32Cst(builder, -1.388833043165504932403564453125e-3f)); 11587e2d672aSAhmed S. Taei Value cstCC8 = bcast(f32Cst(builder, 2.47562347794882953166961669921875e-5f)); 11597e2d672aSAhmed S. Taei Value cstCC10 = 11607e2d672aSAhmed S. Taei bcast(f32Cst(builder, -2.59630184018533327616751194000244140625e-7f)); 11617e2d672aSAhmed S. Taei 11627e2d672aSAhmed S. Taei Value kMod4 = modulo4(fPToSingedInteger(k)); 11637e2d672aSAhmed S. Taei 11647e2d672aSAhmed S. Taei Value kR0 = isEqualTo(kMod4, bcast(i32Cst(builder, 0))); 11657e2d672aSAhmed S. Taei Value kR1 = isEqualTo(kMod4, bcast(i32Cst(builder, 1))); 11667e2d672aSAhmed S. Taei Value kR2 = isEqualTo(kMod4, bcast(i32Cst(builder, 2))); 11677e2d672aSAhmed S. Taei Value kR3 = isEqualTo(kMod4, bcast(i32Cst(builder, 3))); 11687e2d672aSAhmed S. Taei 11697e2d672aSAhmed S. Taei Value sinuseCos = isSine ? bitwiseOr(kR1, kR3) : bitwiseOr(kR0, kR2); 11707e2d672aSAhmed S. Taei Value negativeRange = isSine ? isGreaterThan(kMod4, bcast(i32Cst(builder, 1))) 11717e2d672aSAhmed S. Taei : bitwiseOr(kR1, kR2); 11727e2d672aSAhmed S. Taei 11737e2d672aSAhmed S. Taei Value y2 = mul(y, y); 11747e2d672aSAhmed S. Taei 11757e2d672aSAhmed S. Taei Value base = select(sinuseCos, cstOne, y); 11767e2d672aSAhmed S. Taei Value cstC2 = select(sinuseCos, cstCC2, cstSC2); 11777e2d672aSAhmed S. Taei Value cstC4 = select(sinuseCos, cstCC4, cstSC4); 11787e2d672aSAhmed S. Taei Value cstC6 = select(sinuseCos, cstCC6, cstSC6); 11797e2d672aSAhmed S. Taei Value cstC8 = select(sinuseCos, cstCC8, cstSC8); 11807e2d672aSAhmed S. Taei Value cstC10 = select(sinuseCos, cstCC10, cstSC10); 11817e2d672aSAhmed S. Taei 11827e2d672aSAhmed S. Taei Value v1 = fmla(y2, cstC10, cstC8); 11837e2d672aSAhmed S. Taei Value v2 = fmla(y2, v1, cstC6); 11847e2d672aSAhmed S. Taei Value v3 = fmla(y2, v2, cstC4); 11857e2d672aSAhmed S. Taei Value v4 = fmla(y2, v3, cstC2); 11867e2d672aSAhmed S. Taei Value v5 = fmla(y2, v4, cstOne); 11877e2d672aSAhmed S. Taei Value v6 = mul(base, v5); 11887e2d672aSAhmed S. Taei 11897e2d672aSAhmed S. Taei Value approximation = select(negativeRange, mul(cstNegativeOne, v6), v6); 11907e2d672aSAhmed S. Taei 11917e2d672aSAhmed S. Taei rewriter.replaceOp(op, approximation); 11927e2d672aSAhmed S. Taei 11937e2d672aSAhmed S. Taei return success(); 11947e2d672aSAhmed S. Taei } 11957e2d672aSAhmed S. Taei 11967e2d672aSAhmed S. Taei //----------------------------------------------------------------------------// 119735553d45SEmilio Cota // Rsqrt approximation. 119835553d45SEmilio Cota //----------------------------------------------------------------------------// 119935553d45SEmilio Cota 120035553d45SEmilio Cota namespace { 120135553d45SEmilio Cota struct RsqrtApproximation : public OpRewritePattern<math::RsqrtOp> { 120235553d45SEmilio Cota using OpRewritePattern::OpRewritePattern; 120335553d45SEmilio Cota 120435553d45SEmilio Cota LogicalResult matchAndRewrite(math::RsqrtOp op, 120535553d45SEmilio Cota PatternRewriter &rewriter) const final; 120635553d45SEmilio Cota }; 120735553d45SEmilio Cota } // namespace 120835553d45SEmilio Cota 120935553d45SEmilio Cota LogicalResult 121035553d45SEmilio Cota RsqrtApproximation::matchAndRewrite(math::RsqrtOp op, 121135553d45SEmilio Cota PatternRewriter &rewriter) const { 121262fea88bSJacques Pienaar if (!getElementTypeOrSelf(op.getOperand()).isF32()) 1213ec32d540SEugene Zhulenev return rewriter.notifyMatchFailure(op, "unsupported operand type"); 1214ec32d540SEugene Zhulenev 121562fea88bSJacques Pienaar ArrayRef<int64_t> shape = vectorShape(op.getOperand()); 1216ec32d540SEugene Zhulenev 121735553d45SEmilio Cota // Only support already-vectorized rsqrt's. 1218ec32d540SEugene Zhulenev if (shape.empty() || shape.back() % 8 != 0) 121935553d45SEmilio Cota return rewriter.notifyMatchFailure(op, "unsupported operand type"); 122035553d45SEmilio Cota 122135553d45SEmilio Cota ImplicitLocOpBuilder builder(op->getLoc(), rewriter); 122235553d45SEmilio Cota auto bcast = [&](Value value) -> Value { 1223ec32d540SEugene Zhulenev return broadcast(builder, value, shape); 122435553d45SEmilio Cota }; 122535553d45SEmilio Cota 122635553d45SEmilio Cota Value cstPosInf = bcast(f32FromBits(builder, 0x7f800000u)); 122735553d45SEmilio Cota Value cstOnePointFive = bcast(f32Cst(builder, 1.5f)); 122835553d45SEmilio Cota Value cstNegHalf = bcast(f32Cst(builder, -0.5f)); 122935553d45SEmilio Cota Value cstMinNormPos = bcast(f32FromBits(builder, 0x00800000u)); 123035553d45SEmilio Cota 123162fea88bSJacques Pienaar Value negHalf = builder.create<arith::MulFOp>(op.getOperand(), cstNegHalf); 123235553d45SEmilio Cota 123335553d45SEmilio Cota // Select only the inverse sqrt of positive normals (denormals are 123435553d45SEmilio Cota // flushed to zero). 123562fea88bSJacques Pienaar Value ltMinMask = builder.create<arith::CmpFOp>( 123662fea88bSJacques Pienaar arith::CmpFPredicate::OLT, op.getOperand(), cstMinNormPos); 123735553d45SEmilio Cota Value infMask = builder.create<arith::CmpFOp>(arith::CmpFPredicate::OEQ, 123862fea88bSJacques Pienaar op.getOperand(), cstPosInf); 123935553d45SEmilio Cota Value notNormalFiniteMask = builder.create<arith::OrIOp>(ltMinMask, infMask); 124035553d45SEmilio Cota 124135553d45SEmilio Cota // Compute an approximate result. 1242627fa0b9SEugene Zhulenev Value yApprox = handleMultidimensionalVectors( 1243627fa0b9SEugene Zhulenev builder, op->getOperands(), 8, [&builder](ValueRange operands) -> Value { 1244627fa0b9SEugene Zhulenev return builder.create<x86vector::RsqrtOp>(operands); 1245627fa0b9SEugene Zhulenev }); 124635553d45SEmilio Cota 124735553d45SEmilio Cota // Do a single step of Newton-Raphson iteration to improve the approximation. 124835553d45SEmilio Cota // This uses the formula y_{n+1} = y_n * (1.5 - y_n * (0.5 * x) * y_n). 124935553d45SEmilio Cota // It is essential to evaluate the inner term like this because forming 125035553d45SEmilio Cota // y_n^2 may over- or underflow. 125135553d45SEmilio Cota Value inner = builder.create<arith::MulFOp>(negHalf, yApprox); 125235553d45SEmilio Cota Value fma = builder.create<math::FmaOp>(yApprox, inner, cstOnePointFive); 125335553d45SEmilio Cota Value yNewton = builder.create<arith::MulFOp>(yApprox, fma); 125435553d45SEmilio Cota 125535553d45SEmilio Cota // Select the result of the Newton-Raphson step for positive normal arguments. 125635553d45SEmilio Cota // For other arguments, choose the output of the intrinsic. This will 125735553d45SEmilio Cota // return rsqrt(+inf) = 0, rsqrt(x) = NaN if x < 0, and rsqrt(x) = +inf if 125835553d45SEmilio Cota // x is zero or a positive denormalized float (equivalent to flushing positive 125935553d45SEmilio Cota // denormalized inputs to zero). 1260dec8af70SRiver Riddle Value res = 1261dec8af70SRiver Riddle builder.create<arith::SelectOp>(notNormalFiniteMask, yApprox, yNewton); 126235553d45SEmilio Cota rewriter.replaceOp(op, res); 126335553d45SEmilio Cota 126435553d45SEmilio Cota return success(); 126535553d45SEmilio Cota } 126635553d45SEmilio Cota 126735553d45SEmilio Cota //----------------------------------------------------------------------------// 1268f99ccf65SEugene Zhulenev 1269f99ccf65SEugene Zhulenev void mlir::populateMathPolynomialApproximationPatterns( 127035553d45SEmilio Cota RewritePatternSet &patterns, 127135553d45SEmilio Cota const MathPolynomialApproximationOptions &options) { 12722f9f9afaSRob Suderman patterns.add<AtanApproximation, Atan2Approximation, TanhApproximation, 12732f9f9afaSRob Suderman LogApproximation, Log2Approximation, Log1pApproximation, 12742f9f9afaSRob Suderman ErfPolynomialApproximation, ExpApproximation, ExpM1Approximation, 1275*bbddd19eSJacques Pienaar ReuseF32Expansion<math::Atan2Op>, 12762f9f9afaSRob Suderman SinAndCosApproximation<true, math::SinOp>, 12777e2d672aSAhmed S. Taei SinAndCosApproximation<false, math::CosOp>>( 12780edc4bc8SEmilio Cota patterns.getContext()); 127935553d45SEmilio Cota if (options.enableAvx2) 128035553d45SEmilio Cota patterns.add<RsqrtApproximation>(patterns.getContext()); 1281f99ccf65SEugene Zhulenev } 1282