| 1 | /** |
| 2 | * This file has no copyright assigned and is placed in the Public Domain. |
| 3 | * This file is part of the mingw-w64 runtime package. |
| 4 | * No warranty is given; refer to the file DISCLAIMER.PD within this package. |
| 5 | */ |
| 6 | #include <math.h> |
| 7 | #include <fenv.h> |
| 8 | |
| 9 | long long llrintl (long double x) |
| 10 | { |
| 11 | long long retval = 0ll; |
| 12 | #if (defined(_AMD64_) && !defined(_ARM64EC_)) || (defined(__x86_64__) && !defined(__arm64ec__)) || \ |
| 13 | defined(_X86_) || defined(__i386__) |
| 14 | __asm__ __volatile__ ("fistpll %0" : "=m" (retval) : "t" (x) : "st"); |
| 15 | #else |
| 16 | int mode = fegetround(); |
| 17 | if (mode == FE_DOWNWARD) |
| 18 | retval = (long long)floor(x); |
| 19 | else if (mode == FE_UPWARD) |
| 20 | retval = (long long)ceil(x); |
| 21 | else if (mode == FE_TOWARDZERO) |
| 22 | retval = x >= 0 ? (long long)floor(x) : (long long)ceil(x); |
| 23 | else { |
| 24 | // Break `x` into integral and fractional parts. |
| 25 | long double intg, frac; |
| 26 | frac = modfl(x, &intg); |
| 27 | frac = fabsl(frac); |
| 28 | // Convert the truncated integral part to an integer. |
| 29 | retval = intg; |
| 30 | if (frac < 0.5) { |
| 31 | // Round towards zero. |
| 32 | } else if (frac > 0.5) { |
| 33 | // Round towards infinities. |
| 34 | retval += signbit(x) ? -1 : 1; |
| 35 | } else { |
| 36 | // Round to the nearest even number. |
| 37 | retval += retval % 2; |
| 38 | } |
| 39 | } |
| 40 | #endif |
| 41 | return retval; |
| 42 | } |
| 43 | |