354 lines · c
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-exception6//7//===----------------------------------------------------------------------===//8 9#ifndef LLVM_LIBC_SRC___SUPPORT_MATH_ATAN2F_H10#define LLVM_LIBC_SRC___SUPPORT_MATH_ATAN2F_H11 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_UNLIKELY21#include "src/__support/macros/properties/cpu_features.h" // LIBC_TARGET_CPU_HAS_FMA22 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#else31 32namespace LIBC_NAMESPACE_DECL {33 34namespace math {35 36namespace atan2f_internal {37 38#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS39 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// };48static constexpr fputil::DoubleDouble ATAN_I[17] = {49 {0.0, 0.0},50 {-0x1.c934d86d23f1dp-60, 0x1.ff55bb72cfdeap-5},51 {-0x1.cd37686760c17p-59, 0x1.fd5ba9aac2f6ep-4},52 {0x1.347b0b4f881cap-58, 0x1.7b97b4bce5b02p-3},53 {0x1.8ab6e3cf7afbdp-57, 0x1.f5b75f92c80ddp-3},54 {-0x1.963a544b672d8p-57, 0x1.362773707ebccp-2},55 {-0x1.c63aae6f6e918p-56, 0x1.6f61941e4def1p-2},56 {-0x1.24dec1b50b7ffp-56, 0x1.a64eec3cc23fdp-2},57 {0x1.a2b7f222f65e2p-56, 0x1.dac670561bb4fp-2},58 {-0x1.d5b495f6349e6p-56, 0x1.0657e94db30dp-1},59 {-0x1.928df287a668fp-58, 0x1.1e00babdefeb4p-1},60 {0x1.1021137c71102p-55, 0x1.345f01cce37bbp-1},61 {0x1.2419a87f2a458p-56, 0x1.4978fa3269ee1p-1},62 {0x1.0028e4bc5e7cap-57, 0x1.5d58987169b18p-1},63 {-0x1.8c34d25aadef6p-56, 0x1.700a7c5784634p-1},64 {-0x1.bf76229d3b917p-56, 0x1.819d0b7158a4dp-1},65 {0x1.1a62633145c07p-55, 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// };75static constexpr fputil::DoubleDouble COEFFS[9] = {76 {0.0, 1.0}, // 177 {-0x1.5555555555555p-56, -0x1.5555555555555p-2}, // -1/378 {-0x1.999999999999ap-57, 0x1.999999999999ap-3}, // 1/579 {-0x1.2492492492492p-57, -0x1.2492492492492p-3}, // -1/780 {0x1.c71c71c71c71cp-58, 0x1.c71c71c71c71cp-4}, // 1/981 {0x1.745d1745d1746p-59, -0x1.745d1745d1746p-4}, // -1/1182 {-0x1.3b13b13b13b14p-58, 0x1.3b13b13b13b14p-4}, // 1/1383 {-0x1.1111111111111p-60, -0x1.1111111111111p-4}, // -1/1584 {0x1.e1e1e1e1e1e1ep-61, 0x1.e1e1e1e1e1e1ep-5}, // 1/1785};86 87// Veltkamp's splitting of a double precision into hi + lo, where the hi part is88// slightly smaller than an even split, so that the product of89// hi * (s1 * k + s2) is exact,90// where:91// s1, s2 are single precsion,92// 1/16 <= s1/s2 <= 193// 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 static constexpr fputil::DoubleDouble102split_d(double a) {103 fputil::DoubleDouble r{0.0, 0.0};104 constexpr double C = 0x1.0p33 + 1.0;105 double t1 = C * a;106 double t2 = a - t1;107 r.hi = t1 + t2;108 r.lo = a - r.hi;109 return r;110}111 112// Compute atan( num_d / den_d ) in double-double precision.113// num_d = min(|x|, |y|)114// den_d = max(|x|, |y|)115// q_d = num_d / den_d116// idx, k_d = round( 2^4 * num_d / den_d )117// final_sign = sign of the final result118// const_term = the constant term in the final expression.119LIBC_INLINE static float120atan2f_double_double(double num_d, double den_d, double q_d, int idx,121 double k_d, double final_sign,122 const fputil::DoubleDouble &const_term) {123 fputil::DoubleDouble q;124 double num_r = 0, den_r = 0;125 126 if (idx != 0) {127 // The following range reduction is accurate even without fma for128 // 1/16 <= n/d <= 1.129 // atan(n/d) - atan(idx/16) = atan((n/d - idx/16) / (1 + (n/d) * (idx/16)))130 // = atan((n - d*(idx/16)) / (d + n*idx/16))131 k_d *= 0x1.0p-4;132 num_r = fputil::multiply_add(k_d, -den_d, num_d); // Exact133 den_r = fputil::multiply_add(k_d, num_d, den_d); // Exact134 q.hi = num_r / den_r;135 } else {136 // For 0 < n/d < 1/16, we just need to calculate the lower part of their137 // quotient.138 q.hi = q_d;139 num_r = num_d;140 den_r = den_d;141 }142#ifdef LIBC_TARGET_CPU_HAS_FMA_DOUBLE143 q.lo = fputil::multiply_add(q.hi, -den_r, num_r) / den_r;144#else145 // Compute `(num_r - q.hi * den_r) / den_r` accurately without FMA146 // instructions.147 fputil::DoubleDouble q_hi_dd = split_d(q.hi);148 double t1 = fputil::multiply_add(q_hi_dd.hi, -den_r, num_r); // Exact149 double t2 = fputil::multiply_add(q_hi_dd.lo, -den_r, t1);150 q.lo = t2 / den_r;151#endif // LIBC_TARGET_CPU_HAS_FMA_DOUBLE152 153 // Taylor polynomial, evaluating using Horner's scheme:154 // P = x - x^3/3 + x^5/5 -x^7/7 + x^9/9 - x^11/11 + x^13/13 - x^15/15155 // + x^17/17156 // = x*(1 + x^2*(-1/3 + x^2*(1/5 + x^2*(-1/7 + x^2*(1/9 + x^2*157 // *(-1/11 + x^2*(1/13 + x^2*(-1/15 + x^2 * 1/17))))))))158 fputil::DoubleDouble q2 = fputil::quick_mult(q, q);159 fputil::DoubleDouble p_dd =160 fputil::polyeval(q2, COEFFS[0], COEFFS[1], COEFFS[2], COEFFS[3],161 COEFFS[4], COEFFS[5], COEFFS[6], COEFFS[7], COEFFS[8]);162 fputil::DoubleDouble r_dd =163 fputil::add(const_term, fputil::multiply_add(q, p_dd, ATAN_I[idx]));164 r_dd.hi *= final_sign;165 r_dd.lo *= final_sign;166 167 // Make sure the sum is normalized:168 fputil::DoubleDouble rr = fputil::exact_add(r_dd.hi, r_dd.lo);169 // Round to odd.170 uint64_t rr_bits = cpp::bit_cast<uint64_t>(rr.hi);171 if (LIBC_UNLIKELY(((rr_bits & 0xfff'ffff) == 0) && (rr.lo != 0.0))) {172 Sign hi_sign = fputil::FPBits<double>(rr.hi).sign();173 Sign lo_sign = fputil::FPBits<double>(rr.lo).sign();174 if (hi_sign == lo_sign) {175 ++rr_bits;176 } else if ((rr_bits & fputil::FPBits<double>::FRACTION_MASK) > 0) {177 --rr_bits;178 }179 }180 181 return static_cast<float>(cpp::bit_cast<double>(rr_bits));182}183 184#endif // !LIBC_MATH_HAS_SKIP_ACCURATE_PASS185 186} // namespace atan2f_internal187 188// There are several range reduction steps we can take for atan2(y, x) as189// follow:190 191// * Range reduction 1: signness192// atan2(y, x) will return a number between -PI and PI representing the angle193// forming by the 0x axis and the vector (x, y) on the 0xy-plane.194// In particular, we have that:195// atan2(y, x) = atan( y/x ) if x >= 0 and y >= 0 (I-quadrant)196// = pi + atan( y/x ) if x < 0 and y >= 0 (II-quadrant)197// = -pi + atan( y/x ) if x < 0 and y < 0 (III-quadrant)198// = atan( y/x ) if x >= 0 and y < 0 (IV-quadrant)199// Since atan function is odd, we can use the formula:200// atan(-u) = -atan(u)201// to adjust the above conditions a bit further:202// atan2(y, x) = atan( |y|/|x| ) if x >= 0 and y >= 0 (I-quadrant)203// = pi - atan( |y|/|x| ) if x < 0 and y >= 0 (II-quadrant)204// = -pi + atan( |y|/|x| ) if x < 0 and y < 0 (III-quadrant)205// = -atan( |y|/|x| ) if x >= 0 and y < 0 (IV-quadrant)206// Which can be simplified to:207// atan2(y, x) = sign(y) * atan( |y|/|x| ) if x >= 0208// = sign(y) * (pi - atan( |y|/|x| )) if x < 0209 210// * Range reduction 2: reciprocal211// Now that the argument inside atan is positive, we can use the formula:212// atan(1/x) = pi/2 - atan(x)213// to make the argument inside atan <= 1 as follow:214// atan2(y, x) = sign(y) * atan( |y|/|x|) if 0 <= |y| <= x215// = sign(y) * (pi/2 - atan( |x|/|y| ) if 0 <= x < |y|216// = sign(y) * (pi - atan( |y|/|x| )) if 0 <= |y| <= -x217// = sign(y) * (pi/2 + atan( |x|/|y| )) if 0 <= -x < |y|218 219// * Range reduction 3: look up table.220// After the previous two range reduction steps, we reduce the problem to221// compute atan(u) with 0 <= u <= 1, or to be precise:222// atan( n / d ) where n = min(|x|, |y|) and d = max(|x|, |y|).223// An accurate polynomial approximation for the whole [0, 1] input range will224// require a very large degree. To make it more efficient, we reduce the input225// range further by finding an integer idx such that:226// | n/d - idx/16 | <= 1/32.227// In particular,228// idx := 2^-4 * round(2^4 * n/d)229// Then for the fast pass, we find a polynomial approximation for:230// atan( n/d ) ~ atan( idx/16 ) + (n/d - idx/16) * Q(n/d - idx/16)231// For the accurate pass, we use the addition formula:232// atan( n/d ) - atan( idx/16 ) = atan( (n/d - idx/16)/(1 + (n*idx)/(16*d)) )233// = atan( (n - d * idx/16)/(d + n * idx/16) )234// And finally we use Taylor polynomial to compute the RHS in the accurate pass:235// atan(u) ~ P(u) = u - u^3/3 + u^5/5 - u^7/7 + u^9/9 - u^11/11 + u^13/13 -236// - u^15/15 + u^17/17237// It's error in double-double precision is estimated in Sollya to be:238// > P = x - x^3/3 + x^5/5 -x^7/7 + x^9/9 - x^11/11 + x^13/13 - x^15/15239// + x^17/17;240// > dirtyinfnorm(atan(x) - P, [-2^-5, 2^-5]);241// 0x1.aec6f...p-100242// which is about rounding errors of double-double (2^-104).243 244LIBC_INLINE static constexpr float atan2f(float y, float x) {245 using namespace atan2f_internal;246 using namespace inv_trigf_utils_internal;247 using FPBits = typename fputil::FPBits<float>;248 constexpr double IS_NEG[2] = {1.0, -1.0};249 constexpr double PI = 0x1.921fb54442d18p1;250 constexpr double PI_LO = 0x1.1a62633145c07p-53;251 constexpr double PI_OVER_4 = 0x1.921fb54442d18p-1;252 constexpr double PI_OVER_2 = 0x1.921fb54442d18p0;253 constexpr double THREE_PI_OVER_4 = 0x1.2d97c7f3321d2p+1;254 // Adjustment for constant term:255 // CONST_ADJ[x_sign][y_sign][recip]256 constexpr fputil::DoubleDouble CONST_ADJ[2][2][2] = {257 {{{0.0, 0.0}, {-PI_LO / 2, -PI_OVER_2}},258 {{-0.0, -0.0}, {-PI_LO / 2, -PI_OVER_2}}},259 {{{-PI_LO, -PI}, {PI_LO / 2, PI_OVER_2}},260 {{-PI_LO, -PI}, {PI_LO / 2, PI_OVER_2}}}};261 262 FPBits x_bits(x), y_bits(y);263 bool x_sign = x_bits.sign().is_neg();264 bool y_sign = y_bits.sign().is_neg();265 x_bits.set_sign(Sign::POS);266 y_bits.set_sign(Sign::POS);267 uint32_t x_abs = x_bits.uintval();268 uint32_t y_abs = y_bits.uintval();269 uint32_t max_abs = x_abs > y_abs ? x_abs : y_abs;270 uint32_t min_abs = x_abs <= y_abs ? x_abs : y_abs;271 float num_f = FPBits(min_abs).get_val();272 float den_f = FPBits(max_abs).get_val();273 double num_d = static_cast<double>(num_f);274 double den_d = static_cast<double>(den_f);275 276 if (LIBC_UNLIKELY(max_abs >= 0x7f80'0000U || num_d == 0.0)) {277 if (x_bits.is_nan() || y_bits.is_nan()) {278 if (x_bits.is_signaling_nan() || y_bits.is_signaling_nan())279 fputil::raise_except_if_required(FE_INVALID);280 return FPBits::quiet_nan().get_val();281 }282 double x_d = static_cast<double>(x);283 double y_d = static_cast<double>(y);284 size_t x_except = (x_d == 0.0) ? 0 : (x_abs == 0x7f80'0000 ? 2 : 1);285 size_t y_except = (y_d == 0.0) ? 0 : (y_abs == 0x7f80'0000 ? 2 : 1);286 287 // Exceptional cases:288 // EXCEPT[y_except][x_except][x_is_neg]289 // with x_except & y_except:290 // 0: zero291 // 1: finite, non-zero292 // 2: infinity293 constexpr double EXCEPTS[3][3][2] = {294 {{0.0, PI}, {0.0, PI}, {0.0, PI}},295 {{PI_OVER_2, PI_OVER_2}, {0.0, 0.0}, {0.0, PI}},296 {{PI_OVER_2, PI_OVER_2},297 {PI_OVER_2, PI_OVER_2},298 {PI_OVER_4, THREE_PI_OVER_4}},299 };300 301 double r = IS_NEG[y_sign] * EXCEPTS[y_except][x_except][x_sign];302 303 return static_cast<float>(r);304 }305 306 bool recip = x_abs < y_abs;307 double final_sign = IS_NEG[(x_sign != y_sign) != recip];308 fputil::DoubleDouble const_term = CONST_ADJ[x_sign][y_sign][recip];309 double q_d = num_d / den_d;310 311 double k_d = fputil::nearest_integer(q_d * 0x1.0p4);312 int idx = static_cast<int>(k_d);313 double r = 0.0;314 315#ifdef LIBC_MATH_HAS_SMALL_TABLES316 double p = atan_eval_no_table(num_d, den_d, k_d * 0x1.0p-4);317 r = final_sign * (p + (const_term.hi + ATAN_K_OVER_16[idx]));318#else319 q_d = fputil::multiply_add(k_d, -0x1.0p-4, q_d);320 321 double p = atan_eval(q_d, idx);322 r = final_sign *323 fputil::multiply_add(q_d, p, const_term.hi + ATAN_COEFFS[idx][0]);324#endif // LIBC_MATH_HAS_SMALL_TABLES325 326#ifdef LIBC_MATH_HAS_SKIP_ACCURATE_PASS327 return static_cast<float>(r);328#else329 constexpr uint32_t LOWER_ERR = 4;330 // Mask sticky bits in double precision before rounding to single precision.331 constexpr uint32_t MASK =332 mask_trailing_ones<uint32_t, fputil::FPBits<double>::SIG_LEN -333 FPBits::SIG_LEN - 1>();334 constexpr uint32_t UPPER_ERR = MASK - LOWER_ERR;335 336 uint32_t r_bits = static_cast<uint32_t>(cpp::bit_cast<uint64_t>(r)) & MASK;337 338 // Ziv's rounding test.339 if (LIBC_LIKELY(r_bits > LOWER_ERR && r_bits < UPPER_ERR))340 return static_cast<float>(r);341 342 return atan2f_double_double(num_d, den_d, q_d, idx, k_d, final_sign,343 const_term);344#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS345}346 347} // namespace math348 349} // namespace LIBC_NAMESPACE_DECL350 351#endif // LIBC_MATH_HAS_SKIP_ACCURATE_PASS352 353#endif // LLVM_LIBC_SRC___SUPPORT_MATH_ATAN2F_H354