fpu: Introduce exp_scalbn
Avoid exponent overflow as well as checking that we don't lose information with opposing scaling. Use it in partsN(scalbn) and partsN(round_to_int_normal). Reviewed-by: Philippe Mathieu-Daudé <philmd@linaro.org> Signed-off-by: Richard Henderson <richard.henderson@linaro.org>
Richard Henderson committed
Apr 29, 2026 at 08:49 UTC
3ce572aa8dc884a1ffa8ae640791f0ed58040410
2 files changed
+31
-3
fpu/softfloat-parts.c.inc
+2
-3
@@ -1098,8 +1098,7 @@ static bool partsN(round_to_int_normal)(FloatPartsN *a, FloatRoundMode rmode,
1098
uint64_t frac_lsb, frac_lsbm1, rnd_even_mask, rnd_mask, inc;
1099
int shift_adj;
1100
1101
- scale = MIN(MAX(scale, -0x10000), 0x10000);
1102
- a->exp += scale;
1101
+ a->exp = exp_scalbn(a->exp, scale);
1102
1103
if (a->exp < 0) {
1104
bool one;
@@ -1623,7 +1622,7 @@ FloatPartsN partsN(scalbn)(const FloatPartsN *a, int n, float_status *s)
1622
case float_class_normal:
1623
{
1624
FloatPartsN r = *a;
1626
- r.exp += MIN(MAX(n, -0x10000), 0x10000);
1625
+ r.exp = exp_scalbn(r.exp, n);
1626
return r;
1627
}
1628
default:
fpu/softfloat.c
+29
@@ -461,6 +461,15 @@ typedef struct {
461
uint64_t frac_lo;
462
} FloatParts256;
463
464
+/*
465
+ * Minimum and maximum exponent for scalbn.
466
+ * These are chosen to be much larger than the true exponent for any input format,
467
+ * but also not at the bounds of INT32_{MIN,MAX} so that we can perform other
468
+ * arithmetic on the exponent without overflowing, particularly during uncanon.
469
+ */
470
+#define SCALBN_EXP_MAX 0x0fffffff
471
+#define SCALBN_EXP_MIN (-SCALBN_EXP_MAX)
472
+
473
/* These apply to the most significant word of each FloatPartsN. */
474
#define DECOMPOSED_BINARY_POINT 63
475
#define DECOMPOSED_IMPLICIT_BIT (1ull << DECOMPOSED_BINARY_POINT)
@@ -601,6 +610,26 @@ static float128 QEMU_FLATTEN float128_pack_raw(const FloatParts128 *p)
610
*----------------------------------------------------------------------------*/
611
#include "softfloat-specialize.c.inc"
612
613
+static int32_t exp_scalbn(int32_t exp, int32_t scale)
614
+{
615
+ /*
616
+ * Catch chains of scaling which lose information.
617
+ * In particular, if the exponent has been saturated,
618
+ * do not allow it to become unsaturated.
619
+ */
620
+ if (exp >= SCALBN_EXP_MAX) {
621
+ assert(scale >= 0);
622
+ } else if (exp <= SCALBN_EXP_MIN) {
623
+ assert(scale <= 0);
624
+ }
625
+ if (sadd32_overflow(exp, scale, &exp)) {
626
+ exp = scale < 0 ? SCALBN_EXP_MIN : SCALBN_EXP_MAX;
627
+ } else {
628
+ exp = MIN(MAX(exp, SCALBN_EXP_MIN), SCALBN_EXP_MAX);
629
+ }
630
+ return exp;
631
+}
632
+
633
/*
634
* Helper functions for softfloat-parts.c.inc, per-size operations.
635
*/