//===-- Implementation header for acospif16 ---------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#ifndef LLVM_LIBC_SRC___SUPPORT_MATH_ACOSPIF16_H
#define LLVM_LIBC_SRC___SUPPORT_MATH_ACOSPIF16_H

#include "include/llvm-libc-macros/float16-macros.h"

#ifdef LIBC_TYPES_HAS_FLOAT16

#include "src/__support/FPUtil/FEnvImpl.h"
#include "src/__support/FPUtil/FPBits.h"
#include "src/__support/FPUtil/PolyEval.h"
#include "src/__support/FPUtil/cast.h"
#include "src/__support/FPUtil/multiply_add.h"
#include "src/__support/FPUtil/sqrt.h"
#include "src/__support/macros/optimization.h"

namespace LIBC_NAMESPACE_DECL {

namespace math {

LIBC_INLINE constexpr float16 acospif16(float16 x) {
  using FPBits = fputil::FPBits<float16>;
  FPBits xbits(x);

  uint16_t x_u = xbits.uintval();
  uint16_t x_abs = x_u & 0x7fff;
  uint16_t x_sign = x_u >> 15;

  // |x| > 0x1p0, |x| > 1, or x is NaN.
  if (LIBC_UNLIKELY(x_abs > 0x3c00)) {
    // acospif16(NaN) = NaN
    if (xbits.is_nan()) {
      if (xbits.is_signaling_nan()) {
        fputil::raise_except_if_required(FE_INVALID);
        return FPBits::quiet_nan().get_val();
      }

      return x;
    }

    // 1 < |x| <= +inf
    fputil::raise_except_if_required(FE_INVALID);
    fputil::set_errno_if_required(EDOM);

    return FPBits::quiet_nan().get_val();
  }

  // |x| == 0x1p0, x is 1 or -1
  // if x is (-)1, return 1
  // if x is (+)1, return 0
  if (LIBC_UNLIKELY(x_abs == 0x3c00))
    return fputil::cast<float16>(x_sign ? 1.0f : 0.0f);

  float xf = x;
  float xsq = xf * xf;

  // Degree-6 minimax polynomial coefficients of asin(x) generated by Sollya
  // with: > P = fpminimax(asin(x)/(pi * x), [|0, 2, 4, 6, 8|], [|SG...|], [0,
  // 0.5]);
  constexpr float POLY_COEFFS[5] = {0x1.45f308p-2f, 0x1.b2900cp-5f,
                                    0x1.897e36p-6f, 0x1.9efafcp-7f,
                                    0x1.06d884p-6f};
  // |x| <= 0x1p-1, |x| <= 0.5
  if (x_abs <= 0x3800) {
    // if x is 0, return 0.5
    if (LIBC_UNLIKELY(x_abs == 0))
      return fputil::cast<float16>(0.5f);

    // Note that: acos(x) = pi/2 + asin(-x) = pi/2 - asin(x), then
    //            acospi(x) = 0.5 - asin(x)/pi
    float interm =
        fputil::polyeval(xsq, POLY_COEFFS[0], POLY_COEFFS[1], POLY_COEFFS[2],
                         POLY_COEFFS[3], POLY_COEFFS[4]);

    return fputil::cast<float16>(fputil::multiply_add(-xf, interm, 0.5f));
  }

  // When |x| > 0.5, assume that 0.5 < |x| <= 1
  //
  // Step-by-step range-reduction proof:
  // 1:  Let y = asin(x), such that, x = sin(y)
  // 2:  From complimentary angle identity:
  //       x = sin(y) = cos(pi/2 - y)
  // 3:  Let z = pi/2 - y, such that x = cos(z)
  // 4:  From double angle formula; cos(2A) = 1 - 2 * sin^2(A):
  //       z = 2A, z/2 = A
  //       cos(z) = 1 - 2 * sin^2(z/2)
  // 5:  Make sin(z/2) subject of the formula:
  //       sin(z/2) = sqrt((1 - cos(z))/2)
  // 6:  Recall [3]; x = cos(z). Therefore:
  //       sin(z/2) = sqrt((1 - x)/2)
  // 7:  Let u = (1 - x)/2
  // 8:  Therefore:
  //       asin(sqrt(u)) = z/2
  //       2 * asin(sqrt(u)) = z
  // 9:  Recall [3]; z = pi/2 - y. Therefore:
  //       y = pi/2 - z
  //       y = pi/2 - 2 * asin(sqrt(u))
  // 10: Recall [1], y = asin(x). Therefore:
  //       asin(x) = pi/2 - 2 * asin(sqrt(u))
  // 11: Recall that: acos(x) = pi/2 + asin(-x) = pi/2 - asin(x)
  //     Therefore:
  //       acos(x) = pi/2 - (pi/2 - 2 * asin(sqrt(u)))
  //       acos(x) = 2 * asin(sqrt(u))
  //       acospi(x) = 2 * (asin(sqrt(u)) / pi)
  //
  // THE RANGE REDUCTION, HOW?
  // 12: Recall [7], u = (1 - x)/2
  // 13: Since 0.5 < x <= 1, therefore:
  //       0 <= u <= 0.25 and 0 <= sqrt(u) <= 0.5
  //
  // Hence, we can reuse the same [0, 0.5] domain polynomial approximation for
  // Step [11] as `sqrt(u)` is in range.
  // When -1 < x <= -0.5, the identity:
  //       acos(x) = pi - acos(-x)
  //       acospi(x) = 1 - acos(-x)/pi
  // allows us to compute for the negative x value (lhs)
  // with a positive x value instead (rhs).

  float xf_abs = (xf < 0 ? -xf : xf);
  float u = fputil::multiply_add(-0.5f, xf_abs, 0.5f);
  float sqrt_u = fputil::sqrt<float>(u);

  float asin_sqrt_u =
      sqrt_u * fputil::polyeval(u, POLY_COEFFS[0], POLY_COEFFS[1],
                                POLY_COEFFS[2], POLY_COEFFS[3], POLY_COEFFS[4]);

  // Same as acos(x), but devided the expression with pi
  return fputil::cast<float16>(
      x_sign ? fputil::multiply_add(-2.0f, asin_sqrt_u, 1.0f)
             : 2.0f * asin_sqrt_u);
}

} // namespace math

} // namespace LIBC_NAMESPACE_DECL

#endif // LIBC_TYPES_HAS_FLOAT16

#endif // LLVM_LIBC_SRC___SUPPORT_MATH_ACOSPIF16_H
