[libc-commits] [libc] [libc][stdfix] Implement fixed point fxbits functions in llvm-libc (PR #114912)

via libc-commits libc-commits at lists.llvm.org
Tue Nov 12 11:46:36 PST 2024


================
@@ -0,0 +1,19 @@
+//===-- Implementation of lkbits function ---------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "lkbits.h"
+#include "src/__support/common.h"
+#include "src/__support/fixed_point/fx_bits.h"
+#include "src/__support/macros/config.h"
+
+namespace LIBC_NAMESPACE_DECL {
+LLVM_LIBC_FUNCTION(long accum, lkbits, (int_lk_t x)) {
+  return cpp::bit_cast<long accum, int_lk_t>(x);
----------------
PiJoules wrote:

We can't assume that a `long` is large enough to hold the bits of a `long _Accum` since they are completely different types independent of each other. The same goes for the other integral typedefs. Individual platforms can define different numbers of integral + fractional bits to the fixed point types as long as they conform the rules of minimal required bits and nondecreasing bits with increasing rank. `A.3 Possible Data Type Implementations` gives an example for `typical 24-bit DSP` where the long fixed point types might not fit in a 32-bit int.

Unfortunately, I don't think there's a C preprocessor way we can do size checks for the different ints at compile time. If we did, then we could compare those sizes against the fixed point FBIT and IBIT macros and setup a `#if` chain of comparisons to select the correct type. I think the correct way to do this might be to have the compiler emit predefined macros for either:

1. `__SIZEOF_<FX_TYPE>__` which evaluates to the size of a fixed point type in bits, then we could do the `#if` chain comparing against `__SIZEOF_SHORT/INT/LONG__` to select the right type. This approach doesn't account for padding bits, but we likely won't have any fixed point type where padding is so large that we'd need an even larger int type.
2. `__<FX_TYPE>_TYPE__` which evaluates to the appropriately sized int type (ie. `#define __INT_LR_TYPE__  int`). This might be the easier approach.
3. 
I think for unblocking this PR that using a `long long` is fine for now since clang has only one version of `long _Accum` that anyone uses.

https://github.com/llvm/llvm-project/pull/114912


More information about the libc-commits mailing list