[libc-commits] [libc] [libc][math] Add bit-rounding roundf implementation (PR #221648)

via libc-commits libc-commits at lists.llvm.org
Wed Sep 16 21:00:21 PDT 2026


================
@@ -109,48 +109,41 @@ LIBC_INLINE constexpr T round(T x) {
   using StorageType = typename FPBits<T>::StorageType;
   FPBits<T> bits(x);
 
-  // If x is infinity NaN or zero, return it.
-  if (bits.is_inf_or_nan() || bits.is_zero())
-    return x;
+  // x86 binary80 has NaN encodings with a non-all-ones exponent, so the
+  // biased-exponent check below does not cover every NaN representation.
+  if constexpr (get_fp_type<T>() == FPType::X86_Binary80) {
+    if (bits.is_nan())
+      return x;
+  }
 
-  int exponent = bits.get_exponent();
+  uint16_t biased_exponent = bits.get_biased_exponent();
 
-  // If the exponent is greater than the most negative mantissa
-  // exponent, then x is already an integer.
-  if (exponent >= static_cast<int>(FPBits<T>::FRACTION_LEN))
+  // If x is infinity, NaN, or has no fractional bits, return it.
+  if (biased_exponent >= FPBits<T>::EXP_BIAS + FPBits<T>::FRACTION_LEN)
     return x;
 
-  if (exponent == -1) {
-    // Absolute value of x is greater than equal to 0.5 but less than 1.
+  if (biased_exponent == FPBits<T>::EXP_BIAS - 1) {
+    // Absolute value of x is greater than or equal to 0.5 but less than 1.
     return FPBits<T>::one(bits.sign()).get_val();
   }
 
-  if (exponent <= -2) {
-    // Absolute value of x is less than 0.5.
+  if (biased_exponent <= FPBits<T>::EXP_BIAS - 2) {
----------------
sriramshastry wrote:

I looked at the generated x86-64 assembly against current main; the patch reduces instructions, branches, and code size while removing addss and the 8-byte constant table. With latest patch submission following is the comparision:

```
|Metric						|Main	|Patched  |Change        |
+---------------------------+-------+---------+--------------+
|Instructions				|44		|35		  |-9            |
|Conditional branches		|7		|2		  |-5            |
|Unconditional branches		|1		|0		  |-1            |
|Text size					|130 	|B		  |101 B	-29 B|
|addss						|1		|0		  |Removed       |
|Constant table				|8 B	|0 B	  |Removed       |
|Denormals					|—		|—		  |21.03% faster |
|Full normals				|—		|—		  |22.56% faster |
|Near unity					|—		|—		  |27.71% faster |

```

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


More information about the libc-commits mailing list