xref: /freebsd/contrib/arm-optimized-routines/pl/math/sv_expf_inline.h (revision e9ac41698b2f322d55ccf9da50a3596edb2c1800)
1 /*
2  * SVE helper for single-precision routines which calculate exp(x) and do
3  * not need special-case handling
4  *
5  * Copyright (c) 2023, Arm Limited.
6  * SPDX-License-Identifier: MIT OR Apache-2.0 WITH LLVM-exception
7  */
8 
9 #ifndef PL_MATH_SV_EXPF_INLINE_H
10 #define PL_MATH_SV_EXPF_INLINE_H
11 
12 #include "sv_math.h"
13 #include "pl_sig.h"
14 #include "pl_test.h"
15 
16 struct sv_expf_data
17 {
18   float poly[5];
19   float inv_ln2, ln2_hi, ln2_lo, shift;
20 };
21 
22 /* Coefficients copied from the polynomial in AdvSIMD variant, reversed for
23    compatibility with polynomial helpers. Shift is 1.5*2^17 + 127.  */
24 #define SV_EXPF_DATA                                                          \
25   {                                                                           \
26     .poly = { 0x1.ffffecp-1f, 0x1.fffdb6p-2f, 0x1.555e66p-3f, 0x1.573e2ep-5f, \
27 	      0x1.0e4020p-7f },                                               \
28                                                                               \
29     .inv_ln2 = 0x1.715476p+0f, .ln2_hi = 0x1.62e4p-1f,                        \
30     .ln2_lo = 0x1.7f7d1cp-20f, .shift = 0x1.803f8p17f,                        \
31   }
32 
33 #define C(i) sv_f32 (d->poly[i])
34 
35 static inline svfloat32_t
36 expf_inline (svfloat32_t x, const svbool_t pg, const struct sv_expf_data *d)
37 {
38   /* exp(x) = 2^n (1 + poly(r)), with 1 + poly(r) in [1/sqrt(2),sqrt(2)]
39      x = ln2*n + r, with r in [-ln2/2, ln2/2].  */
40 
41   /* Load some constants in quad-word chunks to minimise memory access.  */
42   svfloat32_t c4_invln2_and_ln2 = svld1rq (svptrue_b32 (), &d->poly[4]);
43 
44   /* n = round(x/(ln2/N)).  */
45   svfloat32_t z = svmla_lane (sv_f32 (d->shift), x, c4_invln2_and_ln2, 1);
46   svfloat32_t n = svsub_x (pg, z, d->shift);
47 
48   /* r = x - n*ln2/N.  */
49   svfloat32_t r = svmls_lane (x, n, c4_invln2_and_ln2, 2);
50   r = svmls_lane (r, n, c4_invln2_and_ln2, 3);
51 
52   /* scale = 2^(n/N).  */
53   svfloat32_t scale = svexpa (svreinterpret_u32_f32 (z));
54 
55   /* y = exp(r) - 1 ~= r + C0 r^2 + C1 r^3 + C2 r^4 + C3 r^5 + C4 r^6.  */
56   svfloat32_t p12 = svmla_x (pg, C (1), C (2), r);
57   svfloat32_t p34 = svmla_lane (C (3), r, c4_invln2_and_ln2, 0);
58   svfloat32_t r2 = svmul_f32_x (pg, r, r);
59   svfloat32_t p14 = svmla_x (pg, p12, p34, r2);
60   svfloat32_t p0 = svmul_f32_x (pg, r, C (0));
61   svfloat32_t poly = svmla_x (pg, p0, r2, p14);
62 
63   return svmla_x (pg, scale, scale, poly);
64 }
65 
66 #endif // PL_MATH_SV_EXPF_INLINE_H