1 //===-- Single-precision cos 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 "math_utils.h"
10 #include "sincosf_utils.h"
11 
12 #include "src/__support/common.h"
13 #include <math.h>
14 
15 #include <stdint.h>
16 
17 namespace __llvm_libc {
18 
19 // Fast cosf implementation. Worst-case ULP is 0.5607, maximum relative
20 // error is 0.5303 * 2^-23. A single-step range reduction is used for
21 // small values. Large inputs have their range reduced using fast integer
22 // arithmetic.
LLVM_LIBC_ENTRYPOINT(cosf)23 float LLVM_LIBC_ENTRYPOINT(cosf)(float y) {
24   double x = y;
25   double s;
26   int n;
27   const sincos_t *p = &__sincosf_table[0];
28 
29   if (abstop12(y) < abstop12(pio4)) {
30     double x2 = x * x;
31 
32     if (unlikely(abstop12(y) < abstop12(as_float(0x39800000))))
33       return 1.0f;
34 
35     return sinf_poly(x, x2, p, 1);
36   } else if (likely(abstop12(y) < abstop12(120.0f))) {
37     x = reduce_fast(x, p, &n);
38 
39     // Setup the signs for sin and cos.
40     s = p->sign[n & 3];
41 
42     if (n & 2)
43       p = &__sincosf_table[1];
44 
45     return sinf_poly(x * s, x * x, p, n ^ 1);
46   } else if (abstop12(y) < abstop12(INFINITY)) {
47     uint32_t xi = as_uint32_bits(y);
48     int sign = xi >> 31;
49 
50     x = reduce_large(xi, &n);
51 
52     // Setup signs for sin and cos - include original sign.
53     s = p->sign[(n + sign) & 3];
54 
55     if ((n + sign) & 2)
56       p = &__sincosf_table[1];
57 
58     return sinf_poly(x * s, x * x, p, n ^ 1);
59   }
60 
61   return invalid(y);
62 }
63 
64 } // namespace __llvm_libc
65