Skip to main content

c/
f80.rs

1// Copyright (c) 2026 Meng Zhuo
2// SPDX-License-Identifier: BSD-3-Clause
3
4// x86_64 long-double ABI bridge.
5//
6// The x86_64 System V ABI passes long double as a 16-byte stack object and
7// returns it in x87 ST(0).  keel's arithmetic is f64 internally, so these
8// helpers only translate at the ABI boundary; precision beyond f64 is lost.
9
10/// A raw x86_64 long double (80-bit value in a 16-byte, 16-aligned slot).
11#[cfg(target_arch = "x86_64")]
12#[repr(C, align(16))]
13#[derive(Clone, Copy)]
14pub struct F80(pub [u8; 16]);
15
16/// Load an x87 80-bit value from `p` and store it as f64.
17#[cfg(target_arch = "x86_64")]
18#[inline]
19pub unsafe fn f80_to_f64(p: *const u8) -> f64 {
20    let mut out: f64 = 0.0;
21    core::arch::asm!(
22        "fld tbyte ptr [{p}]",
23        "fstp qword ptr [{o}]",
24        p = in(reg) p,
25        o = in(reg) &mut out,
26        options(nostack),
27    );
28    out
29}
30
31/// Store `v` as an x87 80-bit value at `p`.
32#[cfg(target_arch = "x86_64")]
33#[inline]
34pub unsafe fn f64_to_f80(v: f64, p: *mut u8) {
35    core::arch::asm!(
36        "fld qword ptr [{v}]",
37        "fstp tbyte ptr [{p}]",
38        v = in(reg) &v,
39        p = in(reg) p,
40        options(nostack),
41    );
42}
43
44#[cfg(target_arch = "x86_64")]
45#[repr(C)]
46struct VaListX86 {
47    gp_offset: i32,
48    fp_offset: i32,
49    overflow_arg_area: *const u8,
50    reg_save_area: *const u8,
51}
52
53/// Read the next C variadic long double.
54///
55/// On x86_64 a long double is always passed on the stack in a 16-byte slot.
56/// The caller's va_list keeps the next stack argument in overflow_arg_area.
57#[cfg(target_arch = "x86_64")]
58pub unsafe fn valist_read_f80(args: &mut VaList<'_>) -> F80 {
59    let p = args as *mut VaList<'_> as *mut VaListX86;
60    let addr = ((*p).overflow_arg_area as usize + 15) & !15usize;
61    let mut out = F80([0u8; 16]);
62    core::ptr::copy_nonoverlapping(addr as *const u8, out.0.as_mut_ptr(), 16);
63    (*p).overflow_arg_area = (addr + 16) as *const u8;
64    out
65}