1 //===- PolynomialApproximation.cpp - Approximate math operations ----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements expansion of math operations to fast approximations
10 // that do not rely on any of the library functions.
11 //
12 //===----------------------------------------------------------------------===//
13 #include "mlir/Dialect/LLVMIR/LLVMDialect.h"
14 #include "mlir/Dialect/LLVMIR/LLVMTypes.h"
15 #include "mlir/Dialect/Math/IR/Math.h"
16 #include "mlir/Dialect/Math/Transforms/Passes.h"
17 #include "mlir/Dialect/Vector/VectorOps.h"
18 #include "mlir/IR/Builders.h"
19 #include "mlir/IR/ImplicitLocOpBuilder.h"
20 #include "mlir/Transforms/DialectConversion.h"
21 #include "mlir/Transforms/GreedyPatternRewriteDriver.h"
22 #include <limits.h>
23 
24 using namespace mlir;
25 using namespace mlir::vector;
26 
27 using TypePredicate = llvm::function_ref<bool(Type)>;
28 
29 static bool isF32(Type type) { return type.isF32(); }
30 
31 static bool isI32(Type type) { return type.isInteger(32); }
32 
33 // Returns vector width if the element type is matching the predicate (scalars
34 // that do match the predicate have width equal to `1`).
35 static Optional<int> vectorWidth(Type type, TypePredicate pred) {
36   // If the type matches the predicate then its width is `1`.
37   if (pred(type))
38     return 1;
39 
40   // Otherwise check if the type is a vector type.
41   auto vectorType = type.dyn_cast<VectorType>();
42   if (vectorType && pred(vectorType.getElementType())) {
43     assert(vectorType.getRank() == 1 && "only 1d vectors are supported");
44     return vectorType.getDimSize(0);
45   }
46 
47   return llvm::None;
48 }
49 
50 // Returns vector width of the type. If the type is a scalar returns `1`.
51 static int vectorWidth(Type type) {
52   auto vectorType = type.dyn_cast<VectorType>();
53   return vectorType ? vectorType.getDimSize(0) : 1;
54 }
55 
56 // Returns vector element type. If the type is a scalar returns the argument.
57 static Type elementType(Type type) {
58   auto vectorType = type.dyn_cast<VectorType>();
59   return vectorType ? vectorType.getElementType() : type;
60 }
61 
62 //----------------------------------------------------------------------------//
63 // Broadcast scalar types and values into vector types and values.
64 //----------------------------------------------------------------------------//
65 
66 // Broadcasts scalar type into vector type (iff width is greater then 1).
67 static Type broadcast(Type type, int width) {
68   assert(!type.isa<VectorType>() && "must be scalar type");
69   return width > 1 ? VectorType::get({width}, type) : type;
70 }
71 
72 // Broadcasts scalar value into vector (iff width is greater then 1).
73 static Value broadcast(ImplicitLocOpBuilder &builder, Value value, int width) {
74   assert(!value.getType().isa<VectorType>() && "must be scalar value");
75   auto type = broadcast(value.getType(), width);
76   return width > 1 ? builder.create<BroadcastOp>(type, value) : value;
77 }
78 
79 //----------------------------------------------------------------------------//
80 // Helper functions to create constants.
81 //----------------------------------------------------------------------------//
82 
83 static Value f32Cst(ImplicitLocOpBuilder &builder, float value) {
84   return builder.create<ConstantOp>(builder.getF32Type(),
85                                     builder.getF32FloatAttr(value));
86 }
87 
88 static Value i32Cst(ImplicitLocOpBuilder &builder, int32_t value) {
89   return builder.create<ConstantOp>(builder.getI32Type(),
90                                     builder.getI32IntegerAttr(value));
91 }
92 
93 static Value f32FromBits(ImplicitLocOpBuilder &builder, uint32_t bits) {
94   Value i32Value = i32Cst(builder, static_cast<int32_t>(bits));
95   return builder.create<LLVM::BitcastOp>(builder.getF32Type(), i32Value);
96 }
97 
98 //----------------------------------------------------------------------------//
99 // Helper functions to build math functions approximations.
100 //----------------------------------------------------------------------------//
101 
102 static Value min(ImplicitLocOpBuilder &builder, Value a, Value b) {
103   return builder.create<SelectOp>(
104       builder.create<CmpFOp>(CmpFPredicate::OLT, a, b), a, b);
105 }
106 
107 static Value max(ImplicitLocOpBuilder &builder, Value a, Value b) {
108   return builder.create<SelectOp>(
109       builder.create<CmpFOp>(CmpFPredicate::OGT, a, b), a, b);
110 }
111 
112 static Value clamp(ImplicitLocOpBuilder &builder, Value value, Value lowerBound,
113                    Value upperBound) {
114   return max(builder, min(builder, value, upperBound), lowerBound);
115 }
116 
117 // Decomposes given floating point value `arg` into a normalized fraction and
118 // an integral power of two (see std::frexp). Returned values have float type.
119 static std::pair<Value, Value> frexp(ImplicitLocOpBuilder &builder, Value arg,
120                                      bool is_positive = false) {
121   assert(isF32(elementType(arg.getType())) && "argument must be f32 type");
122 
123   int width = vectorWidth(arg.getType());
124 
125   auto bcast = [&](Value value) -> Value {
126     return broadcast(builder, value, width);
127   };
128 
129   auto i32 = builder.getIntegerType(32);
130   auto i32Vec = broadcast(i32, width);
131   auto f32Vec = broadcast(builder.getF32Type(), width);
132 
133   Value cst126f = f32Cst(builder, 126.0f);
134   Value cstHalf = f32Cst(builder, 0.5f);
135   Value cstInvMantMask = f32FromBits(builder, ~0x7f800000u);
136 
137   // Bitcast to i32 for bitwise operations.
138   Value i32Half = builder.create<LLVM::BitcastOp>(i32, cstHalf);
139   Value i32InvMantMask = builder.create<LLVM::BitcastOp>(i32, cstInvMantMask);
140   Value i32Arg = builder.create<LLVM::BitcastOp>(i32Vec, arg);
141 
142   // Compute normalized fraction.
143   Value tmp0 = builder.create<LLVM::AndOp>(i32Arg, bcast(i32InvMantMask));
144   Value tmp1 = builder.create<LLVM::OrOp>(tmp0, bcast(i32Half));
145   Value normalizedFraction = builder.create<LLVM::BitcastOp>(f32Vec, tmp1);
146 
147   // Compute exponent.
148   Value arg0 = is_positive ? arg : builder.create<AbsFOp>(arg);
149   Value biasedExponentBits = builder.create<UnsignedShiftRightOp>(
150       builder.create<LLVM::BitcastOp>(i32Vec, arg0),
151       bcast(i32Cst(builder, 23)));
152   Value biasedExponent = builder.create<SIToFPOp>(f32Vec, biasedExponentBits);
153   Value exponent = builder.create<SubFOp>(biasedExponent, bcast(cst126f));
154 
155   return {normalizedFraction, exponent};
156 }
157 
158 // Computes exp2 for an i32 argument.
159 static Value exp2I32(ImplicitLocOpBuilder &builder, Value arg) {
160   assert(isI32(elementType(arg.getType())) && "argument must be i32 type");
161 
162   int width = vectorWidth(arg.getType());
163 
164   auto bcast = [&](Value value) -> Value {
165     return broadcast(builder, value, width);
166   };
167 
168   auto f32Vec = broadcast(builder.getF32Type(), width);
169   // The exponent of f32 located at 23-bit.
170   auto exponetBitLocation = bcast(i32Cst(builder, 23));
171   // Set the exponent bias to zero.
172   auto bias = bcast(i32Cst(builder, 127));
173 
174   Value biasedArg = builder.create<AddIOp>(arg, bias);
175   Value exp2ValueInt =
176       builder.create<ShiftLeftOp>(biasedArg, exponetBitLocation);
177   Value exp2ValueF32 = builder.create<LLVM::BitcastOp>(f32Vec, exp2ValueInt);
178 
179   return exp2ValueF32;
180 }
181 
182 //----------------------------------------------------------------------------//
183 // TanhOp approximation.
184 //----------------------------------------------------------------------------//
185 
186 namespace {
187 struct TanhApproximation : public OpRewritePattern<math::TanhOp> {
188 public:
189   using OpRewritePattern::OpRewritePattern;
190 
191   LogicalResult matchAndRewrite(math::TanhOp op,
192                                 PatternRewriter &rewriter) const final;
193 };
194 } // namespace
195 
196 LogicalResult
197 TanhApproximation::matchAndRewrite(math::TanhOp op,
198                                    PatternRewriter &rewriter) const {
199   auto width = vectorWidth(op.operand().getType(), isF32);
200   if (!width.hasValue())
201     return rewriter.notifyMatchFailure(op, "unsupported operand type");
202 
203   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
204   auto bcast = [&](Value value) -> Value {
205     return broadcast(builder, value, *width);
206   };
207 
208   // Clamp operand into [plusClamp, minusClamp] range.
209   Value minusClamp = bcast(f32Cst(builder, -7.9053111076354980f));
210   Value plusClamp = bcast(f32Cst(builder, 7.90531110763549805f));
211   Value x = clamp(builder, op.operand(), minusClamp, plusClamp);
212 
213   // Mask for tiny values that are approximated with `operand`.
214   Value tiny = bcast(f32Cst(builder, 0.0004f));
215   Value tinyMask = builder.create<CmpFOp>(
216       CmpFPredicate::OLT, builder.create<AbsFOp>(op.operand()), tiny);
217 
218   // The monomial coefficients of the numerator polynomial (odd).
219   Value alpha1 = bcast(f32Cst(builder, 4.89352455891786e-03f));
220   Value alpha3 = bcast(f32Cst(builder, 6.37261928875436e-04f));
221   Value alpha5 = bcast(f32Cst(builder, 1.48572235717979e-05f));
222   Value alpha7 = bcast(f32Cst(builder, 5.12229709037114e-08f));
223   Value alpha9 = bcast(f32Cst(builder, -8.60467152213735e-11f));
224   Value alpha11 = bcast(f32Cst(builder, 2.00018790482477e-13f));
225   Value alpha13 = bcast(f32Cst(builder, -2.76076847742355e-16f));
226 
227   // The monomial coefficients of the denominator polynomial (even).
228   Value beta0 = bcast(f32Cst(builder, 4.89352518554385e-03f));
229   Value beta2 = bcast(f32Cst(builder, 2.26843463243900e-03f));
230   Value beta4 = bcast(f32Cst(builder, 1.18534705686654e-04f));
231   Value beta6 = bcast(f32Cst(builder, 1.19825839466702e-06f));
232 
233   // Since the polynomials are odd/even, we need x^2.
234   Value x2 = builder.create<MulFOp>(x, x);
235 
236   // Evaluate the numerator polynomial p.
237   Value p = builder.create<FmaFOp>(x2, alpha13, alpha11);
238   p = builder.create<FmaFOp>(x2, p, alpha9);
239   p = builder.create<FmaFOp>(x2, p, alpha7);
240   p = builder.create<FmaFOp>(x2, p, alpha5);
241   p = builder.create<FmaFOp>(x2, p, alpha3);
242   p = builder.create<FmaFOp>(x2, p, alpha1);
243   p = builder.create<MulFOp>(x, p);
244 
245   // Evaluate the denominator polynomial q.
246   Value q = builder.create<FmaFOp>(x2, beta6, beta4);
247   q = builder.create<FmaFOp>(x2, q, beta2);
248   q = builder.create<FmaFOp>(x2, q, beta0);
249 
250   // Divide the numerator by the denominator.
251   Value res =
252       builder.create<SelectOp>(tinyMask, x, builder.create<DivFOp>(p, q));
253 
254   rewriter.replaceOp(op, res);
255 
256   return success();
257 }
258 
259 #define LN2_VALUE                                                              \
260   0.693147180559945309417232121458176568075500134360255254120680009493393621L
261 #define LN2E_VALUE                                                             \
262   1.442695040888963407359924681001892137426645954152985934135449406931109219L
263 
264 //----------------------------------------------------------------------------//
265 // LogOp approximation.
266 //----------------------------------------------------------------------------//
267 
268 namespace {
269 
270 // This approximations comes from the Julien Pommier's SSE math library.
271 // Link: http://gruntthepeon.free.fr/ssemath
272 struct LogApproximation : public OpRewritePattern<math::LogOp> {
273 public:
274   using OpRewritePattern::OpRewritePattern;
275 
276   LogicalResult matchAndRewrite(math::LogOp op,
277                                 PatternRewriter &rewriter) const final;
278 };
279 } // namespace
280 
281 LogicalResult
282 LogApproximation::matchAndRewrite(math::LogOp op,
283                                   PatternRewriter &rewriter) const {
284   auto width = vectorWidth(op.operand().getType(), isF32);
285   if (!width.hasValue())
286     return rewriter.notifyMatchFailure(op, "unsupported operand type");
287 
288   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
289   auto bcast = [&](Value value) -> Value {
290     return broadcast(builder, value, *width);
291   };
292 
293   Value cstZero = bcast(f32Cst(builder, 0.0f));
294   Value cstOne = bcast(f32Cst(builder, 1.0f));
295   Value cstNegHalf = bcast(f32Cst(builder, -0.5f));
296 
297   // The smallest non denormalized float number.
298   Value cstMinNormPos = bcast(f32FromBits(builder, 0x00800000u));
299   Value cstMinusInf = bcast(f32FromBits(builder, 0xff800000u));
300   Value cstPosInf = bcast(f32FromBits(builder, 0x7f800000u));
301   Value cstNan = bcast(f32FromBits(builder, 0x7fc00000));
302 
303   // Polynomial coefficients.
304   Value cstCephesSQRTHF = bcast(f32Cst(builder, 0.707106781186547524f));
305   Value cstCephesLogP0 = bcast(f32Cst(builder, 7.0376836292E-2f));
306   Value cstCephesLogP1 = bcast(f32Cst(builder, -1.1514610310E-1f));
307   Value cstCephesLogP2 = bcast(f32Cst(builder, 1.1676998740E-1f));
308   Value cstCephesLogP3 = bcast(f32Cst(builder, -1.2420140846E-1f));
309   Value cstCephesLogP4 = bcast(f32Cst(builder, +1.4249322787E-1f));
310   Value cstCephesLogP5 = bcast(f32Cst(builder, -1.6668057665E-1f));
311   Value cstCephesLogP6 = bcast(f32Cst(builder, +2.0000714765E-1f));
312   Value cstCephesLogP7 = bcast(f32Cst(builder, -2.4999993993E-1f));
313   Value cstCephesLogP8 = bcast(f32Cst(builder, +3.3333331174E-1f));
314 
315   Value x = op.operand();
316 
317   // Truncate input values to the minimum positive normal.
318   x = max(builder, x, cstMinNormPos);
319 
320   // Extract significant in the range [0.5,1) and exponent.
321   std::pair<Value, Value> pair = frexp(builder, x, /*is_positive=*/true);
322   x = pair.first;
323   Value e = pair.second;
324 
325   // Shift the inputs from the range [0.5,1) to [sqrt(1/2), sqrt(2)) and shift
326   // by -1.0. The values are then centered around 0, which improves the
327   // stability of the polynomial evaluation:
328   //
329   //   if( x < SQRTHF ) {
330   //     e -= 1;
331   //     x = x + x - 1.0;
332   //   } else { x = x - 1.0; }
333   Value mask = builder.create<CmpFOp>(CmpFPredicate::OLT, x, cstCephesSQRTHF);
334   Value tmp = builder.create<SelectOp>(mask, x, cstZero);
335 
336   x = builder.create<SubFOp>(x, cstOne);
337   e = builder.create<SubFOp>(e,
338                              builder.create<SelectOp>(mask, cstOne, cstZero));
339   x = builder.create<AddFOp>(x, tmp);
340 
341   Value x2 = builder.create<MulFOp>(x, x);
342   Value x3 = builder.create<MulFOp>(x2, x);
343 
344   // Evaluate the polynomial approximant of degree 8 in three parts.
345   Value y0, y1, y2;
346   y0 = builder.create<FmaFOp>(cstCephesLogP0, x, cstCephesLogP1);
347   y1 = builder.create<FmaFOp>(cstCephesLogP3, x, cstCephesLogP4);
348   y2 = builder.create<FmaFOp>(cstCephesLogP6, x, cstCephesLogP7);
349   y0 = builder.create<FmaFOp>(y0, x, cstCephesLogP2);
350   y1 = builder.create<FmaFOp>(y1, x, cstCephesLogP5);
351   y2 = builder.create<FmaFOp>(y2, x, cstCephesLogP8);
352   y0 = builder.create<FmaFOp>(y0, x3, y1);
353   y0 = builder.create<FmaFOp>(y0, x3, y2);
354   y0 = builder.create<MulFOp>(y0, x3);
355 
356   y0 = builder.create<FmaFOp>(cstNegHalf, x2, y0);
357   x = builder.create<AddFOp>(x, y0);
358 
359   Value cstLn2 = bcast(f32Cst(builder, static_cast<float>(LN2_VALUE)));
360   x = builder.create<FmaFOp>(e, cstLn2, x);
361 
362   Value invalidMask =
363       builder.create<CmpFOp>(CmpFPredicate::ULT, op.operand(), cstZero);
364   Value zeroMask =
365       builder.create<CmpFOp>(CmpFPredicate::OEQ, op.operand(), cstZero);
366   Value posInfMask =
367       builder.create<CmpFOp>(CmpFPredicate::OEQ, op.operand(), cstPosInf);
368 
369   // Filter out invalid values:
370   //  • x == 0     -> -INF
371   //  • x < 0      ->  NAN
372   //  • x == +INF  -> +INF
373   Value aproximation = builder.create<SelectOp>(
374       zeroMask, cstMinusInf,
375       builder.create<SelectOp>(
376           invalidMask, cstNan,
377           builder.create<SelectOp>(posInfMask, cstPosInf, x)));
378 
379   rewriter.replaceOp(op, aproximation);
380 
381   return success();
382 }
383 
384 //----------------------------------------------------------------------------//
385 // Exp approximation.
386 //----------------------------------------------------------------------------//
387 
388 namespace {
389 
390 struct ExpApproximation : public OpRewritePattern<math::ExpOp> {
391 public:
392   using OpRewritePattern::OpRewritePattern;
393 
394   LogicalResult matchAndRewrite(math::ExpOp op,
395                                 PatternRewriter &rewriter) const final;
396 };
397 } // namespace
398 
399 // Approximate exp(x) using its reduced range exp(y) where y is in the range
400 // [0, ln(2)], let y = x - floor(x / ln(2)) * ln(2) = x - k * ln(2), exp(x)
401 // = exp(y) * 2^k. exp(y).
402 LogicalResult
403 ExpApproximation::matchAndRewrite(math::ExpOp op,
404                                   PatternRewriter &rewriter) const {
405   auto width = vectorWidth(op.operand().getType(), isF32);
406   if (!width.hasValue())
407     return rewriter.notifyMatchFailure(op, "unsupported operand type");
408   ImplicitLocOpBuilder builder(op->getLoc(), rewriter);
409 
410   // TODO: Consider a common pattern rewriter with all methods below to
411   // write the approximations.
412   auto bcast = [&](Value value) -> Value {
413     return broadcast(builder, value, *width);
414   };
415   auto fmla = [&](Value a, Value b, Value c) {
416     return builder.create<FmaFOp>(a, b, c);
417   };
418   auto mul = [&](Value a, Value b) -> Value {
419     return builder.create<MulFOp>(a, b);
420   };
421   auto sub = [&](Value a, Value b) -> Value {
422     return builder.create<SubFOp>(a, b);
423   };
424   auto floor = [&](Value a) { return builder.create<FloorFOp>(a); };
425 
426   Value cstLn2 = bcast(f32Cst(builder, static_cast<float>(LN2_VALUE)));
427   Value cstLN2E = bcast(f32Cst(builder, static_cast<float>(LN2E_VALUE)));
428 
429   // Polynomial coefficients.
430   Value cstCephesExpP0 = bcast(f32Cst(builder, 1.0));
431   Value cstCephesExpP1 = bcast(f32Cst(builder, 1.0));
432   Value cstCephesExpP2 = bcast(f32Cst(builder, 0.49970514590562437052f));
433   Value cstCephesExpP3 = bcast(f32Cst(builder, 0.16873890085469545053f));
434   Value cstCephesExpP4 = bcast(f32Cst(builder, 0.03668965196652099192f));
435   Value cstCephesExpP5 = bcast(f32Cst(builder, 0.01314350012789660196f));
436 
437   Value x = op.operand();
438 
439   // Reduced y = x - floor(x / ln(2)) * ln(2) = x - k * ln(2)
440   Value xL2Inv = mul(x, cstLN2E);
441   Value kF32 = floor(xL2Inv);
442   Value kLn2 = mul(kF32, cstLn2);
443   Value y = sub(x, kLn2);
444 
445   // Use Estrin's evaluation scheme with 3 independent parts:
446   // P(y)^y : (c0 + c1 y) + (c2 + c3 y) y^2 + (c4 + c5 y) y^4
447   Value y2 = mul(y, y);
448   Value y4 = mul(y2, y2);
449 
450   Value q0 = fmla(cstCephesExpP1, y, cstCephesExpP0);
451   Value q1 = fmla(cstCephesExpP3, y, cstCephesExpP2);
452   Value q2 = fmla(cstCephesExpP5, y, cstCephesExpP4);
453   Value expY = fmla(q1, y2, q0);
454   expY = fmla(q2, y4, expY);
455 
456   auto i32Vec = broadcast(builder.getI32Type(), *width);
457 
458   // exp2(k)
459   Value k = builder.create<FPToSIOp>(kF32, i32Vec);
460   Value exp2KValue = exp2I32(builder, k);
461 
462   // exp(x) = exp(y) * exp2(k)
463   expY = mul(expY, exp2KValue);
464 
465   // Handle overflow, inf and underflow of exp(x). exp(x) range is [0, inf], its
466   // partitioned as the following:
467   // exp(x) = 0, x <= -inf
468   // exp(x) = underflow (min_float), x <= -88
469   // exp(x) = inf (min_float), x >= 88
470   // Note: |k| = 127 is the value where the 8-bits exponent saturates.
471   Value zerof32Const = bcast(f32Cst(builder, 0));
472   auto constPosInfinity =
473       bcast(f32Cst(builder, std::numeric_limits<float>::infinity()));
474   auto constNegIfinity =
475       bcast(f32Cst(builder, -std::numeric_limits<float>::infinity()));
476   auto underflow = bcast(f32Cst(builder, std::numeric_limits<float>::min()));
477 
478   Value kMaxConst = bcast(i32Cst(builder, 127));
479   Value kMaxNegConst = bcast(i32Cst(builder, -127));
480   Value rightBound = builder.create<CmpIOp>(CmpIPredicate::sle, k, kMaxConst);
481   Value leftBound = builder.create<CmpIOp>(CmpIPredicate::sge, k, kMaxNegConst);
482 
483   Value isNegInfinityX =
484       builder.create<CmpFOp>(CmpFPredicate::OEQ, x, constNegIfinity);
485   Value isPostiveX =
486       builder.create<CmpFOp>(CmpFPredicate::OGT, x, zerof32Const);
487   Value isComputable = builder.create<AndOp>(rightBound, leftBound);
488 
489   expY = builder.create<SelectOp>(
490       isComputable, expY,
491       builder.create<SelectOp>(
492           isPostiveX, constPosInfinity,
493           builder.create<SelectOp>(isNegInfinityX, zerof32Const, underflow)));
494 
495   rewriter.replaceOp(op, expY);
496 
497   return success();
498 }
499 
500 //----------------------------------------------------------------------------//
501 
502 void mlir::populateMathPolynomialApproximationPatterns(
503     OwningRewritePatternList &patterns, MLIRContext *ctx) {
504   patterns.insert<TanhApproximation, LogApproximation, ExpApproximation>(ctx);
505 }
506