From 3688e03a745f0c961c4808a9cf854058501ac4bf Mon Sep 17 00:00:00 2001 From: Alexandre Figueiredo Date: Tue, 27 Oct 2026 00:07:53 +0000 Subject: [PATCH] fix(libc): compute cbrtl with FreeBSD msun's ld80 code as the bundled libc.prx does --- core/libs/prx/libc/src/Math.cpp | 69 ++++++++++++++++++++++++++++++++- core/libs/tests/GuestMath.cpp | 51 ++++++++++++++++++++++++ docs/dev/debt/libc.md | 3 +- 3 files changed, 121 insertions(+), 2 deletions(-) diff --git a/core/libs/prx/libc/src/Math.cpp b/core/libs/prx/libc/src/Math.cpp index 351a33b9b651..c1dd0af819b6 100644 --- a/core/libs/prx/libc/src/Math.cpp +++ b/core/libs/prx/libc/src/Math.cpp @@ -1,3 +1,19 @@ +/* Derived from FreeBSD lib/msun/src/s_cbrtl.c (release/11.4.0) */ +/*- + * ==================================================== + * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. + * Copyright (c) 2009-2011, Bruce D. Evans, Steven G. Kargl, David Schultz. + * + * Developed at SunPro, a Sun Microsystems, Inc. business. + * Permission to use, copy, modify, and distribute this + * software is freely granted, provided that this notice + * is preserved. + * ==================================================== + * + * The argument reduction and testing for exceptional cases was + * written by Steven G. Kargl with input from Bruce D. Evans + * and David A. Schultz. + */ #include "prx/libc/include/Api.hpp" #include #include @@ -173,6 +189,15 @@ ExtendedParts SplitExtended(long double value) { return parts; } +long double JoinExtended(std::uint64_t mantissa, std::uint16_t signExponent) { + unsigned char bytes[sizeof(long double)] = {}; + std::memcpy(bytes, &mantissa, sizeof(mantissa)); + std::memcpy(bytes + sizeof(mantissa), &signExponent, sizeof(signExponent)); + long double value; + std::memcpy(&value, bytes, sizeof(value)); + return value; +} + long double ClearLowMantissaWord(long double value) { unsigned char bytes[sizeof(long double)]; std::memcpy(bytes, &value, sizeof(value)); @@ -559,7 +584,49 @@ long double APS5_VABI acoshl_nid_postfix(long double x) { return std::acosh(x); long double APS5_VABI asinhl_nid_postfix(long double x) { return std::asinh(x); } long double APS5_VABI atanhl_nid_postfix(long double x) { return std::atanh(x); } long double APS5_VABI atan2l_nid_postfix(long double y, long double x) { return std::atan2(y, x); } -long double APS5_VABI cbrtl_nid_postfix(long double x) { return std::cbrt(x); } +long double APS5_VABI cbrtl_nid_postfix(long double x) { + constexpr std::uint32_t B1 = 709958130; + constexpr int Bias = 0x3fff; + ExtendedParts parts = SplitExtended(x); + const std::uint16_t sign = parts.signExponent & 0x8000; + int k = parts.signExponent & 0x7fff; + if (k == 0x7fff) return x + x; + if (k == 0) { + if (parts.mantissa == 0) return x; + parts = SplitExtended(x * 0x1p514L); + k = (parts.signExponent & 0x7fff) - (Bias + 514); + } else { + k -= Bias; + } + long double reduced = JoinExtended(parts.mantissa, Bias); + switch (k % 3) { + case 1: + case -2: + reduced = 2 * reduced; + --k; + break; + case 2: + case -1: + reduced = 4 * reduced; + k -= 2; + break; + } + const long double scale = JoinExtended(0x8000000000000000ull, static_cast(sign | (Bias + k / 3))); + const float estimate = std::bit_cast((std::bit_cast(static_cast(reduced)) & 0x7fffffffu) / 3 + B1); + const double dx = static_cast(reduced); + double dt = estimate; + double dr = dt * dt * dt; + dt = dt * (dx + dx + dr) / (dx + dr + dr); + dr = dt * dt * dt; + dt = dt * (dx + dx + dr) / (dx + dr + dr); + const volatile double shift = 0x1p32; + const volatile double away = 0x1p-31; + long double t = (static_cast(shift) + away + dt) - 0x1p32L; + long double r = reduced / (t * t); + r = (r - t) / ((t + t) + r); + t = t + t * r; + return t * scale; +} long double APS5_VABI erfl_nid_postfix(long double x) { return std::erf(x); } long double APS5_VABI erfcl_nid_postfix(long double x) { return std::erfc(x); } long double APS5_VABI expm1l_nid_postfix(long double x) { return std::expm1(x); } diff --git a/core/libs/tests/GuestMath.cpp b/core/libs/tests/GuestMath.cpp index 8f8fff29c944..f2602ee7f093 100644 --- a/core/libs/tests/GuestMath.cpp +++ b/core/libs/tests/GuestMath.cpp @@ -1160,6 +1160,56 @@ static void CheckCbrtfConsoleBits() { } } +struct X87Call { long double result; std::uint16_t control; std::uint16_t x87Flags; unsigned sseFlags; }; + +template +static X87Call CallAtControlWord(std::uint16_t control, Call call) { + const std::uint16_t savedControl = X87ControlWord(); + const unsigned savedCsr = _mm_getcsr(); + asm volatile("fnclex"); + asm volatile("fldcw %0" : : "m"(control)); + _mm_setcsr(0x1f80); + const long double result = call(); + const X87Call outcome{result, X87ControlWord(), static_cast(X87StatusWord() & 0x3f), _mm_getcsr() & 0x3f}; + asm volatile("fnclex"); + asm volatile("fldcw %0" : : "m"(savedControl)); + _mm_setcsr(savedCsr); + return outcome; +} + +static void CheckCbrtlConsoleBits() { + struct Case { std::uint64_t inputMantissa; std::uint16_t inputSignExponent; std::uint64_t outputMantissa; std::uint16_t outputSignExponent; std::uint16_t x87Flags; unsigned sseFlags; }; + const Case extended[] = { + {0xd800000000000000ull, 0x4003, 0xc000000000000000ull, 0x4000, 0x20, 0x20}, {0xd800000000000000ull, 0xc003, 0xc000000000000000ull, 0xc000, 0x20, 0x20}, + {0x8000000000000000ull, 0x4000, 0xa14517cc6b945711ull, 0x3fff, 0x20, 0x20}, {0xa000000000000000ull, 0x4002, 0x89e24209c3827654ull, 0x4000, 0x20, 0x20}, + {0x0000000000000001ull, 0x0000, 0xa14517cc6b945711ull, 0x2a95, 0x22, 0x20}, {0xffffffffffffffffull, 0x7ffe, 0xa14517cc6b945711ull, 0x5554, 0x20, 0x20}, + {0x8659809ec6db32bcull, 0x401d, 0x82151d1b393fd44dull, 0x4009, 0x20, 0x20}, {0xbd15357afb7986bdull, 0x4020, 0x91c70e7b9838a077ull, 0x400a, 0x20, 0x20}, + {0xcf76fe67ae88c153ull, 0xc00b, 0x965b32c8c1d51019ull, 0xc003, 0x20, 0x20}, {0xa69c3c7f2132c2d6ull, 0x4015, 0xb0153af818af832full, 0x4006, 0x20, 0x20}, + {0x9949610354ae1362ull, 0x4021, 0xab421a4bf7053065ull, 0x400a, 0x20, 0x20}, {0xe62954cd7699f167ull, 0x3fe2, 0xc41b843c989056a9ull, 0x3ff5, 0x20, 0x20}, + {0x0000000000000000ull, 0x0000, 0x0000000000000000ull, 0x0000, 0x00, 0x00}, {0x0000000000000000ull, 0x8000, 0x0000000000000000ull, 0x8000, 0x00, 0x00}, + {0x8000000000000000ull, 0x7fff, 0x8000000000000000ull, 0x7fff, 0x00, 0x00}, {0x8000000000000000ull, 0xffff, 0x8000000000000000ull, 0xffff, 0x00, 0x00}, + {0xc000000000000001ull, 0x7fff, 0xc000000000000001ull, 0x7fff, 0x00, 0x00}, + }; + const Case doublePrecision[] = { + {0x8000000000000000ull, 0x4000, 0xa14517cc6b945800ull, 0x3fff, 0x20, 0x20}, {0xd800000000000000ull, 0xc003, 0xc000000000000000ull, 0xc000, 0x20, 0x20}, + {0x0000000000000001ull, 0x0000, 0xa14517cc6b945800ull, 0x2a95, 0x22, 0x20}, {0x7fffffffffffffffull, 0x0000, 0xa14517cc6b945800ull, 0x2aaa, 0x22, 0x20}, + {0xd82f8566779298d8ull, 0xb21c, 0x986f23ff4a11e000ull, 0xbb5e, 0x20, 0x20}, {0xf8d1d07800000000ull, 0x2284, 0xc94503ff4f674800ull, 0x362b, 0x20, 0x20}, + {0x88e06c5dd95a24c0ull, 0x4020, 0x82e49bff760a1800ull, 0x400a, 0x20, 0x20}, {0xc000000000000001ull, 0x7fff, 0xc000000000000001ull, 0x7fff, 0x00, 0x00}, + }; + const auto check = [](std::uint16_t control, const auto& cases) { + for (const Case& test : cases) { + *__error_nid_postfix() = 12345; + const X87Call call = CallAtControlWord(control, [&] { return cbrtl_nid_postfix(MakeExtended(test.inputMantissa, test.inputSignExponent)); }); + if (!ExtendedBits(call.result, test.outputMantissa, test.outputSignExponent) || call.control != control || call.x87Flags != test.x87Flags || call.sseFlags != test.sseFlags || *__error_nid_postfix() != 12345) { + std::fprintf(stderr, "Guest cbrtl failed for %016llx:%04x with control word %04x\n", static_cast(test.inputMantissa), test.inputSignExponent, control); + std::abort(); + } + } + }; + check(0x037f, extended); + check(0x027f, doublePrecision); +} + static void CheckIntegerConversions() { for (const long long numerator : {4294967301LL, -4294967301LL}) { for (const long long denominator : {3LL, -3LL}) { @@ -2275,6 +2325,7 @@ int main() { CheckFloatMathExports(); CheckIntegerConversions(); CheckCbrtfConsoleBits(); + CheckCbrtlConsoleBits(); CheckExtendedMath(); CheckTrigfConsoleBits(); Require(atof_nid_postfix(" -12.5tail") == -12.5); diff --git a/docs/dev/debt/libc.md b/docs/dev/debt/libc.md index 66bfc4c8f9a7..398c62f10e14 100644 --- a/docs/dev/debt/libc.md +++ b/docs/dev/debt/libc.md @@ -149,7 +149,8 @@ - [tanh](../../../core/libs/prx/libc/src/Math.cpp) (libc) does not compare floating-point exceptions, and its double inputs are checked by sampling, not exhaustively. It is FreeBSD msun's [`s_tanh.c`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/lib/msun/src/s_tanh.c) over this file's msun `Expm1`, with `tiny` read at run time; it sets no `errno`, as the titles' `libc.prx` does not. It gives the same bits as the `tanh` bundled with PPSA07923 and PPSA05916 on 16 million random and 68,211 structured arguments on a Windows host; the FMA-contracted build bundled with PPSA13934 differs on 1,054 of them. - [sinhf](../../../core/libs/prx/libc/src/Math.cpp) (libc) follows the `sinhf` of the `libc.prx` bundled with PPSA28319 (disassembly): FreeBSD msun's [`e_sinhf.c`](https://github.com/freebsd/freebsd-src/blob/5aa554c7e5b6fd9042986df07f12ac5687e41392/lib/msun/src/e_sinhf.c) from before `__ldexp_expf`, which squares `expf(|x| / 2)` between `logf(FLT_MAX)` and the overflow threshold, calling msun's [`expm1f`](https://github.com/freebsd/freebsd-src/blob/59bc2f095289a10b8cfa55cbb2b45c3bd6c2d4ae/lib/msun/src/s_expm1f.c) and [`expf`](https://github.com/freebsd/freebsd-src/blob/59bc2f095289a10b8cfa55cbb2b45c3bd6c2d4ae/lib/msun/src/e_expf.c), whose paths for the arguments it passes are inlined here. Past the threshold Sony's error helper sets `errno` to `ERANGE` before returning `x * 1e37`; msun itself sets no `errno`. That code, run on a Windows host, gives the same bits as this implementation for every finite argument up to the threshold, of both signs; it was not run on Linux. That the system `libSceLibcInternal`, which Ruffle (PPSA68091) and RetroArch (PPSA99169) import while bundling a zero-return `libc.prx`, has the same code is assumed - [acoshf](../../../core/libs/prx/libc/src/Math.cpp) (libc) exact system `libSceLibcInternal` behavior and FMA-contracted copies remain unverified. Positive finite inputs use [msun](https://github.com/freebsd/freebsd-src/blob/5aa554c7e5b6fd9042986df07f12ac5687e41392/lib/msun/src/e_acoshf.c) range handling and this file's `logf`; the middle range divides -1 before addition under directed rounding. Bits, errno and SSE/x87 status and controls match the supplied PPSA03766/PPSA07923 copies on 236,592 positive finite calls (4,929 inputs, four rounding modes, DAZ/FTZ combinations and sticky flags); these samples are not exhaustive. Invalid-domain errno and SSE/x87 invalid flags are checked against two supplied bundled copies; those samples are not exhaustive either. -- [acoshl, asinhl, atanhl, atan2l, cbrtl, erfl, erfcl, expm1l, hypotl, log1pl, log2l, lgammal, tgammal, j0f, j1f, jnf, y0f, y1f and ynf](../../../core/libs/prx/libc/src/Math.cpp) (libc) return the host C library's results (the float Bessel functions through its double ones), not those of the console's own code, so the last bits can differ (`y0f`, `y1f`, `ynf` follow the console at `+-0`). `tgammaf` delegates to the host's double `tgamma` as FreeBSD 11 does ([`s_tgammaf.c`](https://github.com/freebsd/freebsd-src/blob/stable/11/lib/msun/src/s_tgammaf.c)), then restores the sign of a zero result for negative non-integer inputs from the parity of `floor(-x)`; nine title-bundled `libc.prx` builds return that sign for underflowing inputs, where Windows UCRT can return the opposite sign ([#9707](https://github.com/boykopovar/AnyPS5/issues/9707)). As in the console's `libSceLibcInternal.sprx` (SDK 4.5x build of `J03950001`, 0x56410), `lgammal` does not store the sign in `signgam`; `hypotl` returns infinity for an infinite argument even when the other is a NaN, as C11 F.10.4.3 requires. [hypot3, hypot3f and hypot3l](../../../core/libs/prx/libc/src/Math.cpp) follow that module (0x51D30, 0x520D0, 0x52420): the first NaN of x, y and z is returned unchanged, any infinity gives positive infinity, a zero argument gives the two-argument hypot of the other two, and otherwise the largest magnitude is combined with the hypot of the other two +- [acoshl, asinhl, atanhl, atan2l, erfl, erfcl, expm1l, hypotl, log1pl, log2l, lgammal, tgammal, j0f, j1f, jnf, y0f, y1f and ynf](../../../core/libs/prx/libc/src/Math.cpp) (libc) return the host C library's results (the float Bessel functions through its double ones), not those of the console's own code, so the last bits can differ (`y0f`, `y1f`, `ynf` follow the console at `+-0`). `tgammaf` delegates to the host's double `tgamma` as FreeBSD 11 does ([`s_tgammaf.c`](https://github.com/freebsd/freebsd-src/blob/stable/11/lib/msun/src/s_tgammaf.c)), then restores the sign of a zero result for negative non-integer inputs from the parity of `floor(-x)`; nine title-bundled `libc.prx` builds return that sign for underflowing inputs, where Windows UCRT can return the opposite sign ([#9707](https://github.com/boykopovar/AnyPS5/issues/9707)). As in the console's `libSceLibcInternal.sprx` (SDK 4.5x build of `J03950001`, 0x56410), `lgammal` does not store the sign in `signgam`; `hypotl` returns infinity for an infinite argument even when the other is a NaN, as C11 F.10.4.3 requires. [hypot3, hypot3f and hypot3l](../../../core/libs/prx/libc/src/Math.cpp) follow that module (0x51D30, 0x520D0, 0x52420): the first NaN of x, y and z is returned unchanged, any infinity gives positive infinity, a zero argument gives the two-argument hypot of the other two, and otherwise the largest magnitude is combined with the hypot of the other two +- [cbrtl](../../../core/libs/prx/libc/src/Math.cpp) (libc) - other SDK versions and the system `libSceLibcInternal` are not compared. It is FreeBSD msun's [`s_cbrtl.c`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/lib/msun/src/s_cbrtl.c) for ld80, as in the `libc.prx` build `J03093718` bundled with PPSA21564 (0x42360), and like that binary, which has no control-word instruction, it runs at the caller's x87 precision: at 64, 53 and 24 bits, in each rounding mode, it gives that binary's bits, `errno` and exception flags and leaves the control word unchanged for 20,000,000 random encodings, non-canonical ones included - [asinl](../../../core/libs/prx/libc/src/Math.cpp) (libc) follows the `asinl` of the `libc.prx` bundled with PPSA28319 (disassembly), FreeBSD msun's [`e_asinl.c`](https://github.com/freebsd/freebsd-src/blob/9f0432041b8fb69832f10c32da50a67f34feeb61/lib/msun/src/e_asinl.c) with the ld80 [`invtrig.c`](https://github.com/freebsd/freebsd-src/blob/9f0432041b8fb69832f10c32da50a67f34feeb61/lib/msun/ld80/invtrig.c) coefficients, which the binary holds as the same 80-bit constants. For |x| > 1, the infinities and NaN, Sony's error helper raises `FE_INVALID` and sets `errno` to `EDOM` before returning `(x - x) / (x - x)`, so a NaN argument also sets `EDOM`; msun itself sets no `errno`. 20 million random arguments in (-1, 1) give the same bits as that code run on a Windows host. The result needs the x87 precision control at 64 bits, as FreeBSD amd64 starts threads (control word `0x37f`), but guest threads do not set it: on Windows a thread started by `_beginthreadex` runs at 53 bits (`0x27f`), where `asinl(0.75)` returns mantissa `0xd91a98ae3406e000` instead of `0xd91a98ae3406e041`. The system `libSceLibcInternal` that RetroArch (PPSA99169) imports is assumed to have the same code - [acosf](../../../core/libs/prx/libc/src/Math.cpp) (libc) - for |x| > 1, the infinities and NaN, quiet NaN included, it stores `EDOM` and raises `FE_INVALID` and returns the same NaNs as titles' `libc.prx` (PPSA07923, PPSA13934). For |x| <= 1 it follows the `acosf` of the `libc.prx` bundled with PPSA28319 (disassembly): FreeBSD msun's [`e_acosf.c`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/lib/msun/src/e_acosf.c), with the same constants, `pio2_lo` read at run time and the `0xfffff000` mask on `sqrtf(z)`, which the binary holds. Titles ship different builds of that `libc.prx`: PPSA13934's is FMA-contracted and differs from this one by 1 ulp on 129,170 inputs (#9668), so no single port matches every title's last bit. - [asinf](../../../core/libs/prx/libc/src/Math.cpp) (libc) - for |x| > 1, the infinities and NaN, it stores `EDOM` before returning `(x - x) / (x - x)`, as the `libc.prx` bundled with eleven titles does, PPSA13934's included. Tiny arguments return `x` without raising `FE_INEXACT`. Otherwise this is FreeBSD msun's [`e_asinf.c`](https://github.com/freebsd/freebsd-src/blob/release/11.4.0/lib/msun/src/e_asinf.c), which gives the same bits as the `asinf` of the `libc.prx` bundled with PPSA07923 and PPSA05916 for all 2^32 arguments (run on a Windows host). The FMA-contracted builds bundled with PPSA13934 and PPSA09614 differ from it by 1 ulp on 391,714 arguments, so no single port matches every title's last bit.