1//===-- nextupdown implementation for x86 long double numbers ---*- C++ -*-===//
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#ifndef LLVM_LIBC_SRC___SUPPORT_FPUTIL_X86_64_NEXTUPDOWNLONGDOUBLE_H
10#define LLVM_LIBC_SRC___SUPPORT_FPUTIL_X86_64_NEXTUPDOWNLONGDOUBLE_H
11
12#include "src/__support/FPUtil/FPBits.h"
13#include "src/__support/macros/attributes.h"
14#include "src/__support/macros/config.h"
15#include "src/__support/macros/properties/architectures.h"
16
17#if !defined(LIBC_TARGET_ARCH_IS_X86)
18#error "Invalid include"
19#endif
20
21namespace LIBC_NAMESPACE_DECL {
22namespace fputil {
23
24template <bool IsDown>
25LIBC_INLINE LIBC_BIT_CAST_CONSTEXPR long double nextupdown(long double x) {
26 constexpr Sign sign = IsDown ? Sign::NEG : Sign::POS;
27
28 using FPBits_t = FPBits<long double>;
29 FPBits_t xbits(x);
30 if (xbits.is_nan() || xbits == FPBits_t::inf(sign))
31 return x;
32
33 // Crossing the normal/subnormal boundary also changes the explicit
34 // integer bit in the x86 extended precision encoding.
35 if (xbits == FPBits_t::max_subnormal(sign))
36 return FPBits_t::min_normal(sign).get_val();
37 if (xbits == FPBits_t::min_normal(sign: sign.negate()))
38 return FPBits_t::max_subnormal(sign: sign.negate()).get_val();
39
40 if (xbits.is_zero())
41 return FPBits_t::min_subnormal(sign).get_val();
42
43 using StorageType = typename FPBits_t::StorageType;
44
45 if (xbits.sign() == sign) {
46 if (xbits.get_mantissa() == FPBits_t::FRACTION_MASK) {
47 xbits.set_mantissa(0);
48 xbits.set_biased_exponent(xbits.get_biased_exponent() + 1);
49 } else {
50 xbits = FPBits_t(StorageType(xbits.uintval() + 1));
51 }
52
53 return xbits.get_val();
54 }
55
56 if (xbits.get_mantissa() == 0) {
57 xbits.set_mantissa(FPBits_t::FRACTION_MASK);
58 xbits.set_biased_exponent(xbits.get_biased_exponent() - 1);
59 } else {
60 xbits = FPBits_t(StorageType(xbits.uintval() - 1));
61 }
62
63 return xbits.get_val();
64}
65
66} // namespace fputil
67} // namespace LIBC_NAMESPACE_DECL
68
69#endif // LLVM_LIBC_SRC___SUPPORT_FPUTIL_X86_64_NEXTUPDOWNLONGDOUBLE_H
70