#ifndef LLVM_LIBC_SRC___SUPPORT_FPUTIL_NEAREST_INTEGER_H
#define LLVM_LIBC_SRC___SUPPORT_FPUTIL_NEAREST_INTEGER_H
#include "src/__support/macros/config.h"
#include "src/__support/macros/optimization.h"
#include "src/__support/macros/properties/architectures.h"
#include "src/__support/macros/properties/cpu_features.h"
#if (defined(LIBC_TARGET_ARCH_IS_X86_64) && defined(LIBC_TARGET_CPU_HAS_SSE4_2))
#include "x86_64/nearest_integer.h"
#elif defined(LIBC_TARGET_ARCH_IS_AARCH64)
#include "aarch64/nearest_integer.h"
#elif defined(LIBC_TARGET_ARCH_IS_GPU)
namespace LIBC_NAMESPACE_DECL {
namespace fputil {
LIBC_INLINE float nearest_integer(float x) { return __builtin_rintf(x); }
LIBC_INLINE double nearest_integer(double x) { return __builtin_rint(x); }
}
}
#else
namespace LIBC_NAMESPACE_DECL {
namespace fputil {
LIBC_INLINE float nearest_integer(float x) {
if (x < 0x1p24f && x > -0x1p24f) {
float r = x < 0 ? (x - 0x1.0p23f) + 0x1.0p23f : (x + 0x1.0p23f) - 0x1.0p23f;
float diff = x - r;
if (LIBC_UNLIKELY(diff > 0.5f))
return r + 1.0f;
if (LIBC_UNLIKELY(diff < -0.5f))
return r - 1.0f;
return r;
}
return x;
}
LIBC_INLINE double nearest_integer(double x) {
if (x < 0x1p53 && x > -0x1p53) {
double r = x < 0 ? (x - 0x1.0p52) + 0x1.0p52 : (x + 0x1.0p52) - 0x1.0p52;
double diff = x - r;
if (LIBC_UNLIKELY(diff > 0.5))
return r + 1.0;
if (LIBC_UNLIKELY(diff < -0.5))
return r - 1.0;
return r;
}
return x;
}
}
}
#endif
#endif