1 //===-- Single-precision atan2f function ----------------------------------===//
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 #include "src/math/atan2f.h"
10 #include "inv_trigf_utils.h"
11 #include "src/__support/FPUtil/FPBits.h"
12 #include "src/__support/FPUtil/PolyEval.h"
13 #include "src/__support/FPUtil/double_double.h"
14 #include "src/__support/FPUtil/multiply_add.h"
15 #include "src/__support/FPUtil/nearest_integer.h"
16 #include "src/__support/FPUtil/rounding_mode.h"
17 #include "src/__support/macros/config.h"
18 #include "src/__support/macros/optimization.h" // LIBC_UNLIKELY
19
20 namespace LIBC_NAMESPACE_DECL {
21
22 namespace {
23
24 // Look up tables for accurate pass:
25
26 // atan(i/16) with i = 0..16, generated by Sollya with:
27 // > for i from 0 to 16 do {
28 // a = round(atan(i/16), D, RN);
29 // b = round(atan(i/16) - a, D, RN);
30 // print("{", b, ",", a, "},");
31 // };
32 constexpr fputil::DoubleDouble ATAN_I[17] = {
33 {0.0, 0.0},
34 {-0x1.c934d86d23f1dp-60, 0x1.ff55bb72cfdeap-5},
35 {-0x1.cd37686760c17p-59, 0x1.fd5ba9aac2f6ep-4},
36 {0x1.347b0b4f881cap-58, 0x1.7b97b4bce5b02p-3},
37 {0x1.8ab6e3cf7afbdp-57, 0x1.f5b75f92c80ddp-3},
38 {-0x1.963a544b672d8p-57, 0x1.362773707ebccp-2},
39 {-0x1.c63aae6f6e918p-56, 0x1.6f61941e4def1p-2},
40 {-0x1.24dec1b50b7ffp-56, 0x1.a64eec3cc23fdp-2},
41 {0x1.a2b7f222f65e2p-56, 0x1.dac670561bb4fp-2},
42 {-0x1.d5b495f6349e6p-56, 0x1.0657e94db30dp-1},
43 {-0x1.928df287a668fp-58, 0x1.1e00babdefeb4p-1},
44 {0x1.1021137c71102p-55, 0x1.345f01cce37bbp-1},
45 {0x1.2419a87f2a458p-56, 0x1.4978fa3269ee1p-1},
46 {0x1.0028e4bc5e7cap-57, 0x1.5d58987169b18p-1},
47 {-0x1.8c34d25aadef6p-56, 0x1.700a7c5784634p-1},
48 {-0x1.bf76229d3b917p-56, 0x1.819d0b7158a4dp-1},
49 {0x1.1a62633145c07p-55, 0x1.921fb54442d18p-1},
50 };
51
52 // Taylor polynomial, generated by Sollya with:
53 // > for i from 0 to 8 do {
54 // j = (-1)^(i + 1)/(2*i + 1);
55 // a = round(j, D, RN);
56 // b = round(j - a, D, RN);
57 // print("{", b, ",", a, "},");
58 // };
59 constexpr fputil::DoubleDouble COEFFS[9] = {
60 {0.0, 1.0}, // 1
61 {-0x1.5555555555555p-56, -0x1.5555555555555p-2}, // -1/3
62 {-0x1.999999999999ap-57, 0x1.999999999999ap-3}, // 1/5
63 {-0x1.2492492492492p-57, -0x1.2492492492492p-3}, // -1/7
64 {0x1.c71c71c71c71cp-58, 0x1.c71c71c71c71cp-4}, // 1/9
65 {0x1.745d1745d1746p-59, -0x1.745d1745d1746p-4}, // -1/11
66 {-0x1.3b13b13b13b14p-58, 0x1.3b13b13b13b14p-4}, // 1/13
67 {-0x1.1111111111111p-60, -0x1.1111111111111p-4}, // -1/15
68 {0x1.e1e1e1e1e1e1ep-61, 0x1.e1e1e1e1e1e1ep-5}, // 1/17
69 };
70
71 // Veltkamp's splitting of a double precision into hi + lo, where the hi part is
72 // slightly smaller than an even split, so that the product of
73 // hi * (s1 * k + s2) is exact,
74 // where:
75 // s1, s2 are single precsion,
76 // 1/16 <= s1/s2 <= 1
77 // 1/16 <= k <= 1 is an integer.
78 // So the maximal precision of (s1 * k + s2) is:
79 // prec(s1 * k + s2) = 2 + log2(msb(s2)) - log2(lsb(k_d * s1))
80 // = 2 + log2(msb(s1)) + 4 - log2(lsb(k_d)) - log2(lsb(s1))
81 // = 2 + log2(lsb(s1)) + 23 + 4 - (-4) - log2(lsb(s1))
82 // = 33.
83 // Thus, the Veltkamp splitting constant is C = 2^33 + 1.
84 // This is used when FMA instruction is not available.
split_d(double a)85 [[maybe_unused]] constexpr fputil::DoubleDouble split_d(double a) {
86 fputil::DoubleDouble r{0.0, 0.0};
87 constexpr double C = 0x1.0p33 + 1.0;
88 double t1 = C * a;
89 double t2 = a - t1;
90 r.hi = t1 + t2;
91 r.lo = a - r.hi;
92 return r;
93 }
94
95 // Compute atan( num_d / den_d ) in double-double precision.
96 // num_d = min(|x|, |y|)
97 // den_d = max(|x|, |y|)
98 // q_d = num_d / den_d
99 // idx, k_d = round( 2^4 * num_d / den_d )
100 // final_sign = sign of the final result
101 // const_term = the constant term in the final expression.
atan2f_double_double(double num_d,double den_d,double q_d,int idx,double k_d,double final_sign,const fputil::DoubleDouble & const_term)102 float atan2f_double_double(double num_d, double den_d, double q_d, int idx,
103 double k_d, double final_sign,
104 const fputil::DoubleDouble &const_term) {
105 fputil::DoubleDouble q;
106 double num_r, den_r;
107
108 if (idx != 0) {
109 // The following range reduction is accurate even without fma for
110 // 1/16 <= n/d <= 1.
111 // atan(n/d) - atan(idx/16) = atan((n/d - idx/16) / (1 + (n/d) * (idx/16)))
112 // = atan((n - d*(idx/16)) / (d + n*idx/16))
113 k_d *= 0x1.0p-4;
114 num_r = fputil::multiply_add(k_d, -den_d, num_d); // Exact
115 den_r = fputil::multiply_add(k_d, num_d, den_d); // Exact
116 q.hi = num_r / den_r;
117 } else {
118 // For 0 < n/d < 1/16, we just need to calculate the lower part of their
119 // quotient.
120 q.hi = q_d;
121 num_r = num_d;
122 den_r = den_d;
123 }
124 #ifdef LIBC_TARGET_CPU_HAS_FMA
125 q.lo = fputil::multiply_add(q.hi, -den_r, num_r) / den_r;
126 #else
127 // Compute `(num_r - q.hi * den_r) / den_r` accurately without FMA
128 // instructions.
129 fputil::DoubleDouble q_hi_dd = split_d(q.hi);
130 double t1 = fputil::multiply_add(q_hi_dd.hi, -den_r, num_r); // Exact
131 double t2 = fputil::multiply_add(q_hi_dd.lo, -den_r, t1);
132 q.lo = t2 / den_r;
133 #endif // LIBC_TARGET_CPU_HAS_FMA
134
135 // Taylor polynomial, evaluating using Horner's scheme:
136 // P = x - x^3/3 + x^5/5 -x^7/7 + x^9/9 - x^11/11 + x^13/13 - x^15/15
137 // + x^17/17
138 // = x*(1 + x^2*(-1/3 + x^2*(1/5 + x^2*(-1/7 + x^2*(1/9 + x^2*
139 // *(-1/11 + x^2*(1/13 + x^2*(-1/15 + x^2 * 1/17))))))))
140 fputil::DoubleDouble q2 = fputil::quick_mult(q, q);
141 fputil::DoubleDouble p_dd =
142 fputil::polyeval(q2, COEFFS[0], COEFFS[1], COEFFS[2], COEFFS[3],
143 COEFFS[4], COEFFS[5], COEFFS[6], COEFFS[7], COEFFS[8]);
144 fputil::DoubleDouble r_dd =
145 fputil::add(const_term, fputil::multiply_add(q, p_dd, ATAN_I[idx]));
146 r_dd.hi *= final_sign;
147 r_dd.lo *= final_sign;
148
149 // Make sure the sum is normalized:
150 fputil::DoubleDouble rr = fputil::exact_add(r_dd.hi, r_dd.lo);
151 // Round to odd.
152 uint64_t rr_bits = cpp::bit_cast<uint64_t>(rr.hi);
153 if (LIBC_UNLIKELY(((rr_bits & 0xfff'ffff) == 0) && (rr.lo != 0.0))) {
154 Sign hi_sign = fputil::FPBits<double>(rr.hi).sign();
155 Sign lo_sign = fputil::FPBits<double>(rr.lo).sign();
156 if (hi_sign == lo_sign) {
157 ++rr_bits;
158 } else if ((rr_bits & fputil::FPBits<double>::FRACTION_MASK) > 0) {
159 --rr_bits;
160 }
161 }
162
163 return static_cast<float>(cpp::bit_cast<double>(rr_bits));
164 }
165
166 } // anonymous namespace
167
168 // There are several range reduction steps we can take for atan2(y, x) as
169 // follow:
170
171 // * Range reduction 1: signness
172 // atan2(y, x) will return a number between -PI and PI representing the angle
173 // forming by the 0x axis and the vector (x, y) on the 0xy-plane.
174 // In particular, we have that:
175 // atan2(y, x) = atan( y/x ) if x >= 0 and y >= 0 (I-quadrant)
176 // = pi + atan( y/x ) if x < 0 and y >= 0 (II-quadrant)
177 // = -pi + atan( y/x ) if x < 0 and y < 0 (III-quadrant)
178 // = atan( y/x ) if x >= 0 and y < 0 (IV-quadrant)
179 // Since atan function is odd, we can use the formula:
180 // atan(-u) = -atan(u)
181 // to adjust the above conditions a bit further:
182 // atan2(y, x) = atan( |y|/|x| ) if x >= 0 and y >= 0 (I-quadrant)
183 // = pi - atan( |y|/|x| ) if x < 0 and y >= 0 (II-quadrant)
184 // = -pi + atan( |y|/|x| ) if x < 0 and y < 0 (III-quadrant)
185 // = -atan( |y|/|x| ) if x >= 0 and y < 0 (IV-quadrant)
186 // Which can be simplified to:
187 // atan2(y, x) = sign(y) * atan( |y|/|x| ) if x >= 0
188 // = sign(y) * (pi - atan( |y|/|x| )) if x < 0
189
190 // * Range reduction 2: reciprocal
191 // Now that the argument inside atan is positive, we can use the formula:
192 // atan(1/x) = pi/2 - atan(x)
193 // to make the argument inside atan <= 1 as follow:
194 // atan2(y, x) = sign(y) * atan( |y|/|x|) if 0 <= |y| <= x
195 // = sign(y) * (pi/2 - atan( |x|/|y| ) if 0 <= x < |y|
196 // = sign(y) * (pi - atan( |y|/|x| )) if 0 <= |y| <= -x
197 // = sign(y) * (pi/2 + atan( |x|/|y| )) if 0 <= -x < |y|
198
199 // * Range reduction 3: look up table.
200 // After the previous two range reduction steps, we reduce the problem to
201 // compute atan(u) with 0 <= u <= 1, or to be precise:
202 // atan( n / d ) where n = min(|x|, |y|) and d = max(|x|, |y|).
203 // An accurate polynomial approximation for the whole [0, 1] input range will
204 // require a very large degree. To make it more efficient, we reduce the input
205 // range further by finding an integer idx such that:
206 // | n/d - idx/16 | <= 1/32.
207 // In particular,
208 // idx := 2^-4 * round(2^4 * n/d)
209 // Then for the fast pass, we find a polynomial approximation for:
210 // atan( n/d ) ~ atan( idx/16 ) + (n/d - idx/16) * Q(n/d - idx/16)
211 // For the accurate pass, we use the addition formula:
212 // atan( n/d ) - atan( idx/16 ) = atan( (n/d - idx/16)/(1 + (n*idx)/(16*d)) )
213 // = atan( (n - d * idx/16)/(d + n * idx/16) )
214 // And finally we use Taylor polynomial to compute the RHS in the accurate pass:
215 // atan(u) ~ P(u) = u - u^3/3 + u^5/5 - u^7/7 + u^9/9 - u^11/11 + u^13/13 -
216 // - u^15/15 + u^17/17
217 // It's error in double-double precision is estimated in Sollya to be:
218 // > P = x - x^3/3 + x^5/5 -x^7/7 + x^9/9 - x^11/11 + x^13/13 - x^15/15
219 // + x^17/17;
220 // > dirtyinfnorm(atan(x) - P, [-2^-5, 2^-5]);
221 // 0x1.aec6f...p-100
222 // which is about rounding errors of double-double (2^-104).
223
224 LLVM_LIBC_FUNCTION(float, atan2f, (float y, float x)) {
225 using FPBits = typename fputil::FPBits<float>;
226 constexpr double IS_NEG[2] = {1.0, -1.0};
227 constexpr double PI = 0x1.921fb54442d18p1;
228 constexpr double PI_LO = 0x1.1a62633145c07p-53;
229 constexpr double PI_OVER_4 = 0x1.921fb54442d18p-1;
230 constexpr double PI_OVER_2 = 0x1.921fb54442d18p0;
231 constexpr double THREE_PI_OVER_4 = 0x1.2d97c7f3321d2p+1;
232 // Adjustment for constant term:
233 // CONST_ADJ[x_sign][y_sign][recip]
234 constexpr fputil::DoubleDouble CONST_ADJ[2][2][2] = {
235 {{{0.0, 0.0}, {-PI_LO / 2, -PI_OVER_2}},
236 {{-0.0, -0.0}, {-PI_LO / 2, -PI_OVER_2}}},
237 {{{-PI_LO, -PI}, {PI_LO / 2, PI_OVER_2}},
238 {{-PI_LO, -PI}, {PI_LO / 2, PI_OVER_2}}}};
239
240 FPBits x_bits(x), y_bits(y);
241 bool x_sign = x_bits.sign().is_neg();
242 bool y_sign = y_bits.sign().is_neg();
243 x_bits.set_sign(Sign::POS);
244 y_bits.set_sign(Sign::POS);
245 uint32_t x_abs = x_bits.uintval();
246 uint32_t y_abs = y_bits.uintval();
247 uint32_t max_abs = x_abs > y_abs ? x_abs : y_abs;
248 uint32_t min_abs = x_abs <= y_abs ? x_abs : y_abs;
249 float num_f = FPBits(min_abs).get_val();
250 float den_f = FPBits(max_abs).get_val();
251 double num_d = static_cast<double>(num_f);
252 double den_d = static_cast<double>(den_f);
253
254 if (LIBC_UNLIKELY(max_abs >= 0x7f80'0000U || num_d == 0.0)) {
255 if (x_bits.is_nan() || y_bits.is_nan())
256 return FPBits::quiet_nan().get_val();
257 double x_d = static_cast<double>(x);
258 double y_d = static_cast<double>(y);
259 size_t x_except = (x_d == 0.0) ? 0 : (x_abs == 0x7f80'0000 ? 2 : 1);
260 size_t y_except = (y_d == 0.0) ? 0 : (y_abs == 0x7f80'0000 ? 2 : 1);
261
262 // Exceptional cases:
263 // EXCEPT[y_except][x_except][x_is_neg]
264 // with x_except & y_except:
265 // 0: zero
266 // 1: finite, non-zero
267 // 2: infinity
268 constexpr double EXCEPTS[3][3][2] = {
269 {{0.0, PI}, {0.0, PI}, {0.0, PI}},
270 {{PI_OVER_2, PI_OVER_2}, {0.0, 0.0}, {0.0, PI}},
271 {{PI_OVER_2, PI_OVER_2},
272 {PI_OVER_2, PI_OVER_2},
273 {PI_OVER_4, THREE_PI_OVER_4}},
274 };
275
276 double r = IS_NEG[y_sign] * EXCEPTS[y_except][x_except][x_sign];
277
278 return static_cast<float>(r);
279 }
280
281 bool recip = x_abs < y_abs;
282 double final_sign = IS_NEG[(x_sign != y_sign) != recip];
283 fputil::DoubleDouble const_term = CONST_ADJ[x_sign][y_sign][recip];
284 double q_d = num_d / den_d;
285
286 double k_d = fputil::nearest_integer(q_d * 0x1.0p4f);
287 int idx = static_cast<int>(k_d);
288 q_d = fputil::multiply_add(k_d, -0x1.0p-4, q_d);
289
290 double p = atan_eval(q_d, idx);
291 double r = final_sign *
292 fputil::multiply_add(q_d, p, const_term.hi + ATAN_COEFFS[idx][0]);
293
294 constexpr uint32_t LOWER_ERR = 4;
295 // Mask sticky bits in double precision before rounding to single precision.
296 constexpr uint32_t MASK =
297 mask_trailing_ones<uint32_t, fputil::FPBits<double>::SIG_LEN -
298 FPBits::SIG_LEN - 1>();
299 constexpr uint32_t UPPER_ERR = MASK - LOWER_ERR;
300
301 uint32_t r_bits = static_cast<uint32_t>(cpp::bit_cast<uint64_t>(r)) & MASK;
302
303 // Ziv's rounding test.
304 if (LIBC_LIKELY(r_bits > LOWER_ERR && r_bits < UPPER_ERR))
305 return static_cast<float>(r);
306
307 return atan2f_double_double(num_d, den_d, q_d, idx, k_d, final_sign,
308 const_term);
309 }
310
311 } // namespace LIBC_NAMESPACE_DECL
312