1/* Round to integer type. ldbl-96 version.
2 Copyright (C) 2016-2018 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Lesser General Public
7 License as published by the Free Software Foundation; either
8 version 2.1 of the License, or (at your option) any later version.
9
10 The GNU C Library is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public
16 License along with the GNU C Library; if not, see
17 <http://www.gnu.org/licenses/>. */
18
19#include <errno.h>
20#include <fenv.h>
21#include <math.h>
22#include <math_private.h>
23#include <libm-alias-ldouble.h>
24#include <stdbool.h>
25#include <stdint.h>
26
27#define BIAS 0x3fff
28#define MANT_DIG 64
29
30#if UNSIGNED
31# define RET_TYPE uintmax_t
32#else
33# define RET_TYPE intmax_t
34#endif
35
36#include <fromfp.h>
37
38RET_TYPE
39FUNC (long double x, int round, unsigned int width)
40{
41 if (width > INTMAX_WIDTH)
42 width = INTMAX_WIDTH;
43 uint16_t se;
44 uint32_t hx, lx;
45 GET_LDOUBLE_WORDS (se, hx, lx, x);
46 bool negative = (se & 0x8000) != 0;
47 if (width == 0)
48 return fromfp_domain_error (negative, width);
49 if ((hx | lx) == 0)
50 return 0;
51 int exponent = se & 0x7fff;
52 exponent -= BIAS;
53 int max_exponent = fromfp_max_exponent (negative, width);
54 if (exponent > max_exponent)
55 return fromfp_domain_error (negative, width);
56
57 uint64_t ix = (((uint64_t) hx) << 32) | lx;
58 uintmax_t uret;
59 bool half_bit, more_bits;
60 if (exponent >= MANT_DIG - 1)
61 {
62 uret = ix;
63 /* Exponent 63; no shifting required. */
64 half_bit = false;
65 more_bits = false;
66 }
67 else if (exponent >= -1)
68 {
69 uint64_t h = 1ULL << (MANT_DIG - 2 - exponent);
70 half_bit = (ix & h) != 0;
71 more_bits = (ix & (h - 1)) != 0;
72 if (exponent == -1)
73 uret = 0;
74 else
75 uret = ix >> (MANT_DIG - 1 - exponent);
76 }
77 else
78 {
79 uret = 0;
80 half_bit = false;
81 more_bits = true;
82 }
83 return fromfp_round_and_return (negative, uret, half_bit, more_bits, round,
84 exponent, max_exponent, width);
85}
86