keel-libc 0.1.7

A Rust no_std musl-compatible libc implementation
Documentation
// Copyright (c) 2026 Meng Zhuo
// SPDX-License-Identifier: BSD-3-Clause

// x86_64 long-double ABI bridge.
//
// The x86_64 System V ABI passes long double as a 16-byte stack object and
// returns it in x87 ST(0).  keel's arithmetic is f64 internally, so these
// helpers only translate at the ABI boundary; precision beyond f64 is lost.

/// A raw x86_64 long double (80-bit value in a 16-byte, 16-aligned slot).
#[cfg(target_arch = "x86_64")]
#[repr(C, align(16))]
#[derive(Clone, Copy)]
pub struct F80(pub [u8; 16]);

/// Load an x87 80-bit value from `p` and store it as f64.
#[cfg(target_arch = "x86_64")]
#[inline]
pub unsafe fn f80_to_f64(p: *const u8) -> f64 {
    let mut out: f64 = 0.0;
    core::arch::asm!(
        "fld tbyte ptr [{p}]",
        "fstp qword ptr [{o}]",
        p = in(reg) p,
        o = in(reg) &mut out,
        options(nostack),
    );
    out
}

/// Store `v` as an x87 80-bit value at `p`.
#[cfg(target_arch = "x86_64")]
#[inline]
pub unsafe fn f64_to_f80(v: f64, p: *mut u8) {
    core::arch::asm!(
        "fld qword ptr [{v}]",
        "fstp tbyte ptr [{p}]",
        v = in(reg) &v,
        p = in(reg) p,
        options(nostack),
    );
}

#[cfg(target_arch = "x86_64")]
#[repr(C)]
struct VaListX86 {
    gp_offset: i32,
    fp_offset: i32,
    overflow_arg_area: *const u8,
    reg_save_area: *const u8,
}

/// Read the next C variadic long double.
///
/// On x86_64 a long double is always passed on the stack in a 16-byte slot.
/// The caller's va_list keeps the next stack argument in overflow_arg_area.
#[cfg(target_arch = "x86_64")]
pub unsafe fn valist_read_f80(args: &mut VaList<'_>) -> F80 {
    let p = args as *mut VaList<'_> as *mut VaListX86;
    let addr = ((*p).overflow_arg_area as usize + 15) & !15usize;
    let mut out = F80([0u8; 16]);
    core::ptr::copy_nonoverlapping(addr as *const u8, out.0.as_mut_ptr(), 16);
    (*p).overflow_arg_area = (addr + 16) as *const u8;
    out
}