1 /*
2 * Double-precision vector atan2(x) function.
3 *
4 * Copyright (c) 2021-2023, Arm Limited.
5 * SPDX-License-Identifier: MIT OR Apache-2.0 WITH LLVM-exception
6 */
7
8 #include "v_math.h"
9 #include "pl_sig.h"
10 #include "pl_test.h"
11
12 #if V_SUPPORTED
13
14 #include "atan_common.h"
15
16 #define PiOver2 v_f64 (0x1.921fb54442d18p+0)
17 #define SignMask v_u64 (0x8000000000000000)
18
19 /* Special cases i.e. 0, infinity, NaN (fall back to scalar calls). */
20 VPCS_ATTR
21 NOINLINE static v_f64_t
specialcase(v_f64_t y,v_f64_t x,v_f64_t ret,v_u64_t cmp)22 specialcase (v_f64_t y, v_f64_t x, v_f64_t ret, v_u64_t cmp)
23 {
24 return v_call2_f64 (atan2, y, x, ret, cmp);
25 }
26
27 /* Returns 1 if input is the bit representation of 0, infinity or nan. */
28 static inline v_u64_t
zeroinfnan(v_u64_t i)29 zeroinfnan (v_u64_t i)
30 {
31 return v_cond_u64 (2 * i - 1 >= v_u64 (2 * asuint64 (INFINITY) - 1));
32 }
33
34 /* Fast implementation of vector atan2.
35 Maximum observed error is 2.8 ulps:
36 v_atan2(0x1.9651a429a859ap+5, 0x1.953075f4ee26p+5)
37 got 0x1.92d628ab678ccp-1
38 want 0x1.92d628ab678cfp-1. */
39 VPCS_ATTR
V_NAME(atan2)40 v_f64_t V_NAME (atan2) (v_f64_t y, v_f64_t x)
41 {
42 v_u64_t ix = v_as_u64_f64 (x);
43 v_u64_t iy = v_as_u64_f64 (y);
44
45 v_u64_t special_cases = zeroinfnan (ix) | zeroinfnan (iy);
46
47 v_u64_t sign_x = ix & SignMask;
48 v_u64_t sign_y = iy & SignMask;
49 v_u64_t sign_xy = sign_x ^ sign_y;
50
51 v_f64_t ax = v_abs_f64 (x);
52 v_f64_t ay = v_abs_f64 (y);
53
54 v_u64_t pred_xlt0 = x < 0.0;
55 v_u64_t pred_aygtax = ay > ax;
56
57 /* Set up z for call to atan. */
58 v_f64_t n = v_sel_f64 (pred_aygtax, -ax, ay);
59 v_f64_t d = v_sel_f64 (pred_aygtax, ay, ax);
60 v_f64_t z = v_div_f64 (n, d);
61
62 /* Work out the correct shift. */
63 v_f64_t shift = v_sel_f64 (pred_xlt0, v_f64 (-2.0), v_f64 (0.0));
64 shift = v_sel_f64 (pred_aygtax, shift + 1.0, shift);
65 shift *= PiOver2;
66
67 v_f64_t ret = eval_poly (z, z, shift);
68
69 /* Account for the sign of x and y. */
70 ret = v_as_f64_u64 (v_as_u64_f64 (ret) ^ sign_xy);
71
72 if (unlikely (v_any_u64 (special_cases)))
73 {
74 return specialcase (y, x, ret, special_cases);
75 }
76
77 return ret;
78 }
79 VPCS_ALIAS
80
81 /* Arity of 2 means no mathbench entry emitted. See test/mathbench_funcs.h. */
82 PL_SIG (V, D, 2, atan2)
83 // TODO tighten this once __v_atan2 is fixed
84 PL_TEST_ULP (V_NAME (atan2), 2.9)
85 PL_TEST_INTERVAL (V_NAME (atan2), -10.0, 10.0, 50000)
86 PL_TEST_INTERVAL (V_NAME (atan2), -1.0, 1.0, 40000)
87 PL_TEST_INTERVAL (V_NAME (atan2), 0.0, 1.0, 40000)
88 PL_TEST_INTERVAL (V_NAME (atan2), 1.0, 100.0, 40000)
89 PL_TEST_INTERVAL (V_NAME (atan2), 1e6, 1e32, 40000)
90 #endif
91