#include "src/math/log2f16.h"
#include "hdr/errno_macros.h"
#include "hdr/fenv_macros.h"
#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/except_value_utils.h"
#include "src/__support/FPUtil/multiply_add.h"
#include "src/__support/common.h"
#include "src/__support/macros/config.h"
#include "src/__support/macros/optimization.h"
#include "src/__support/macros/properties/cpu_features.h"
#include "src/__support/math/expxf16_utils.h"
namespace LIBC_NAMESPACE_DECL {
#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
#ifdef LIBC_TARGET_CPU_HAS_FMA_FLOAT
static constexpr size_t N_LOG2F16_EXCEPTS = 2;
#else
static constexpr size_t N_LOG2F16_EXCEPTS = 9;
#endif
static constexpr fputil::ExceptValues<float16, N_LOG2F16_EXCEPTS>
LOG2F16_EXCEPTS = {{
#ifndef LIBC_TARGET_CPU_HAS_FMA_FLOAT
{0x3889U, 0xba8dU, 0U, 1U, 0U},
{0x3b8dU, 0xad56U, 0U, 1U, 0U},
#endif
{0x3ba3U, 0xac4aU, 0U, 1U, 0U},
#ifndef LIBC_TARGET_CPU_HAS_FMA_FLOAT
{0x3be6U, 0xa4b8U, 0U, 1U, 0U},
{0x3bebU, 0xa39cU, 0U, 1U, 1U},
#endif
{0x3bedU, 0xa2e2U, 0U, 1U, 1U},
#ifndef LIBC_TARGET_CPU_HAS_FMA_FLOAT
{0x3bfbU, 0x9b38U, 0U, 1U, 1U},
{0x3bffU, 0x91c5U, 0U, 1U, 1U},
{0x3c89U, 0x31cbU, 1U, 0U, 1U},
#endif
}};
#endif
LLVM_LIBC_FUNCTION(float16, log2f16, (float16 x)) {
using namespace math::expxf16_internal;
using FPBits = fputil::FPBits<float16>;
FPBits x_bits(x);
uint16_t x_u = x_bits.uintval();
if (LIBC_UNLIKELY(x_u == 0U || x_u == 0x3c00U || x_u >= 0x7c00U)) {
if (x_bits.is_nan()) {
if (x_bits.is_signaling_nan()) {
fputil::raise_except_if_required(FE_INVALID);
return FPBits::quiet_nan().get_val();
}
return x;
}
if ((x_u & 0x7fffU) == 0U) {
fputil::raise_except_if_required(FE_DIVBYZERO);
return FPBits::inf(Sign::NEG).get_val();
}
if (x_u == 0x3c00U)
return FPBits::zero().get_val();
if (x_u > 0x8000U) {
fputil::set_errno_if_required(EDOM);
fputil::raise_except_if_required(FE_INVALID);
return FPBits::quiet_nan().get_val();
}
return FPBits::inf().get_val();
}
#ifndef LIBC_MATH_HAS_SKIP_ACCURATE_PASS
if (auto r = LOG2F16_EXCEPTS.lookup(x_u); LIBC_UNLIKELY(r.has_value()))
return r.value();
#endif
int m = -FPBits::EXP_BIAS;
if ((x_u & FPBits::EXP_MASK) == 0U) {
constexpr float NORMALIZE_EXP = 1U << FPBits::FRACTION_LEN;
x_bits = FPBits(x_bits.get_val() * fputil::cast<float16>(NORMALIZE_EXP));
x_u = x_bits.uintval();
m -= FPBits::FRACTION_LEN;
}
uint16_t mant = x_bits.get_mantissa();
int f = mant >> 5;
m += x_u >> FPBits::FRACTION_LEN;
x_bits.set_biased_exponent(FPBits::EXP_BIAS);
float mant_f = x_bits.get_val();
float v = fputil::multiply_add(mant_f, ONE_OVER_F_F[f], -1.0f);
float log2p1_d_over_f =
v * fputil::polyeval(v, 0x1.715476p+0f, -0x1.71771ap-1f, 0x1.ecb38ep-2f);
float log2_1_mant = LOG2F_F[f] + log2p1_d_over_f;
return fputil::cast<float16>(static_cast<float>(m) + log2_1_mant);
}
}