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