Mirror of the gdb-patches mailing list
 help / color / mirror / Atom feed
* [PATCH v5 0/5] gdb: Fix target floating-point encoding and signed-zero negation
@ 2026-11-12 18:52 Robert Dubner
  2026-11-12 18:52 ` [PATCH v5 1/5] gdb: Preserve neighboring bits when writing floating-point fields Robert Dubner
                   ` (4 more replies)
  0 siblings, 5 replies; 6+ messages in thread
From: Robert Dubner @ 2026-11-12 18:52 UTC (permalink / raw)
  To: gdb-patches; +Cc: stephan.rohr

This series fixes floating-point encoding, subnormal rounding, and
signed-zero handling in GDB.

It brings together the previously submitted neighboring-bit, subnormal,
and signed-zero fixes, followed by a fix for oversized shifts in
put_field.  It incorporates Stephan Rohr's review feedback, including
unit tests in target-float.c and conditional _Float128 coverage for
unary negation.

Changes in v5 include the following.

- Reuse the floating-point selftest type helper for signed-zero and
  wide-special-value tests.
- Adjust comments and formatting, including the explanation of the
  conditional _Float128 variable.
- Add the Reviewed-By tag for the subnormal patch.
- Extend validation with full GDB selftests, a full DejaGNU baseline
  comparison, UBSan, and the macro-disabled _Float128 test path.

The five patches make the following changes.

1. Preserve neighboring bits when writing a floating-point field that
   occupies only part of a byte.

2. Encode subnormal values correctly and carry MPFR ternary results
   through subnormal rounding to avoid double rounding.

3. Preserve signed zero during MPFR target conversions, while retaining
   existing zero encodings for formats without signed-zero support.

4. Implement floating-point unary negation by multiplication by -1,
   preserving the existing integer and fixed-point behavior.

5. Avoid shifts greater than or equal to the width of unsigned long
   when writing fields wider than stuff_to_put.

Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=34927

Robert Dubner (5):
  gdb: Preserve neighboring bits when writing floating-point fields
  gdb: Preserve subnormal values in target floating-point operations
  gdb: Preserve signed zero in MPFR target conversions
  gdb: Preserve signed zero in floating-point unary negation
  gdb: Avoid oversized shifts when writing floating-point fields

 gdb/target-float.c                   | 653 ++++++++++++++++++++++++---
 gdb/testsuite/gdb.base/float-neg.c   |  38 ++
 gdb/testsuite/gdb.base/float-neg.exp |  79 ++++
 gdb/valarith.c                       |   8 +-
 4 files changed, 722 insertions(+), 56 deletions(-)
 create mode 100644 gdb/testsuite/gdb.base/float-neg.c
 create mode 100644 gdb/testsuite/gdb.base/float-neg.exp


base-commit: 9db3b515b964c1bbdc4d20c1202fbf27719be269
-- 
2.34.1


^ permalink raw reply	[flat|nested] 6+ messages in thread

* [PATCH v5 1/5] gdb: Preserve neighboring bits when writing floating-point fields
  2026-11-12 18:52 [PATCH v5 0/5] gdb: Fix target floating-point encoding and signed-zero negation Robert Dubner
@ 2026-11-12 18:52 ` Robert Dubner
  2026-11-12 18:52 ` [PATCH v5 2/5] gdb: Preserve subnormal values in target floating-point operations Robert Dubner
                   ` (3 subsequent siblings)
  4 siblings, 0 replies; 6+ messages in thread
From: Robert Dubner @ 2026-11-12 18:52 UTC (permalink / raw)
  To: gdb-patches; +Cc: stephan.rohr

put_field can clear bits outside the requested field when writing part
of a byte.  For IEEE binary16, writing the exponent can clear the
adjacent sign bit, turning a negative value positive.

Limit both clearing and setting to the requested field width.  Derive
the mask from cur_bitshift to account for little-endian formats whose
total size is not a multiple of eight bits.  Correct the function
comment to describe bit lengths and the input requirements.

Add a unit test in target-float.c covering neighboring-bit preservation
in both byte orders, including formats with partial final bytes.

Reviewed-By: Rohr, Stephan <stephan.rohr@intel.com>
Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=34927
---
 gdb/target-float.c | 118 ++++++++++++++++++++++++++++++++++++++++-----
 1 file changed, 107 insertions(+), 11 deletions(-)

diff --git a/gdb/target-float.c b/gdb/target-float.c
index 31b5ac642a7..89a95067f2f 100644
--- a/gdb/target-float.c
+++ b/gdb/target-float.c
@@ -21,6 +21,7 @@
 #include "floatformat.h"
 #include "target-float.h"
 #include "gdbarch.h"
+#include "gdbsupport/selftest.h"
 
 /* Target floating-point operations.
 
@@ -229,8 +230,9 @@ get_field (const bfd_byte *data, enum floatformat_byteorders order,
   return result;
 }
 
-/* Set a field which starts at START and is LEN bytes long.  DATA and
-   TOTAL_LEN are the thing we are extracting it from, in byteorder ORDER.  */
+/* Set a field which starts at START and is LEN bits long.  DATA is the
+   buffer we are storing into, with TOTAL_LEN bits in byteorder ORDER.
+   STUFF_TO_PUT is trimmed to fit in LEN bits.  */
 static void
 put_field (unsigned char *data, enum floatformat_byteorders order,
 	   unsigned int total_len, unsigned int start, unsigned int len,
@@ -260,11 +262,11 @@ put_field (unsigned char *data, enum floatformat_byteorders order,
     }
   if (cur_bitshift > -FLOATFORMAT_CHAR_BIT)
     {
-      *(data + cur_byte) &=
-	~(((1 << ((start + len) % FLOATFORMAT_CHAR_BIT)) - 1)
-	  << (-cur_bitshift));
-      *(data + cur_byte) |=
-	(stuff_to_put & ((1 << FLOATFORMAT_CHAR_BIT) - 1)) << (-cur_bitshift);
+      unsigned int bits
+	= std::min (len, (unsigned int) (FLOATFORMAT_CHAR_BIT + cur_bitshift));
+      unsigned int mask = ((1 << bits) - 1) << (-cur_bitshift);
+      *(data + cur_byte) &= ~mask;
+      *(data + cur_byte) |= (stuff_to_put << (-cur_bitshift)) & mask;
     }
   cur_bitshift += FLOATFORMAT_CHAR_BIT;
   if (order == floatformat_little)
@@ -277,10 +279,11 @@ put_field (unsigned char *data, enum floatformat_byteorders order,
     {
       if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
 	{
-	  /* This is the last byte.  */
-	  *(data + cur_byte) &=
-	    ~((1 << (len - cur_bitshift)) - 1);
-	  *(data + cur_byte) |= (stuff_to_put >> cur_bitshift);
+	  /* This is the last byte.  Make sure we don't OR in extra high-order
+	     bits when STUFF_TO_PUT violates the LEN restriction.  */
+	  unsigned int mask = (1U << (len - cur_bitshift)) - 1;
+	  *(data + cur_byte) &= ~mask;
+	  *(data + cur_byte) |= (stuff_to_put >> cur_bitshift) & mask;
 	}
       else
 	*(data + cur_byte) = ((stuff_to_put >> cur_bitshift)
@@ -2491,3 +2494,96 @@ target_float_compare (const gdb_byte *x, const struct type *type_x,
   const target_float_ops *ops = get_target_float_ops (type_x, type_y);
   return ops->compare (x, type_x, y, type_y);
 }
+
+#if GDB_SELF_TEST
+namespace selftests
+{
+
+/* Check that writing a field preserves neighboring bits and buffer guards.
+   Use explicit expected bytes, independently of get_field and host floating-
+   point formats.  */
+
+static void
+put_field_test ()
+{
+  struct test_case
+  {
+    floatformat_byteorders order;
+    unsigned int total_len;
+    unsigned int start;
+    unsigned int len;
+    unsigned long value;
+    unsigned char before[2];
+    unsigned char after[2];
+  };
+
+  const test_case tests[] =
+    {
+      /* Writing the binary16 exponent must preserve the sign and fraction.
+	 The first pair produces the encoding of -1.5.  */
+      {floatformat_big, 16, 1, 5, 15, {0x82, 0x00}, {0xbe, 0x00}},
+      {floatformat_little, 16, 1, 5, 15, {0x00, 0x82}, {0x00, 0xbe}},
+      {floatformat_big, 16, 1, 5, 0, {0xff, 0xff}, {0x83, 0xff}},
+      {floatformat_little, 16, 1, 5, 0, {0xff, 0xff}, {0xff, 0x83}},
+      {floatformat_big, 16, 1, 5, 31, {0x80, 0x03}, {0xfc, 0x03}},
+      {floatformat_little, 16, 1, 5, 31, {0x03, 0x80}, {0x03, 0xfc}},
+
+      /* Check fields that span bytes and end on a byte boundary.  */
+      {floatformat_big, 16, 4, 12, 0x123, {0xff, 0xff}, {0xf1, 0x23}},
+      {floatformat_little, 16, 4, 12, 0x123, {0xff, 0xff}, {0x23, 0xf1}},
+      {floatformat_big, 16, 0, 16, 0xa55a, {0xff, 0xff}, {0xa5, 0x5a}},
+      {floatformat_little, 16, 0, 16, 0xa55a, {0xff, 0xff}, {0x5a, 0xa5}},
+
+      /* A non-byte-sized format also exercises the little-endian excess
+	 adjustment.  Preserve its padding and neighboring field bits.  */
+      {floatformat_big, 13, 1, 3, 0, {0xff, 0xff}, {0x8f, 0xff}},
+      {floatformat_little, 13, 1, 3, 0, {0xff, 0xff}, {0xff, 0xf1}},
+      {floatformat_big, 13, 1, 3, 5, {0xff, 0xff}, {0xdf, 0xff}},
+      {floatformat_little, 13, 1, 3, 5, {0xff, 0xff}, {0xff, 0xfb}},
+      {floatformat_big, 13, 1, 5, 0, {0xff, 0xff}, {0x83, 0xff}},
+      {floatformat_little, 13, 1, 5, 0, {0xff, 0xff}, {0x7f, 0xf0}},
+
+      /* Make sure STUFF_TO_PUT does not change bits outside the field.  */
+      {floatformat_big, 16, 6, 10, 0x7ff, {0x00, 0x00}, {0x03, 0xff}},
+      {floatformat_little, 16, 6, 10, 0x7ff, {0x00, 0x00}, {0xff, 0x03}},
+    };
+
+  for (const test_case &test : tests)
+    {
+      unsigned char data[] = {0xa5, test.before[0], test.before[1], 0x5a};
+      put_field (data + 1, test.order, test.total_len, test.start, test.len,
+		 test.value);
+      SELF_CHECK (data[0] == 0xa5);
+      SELF_CHECK (data[1] == test.after[0]);
+      SELF_CHECK (data[2] == test.after[1]);
+      SELF_CHECK (data[3] == 0x5a);
+    }
+
+  /* A 32-bit field that starts and ends partway through a byte.  */
+  for (auto order : {floatformat_big, floatformat_little})
+    {
+      unsigned char data[] = {0x12, 0xa5, 0xa5, 0xa5, 0xa5, 0xa5, 0x34};
+      unsigned char expected[] = {0xaf, 0xed, 0xcb, 0xa9, 0x85};
+
+      if (order == floatformat_little)
+	std::reverse (expected, expected + sizeof (expected));
+
+      put_field (data + 1, order, 40, 4, 32, 0xfedcba98UL);
+
+      SELF_CHECK (data[0] == 0x12);
+      SELF_CHECK (std::equal (expected, expected + sizeof (expected),
+			      data + 1));
+      SELF_CHECK (data[6] == 0x34);
+    }
+}
+
+} /* namespace selftests */
+#endif /* GDB_SELF_TEST */
+
+INIT_GDB_FILE (target_float)
+{
+#if GDB_SELF_TEST
+  selftests::register_test ("target-float-put-field",
+			   selftests::put_field_test);
+#endif
+}
-- 
2.34.1


^ permalink raw reply	[flat|nested] 6+ messages in thread

* [PATCH v5 2/5] gdb: Preserve subnormal values in target floating-point operations
  2026-11-12 18:52 [PATCH v5 0/5] gdb: Fix target floating-point encoding and signed-zero negation Robert Dubner
  2026-11-12 18:52 ` [PATCH v5 1/5] gdb: Preserve neighboring bits when writing floating-point fields Robert Dubner
@ 2026-11-12 18:52 ` Robert Dubner
  2026-11-12 18:52 ` [PATCH v5 3/5] gdb: Preserve signed zero in MPFR target conversions Robert Dubner
                   ` (2 subsequent siblings)
  4 siblings, 0 replies; 6+ messages in thread
From: Robert Dubner @ 2026-11-12 18:52 UTC (permalink / raw)
  To: gdb-patches; +Cc: stephan.rohr

The MPFR encoder can flush representable subnormal values to zero or
encode their significands incorrectly.

Encode subnormals with a zero exponent field and align their fractions
to the minimum normal exponent.  Discard the implicit leading bit only
for normal values.

Carry MPFR's ternary results through parsing, conversions, and arithmetic
to avoid double rounding.  Temporarily adjust the minimum exponent while
rounding, restoring it afterward.  Preserve flush-to-zero behavior for
formats without subnormal support.

Explain the subnormal boundary, minimum-exponent calculation, and
significand scaling.

Add unit tests covering both byte orders, exact subnormals, rounding
boundaries, narrowing conversions, arithmetic, explicit integer bits,
and restoration of MPFR's exponent range.

Reviewed-By: Rohr, Stephan <stephan.rohr@intel.com>
Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=34927
---
 gdb/target-float.c | 318 +++++++++++++++++++++++++++++++++++++++------
 1 file changed, 281 insertions(+), 37 deletions(-)

diff --git a/gdb/target-float.c b/gdb/target-float.c
index 89a95067f2f..a267330d192 100644
--- a/gdb/target-float.c
+++ b/gdb/target-float.c
@@ -21,8 +21,13 @@
 #include "floatformat.h"
 #include "target-float.h"
 #include "gdbarch.h"
+#include "gdbsupport/scope-exit.h"
 #include "gdbsupport/selftest.h"
 
+#if GDB_SELF_TEST
+#include "arch-utils.h"
+#endif
+
 /* Target floating-point operations.
 
    We provide multiple implementations of those operations, which differ
@@ -1219,10 +1224,12 @@ class mpfr_float_ops : public target_float_ops
   void from_target (const struct type *type,
 		const gdb_byte *from, gdb_mpfr &to) const;
 
+  /* INEXACT is the MPFR ternary result of the computation producing FROM.
+     Carry it into subnormal rounding to avoid rounding twice.  */
   void to_target (const struct type *type,
-		  const gdb_mpfr &from, gdb_byte *to) const;
+		  const gdb_mpfr &from, gdb_byte *to, int inexact = 0) const;
   void to_target (const struct floatformat *fmt,
-		  const gdb_mpfr &from, gdb_byte *to) const;
+		  const gdb_mpfr &from, gdb_byte *to, int inexact = 0) const;
 };
 
 
@@ -1345,12 +1352,14 @@ mpfr_float_ops::from_target (const struct type *type,
 
 void
 mpfr_float_ops::to_target (const struct floatformat *fmt,
-			   const gdb_mpfr &from, gdb_byte *orig_to) const
+			   const gdb_mpfr &from, gdb_byte *orig_to,
+			   int inexact) const
 {
   unsigned char *to = orig_to;
   mpfr_exp_t exponent;
   unsigned int mant_bits, mant_off;
   int mant_bits_left;
+  bool subnormal;
   enum floatformat_byteorders order = fmt->byteorder;
   unsigned char newto[FLOATFORMAT_LARGEST_BYTES];
 
@@ -1403,8 +1412,37 @@ mpfr_float_ops::to_target (const struct floatformat *fmt,
     {
       put_field (to, order, fmt->totalsize, fmt->sign_start, 1, 1);
       mpfr_neg (tmp.val, tmp.val, MPFR_RNDN);
+      inexact = -inexact;
     }
 
+  /* MPFR represents a nonzero finite value as M * 2^E, where
+     0.5 <= abs (M) < 1.  The smallest normal target value is
+     2^(1 - exp_bias), so its MPFR exponent is 2 - exp_bias.
+     Smaller exponents (E + exp_bias <= 1) require subnormal rounding.
+     Formats without an infinity/NaN exponent do not support subnormals.  */
+  if (!mpfr_inf_p (tmp.val) && fmt->exp_nan != 0
+      && mpfr_get_exp (tmp.val) + fmt->exp_bias <= 1)
+    {
+      mpfr_exp_t saved_emin = mpfr_get_emin ();
+      SCOPE_EXIT
+	{
+	  mpfr_set_emin (saved_emin);
+	};
+
+      /* With precision P, the least subnormal is
+	 2^(1 - exp_bias - (P - 1)).  MPFR's exponent is one greater
+	 than the power of two, giving emin = 3 - exp_bias - P.
+	 Restrict the range only while rounding: the encoding below needs
+	 intermediates outside the target's range (e.g. for binary16).
+	 Use the operation's ternary result to avoid double rounding.  */
+      mpfr_set_emin (3 - fmt->exp_bias - floatformat_precision (fmt));
+      inexact = mpfr_check_range (tmp.val, inexact, MPFR_RNDN);
+      mpfr_subnormalize (tmp.val, inexact, MPFR_RNDN);
+    }
+
+  if (mpfr_zero_p (tmp.val))
+    goto finalize_byteorder;
+
   if (mpfr_inf_p (tmp.val))		/* Result is Infinity.  */
     {
       /* Infinity exponent is same as NaN's.  */
@@ -1418,14 +1456,28 @@ mpfr_float_ops::to_target (const struct floatformat *fmt,
 
   mpfr_frexp (&exponent, tmp.val, tmp.val, MPFR_RNDN);
 
-  if (exponent + fmt->exp_bias <= 0)
-    {
-      /* The value is too small to be expressed in the destination
-	 type (not enough bits in the exponent.  Treat as 0.  */
-      put_field (to, order, fmt->totalsize, fmt->exp_start,
-		 fmt->exp_len, 0);
-      put_field (to, order, fmt->totalsize, fmt->man_start,
-		 fmt->man_len, 0);
+  /* Test to see if the value is subnormal after it was rounded.  For example,
+     a value halfway between the largest subnormal and the smallest normal
+     tests as subnormal above, but after rounding will test as normal here.
+     So this second test has to be done.  */
+  subnormal = fmt->exp_nan != 0 && exponent + fmt->exp_bias <= 1;
+  if (subnormal)
+    {
+      /* Subnormals use the minimum normal exponent, but have no leading
+	 one.  Scale the fraction returned by mpfr_frexp to that exponent,
+	 leaving the leading zero explicit, even for formats with an
+	 implicit integer bit.  The loop below extracts successive 32-bit
+	 chunks of this fraction.  An explicit integer bit occupies its
+	 first bit, so shift one place further right for those formats.  */
+      mpfr_mul_2si (tmp.val, tmp.val,
+		    exponent + fmt->exp_bias
+		    - (fmt->intbit == floatformat_intbit_no ? 1 : 2),
+		    MPFR_RNDN);
+    }
+  else if (exponent + fmt->exp_bias <= 0)
+    {
+      /* Formats without subnormals flush values that are too small to
+	 represent to zero.  The exponent and mantissa are already zero.  */
       goto finalize_byteorder;
     }
 
@@ -1441,7 +1493,7 @@ mpfr_float_ops::to_target (const struct floatformat *fmt,
     }
 
   put_field (to, order, fmt->totalsize, fmt->exp_start, fmt->exp_len,
-	     exponent + fmt->exp_bias - 1);
+	     subnormal ? 0 : exponent + fmt->exp_bias - 1);
 
   mant_bits_left = fmt->man_len;
   mant_off = fmt->man_start;
@@ -1455,11 +1507,8 @@ mpfr_float_ops::to_target (const struct floatformat *fmt,
       mant_long = mpfr_get_ui (tmp.val, MPFR_RNDZ) & 0xffffffffL;
       mpfr_sub_ui (tmp.val, tmp.val, mant_long, MPFR_RNDZ);
 
-      /* If the integer bit is implicit, then we need to discard it.
-	 If we are discarding a zero, we should be (but are not) creating
-	 a denormalized number which means adjusting the exponent
-	 (I think).  */
-      if (mant_bits_left == fmt->man_len
+      /* Only normal values have an implicit leading one to discard.  */
+      if (!subnormal && mant_bits_left == fmt->man_len
 	  && fmt->intbit == floatformat_intbit_no)
 	{
 	  mant_long <<= 1;
@@ -1496,12 +1545,13 @@ mpfr_float_ops::to_target (const struct floatformat *fmt,
 
 void
 mpfr_float_ops::to_target (const struct type *type,
-			   const gdb_mpfr &from, gdb_byte *to) const
+			   const gdb_mpfr &from, gdb_byte *to,
+			   int inexact) const
 {
   /* Ensure possible padding bytes in the target buffer are zeroed out.  */
   memset (to, 0, type->length ());
 
-  to_target (floatformat_from_type (type), from, to);
+  to_target (floatformat_from_type (type), from, to, inexact);
 }
 
 /* Convert the byte-stream ADDR, interpreted as floating-point type TYPE,
@@ -1559,13 +1609,13 @@ mpfr_float_ops::from_string (gdb_byte *addr,
   gdb_mpfr tmp (type);
 
   char *endptr;
-  mpfr_strtofr (tmp.val, in.c_str (), &endptr, 0, MPFR_RNDN);
+  int inexact = mpfr_strtofr (tmp.val, in.c_str (), &endptr, 0, MPFR_RNDN);
 
   /* We only accept the whole string.  */
   if (*endptr)
     return false;
 
-  to_target (type, tmp, addr);
+  to_target (type, tmp, addr, inexact);
   return true;
 }
 
@@ -1588,8 +1638,8 @@ mpfr_float_ops::from_longest (gdb_byte *addr,
 			      LONGEST val) const
 {
   gdb_mpfr tmp (type);
-  mpfr_set_sj (tmp.val, val, MPFR_RNDN);
-  to_target (type, tmp, addr);
+  int inexact = mpfr_set_sj (tmp.val, val, MPFR_RNDN);
+  to_target (type, tmp, addr, inexact);
 }
 
 /* Convert unsigned integer VAL to a target floating-number of type TYPE
@@ -1600,8 +1650,8 @@ mpfr_float_ops::from_ulongest (gdb_byte *addr,
 			       ULONGEST val) const
 {
   gdb_mpfr tmp (type);
-  mpfr_set_uj (tmp.val, val, MPFR_RNDN);
-  to_target (type, tmp, addr);
+  int inexact = mpfr_set_uj (tmp.val, val, MPFR_RNDN);
+  to_target (type, tmp, addr, inexact);
 }
 
 /* Convert the byte-stream ADDR, interpreted as floating-point type TYPE,
@@ -1623,8 +1673,8 @@ mpfr_float_ops::from_host_double (gdb_byte *addr,
 				  double val) const
 {
   gdb_mpfr tmp (type);
-  mpfr_set_d (tmp.val, val, MPFR_RNDN);
-  to_target (type, tmp, addr);
+  int inexact = mpfr_set_d (tmp.val, val, MPFR_RNDN);
+  to_target (type, tmp, addr, inexact);
 }
 
 /* Convert a floating-point number of type FROM_TYPE from the target
@@ -1638,8 +1688,8 @@ mpfr_float_ops::convert (const gdb_byte *from,
 {
   gdb_mpfr from_tmp (from_type), to_tmp (to_type);
   from_target (from_type, from, from_tmp);
-  mpfr_set (to_tmp.val, from_tmp.val, MPFR_RNDN);
-  to_target (to_type, to_tmp, to);
+  int inexact = mpfr_set (to_tmp.val, from_tmp.val, MPFR_RNDN);
+  to_target (to_type, to_tmp, to, inexact);
 }
 
 /* Perform the binary operation indicated by OPCODE, using as operands the
@@ -1657,34 +1707,35 @@ mpfr_float_ops::binop (enum exp_opcode op,
   from_target (type_x, x, x_tmp);
   from_target (type_y, y, y_tmp);
 
+  int inexact;
   switch (op)
     {
       case BINOP_ADD:
-	mpfr_add (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
+	inexact = mpfr_add (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
 	break;
 
       case BINOP_SUB:
-	mpfr_sub (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
+	inexact = mpfr_sub (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
 	break;
 
       case BINOP_MUL:
-	mpfr_mul (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
+	inexact = mpfr_mul (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
 	break;
 
       case BINOP_DIV:
-	mpfr_div (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
+	inexact = mpfr_div (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
 	break;
 
       case BINOP_EXP:
-	mpfr_pow (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
+	inexact = mpfr_pow (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
 	break;
 
       case BINOP_MIN:
-	mpfr_min (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
+	inexact = mpfr_min (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
 	break;
 
       case BINOP_MAX:
-	mpfr_max (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
+	inexact = mpfr_max (tmp.val, x_tmp.val, y_tmp.val, MPFR_RNDN);
 	break;
 
       default:
@@ -1692,7 +1743,7 @@ mpfr_float_ops::binop (enum exp_opcode op,
 	break;
     }
 
-  to_target (type_res, tmp, res);
+  to_target (type_res, tmp, res, inexact);
 }
 
 /* Compare the two target byte streams X and Y, interpreted as floating-point
@@ -2576,6 +2627,193 @@ put_field_test ()
       SELF_CHECK (data[6] == 0x34);
     }
 }
+/* Exercise the MPFR implementation directly, independently of the host's
+   floating-point formats.  Each pair contains big- and little-endian
+   forms.  */
+
+static const floatformat *const subnormal_formats[][2] =
+  {
+    {&floatformat_ieee_half_big, &floatformat_ieee_half_little},
+    {&floatformat_ieee_single_big, &floatformat_ieee_single_little},
+    {&floatformat_ieee_double_big, &floatformat_ieee_double_little},
+    {&floatformat_ieee_quad_big, &floatformat_ieee_quad_little}
+  };
+
+static type *
+subnormal_type (const floatformat *fmt)
+{
+  /* Supply FMT in both slots so it can be selected independently of the
+     architecture's byte order.  init_float_type retains only that format.  */
+  const floatformat *pair[] = {fmt, fmt};
+  type_allocator alloc (get_current_arch ());
+  return init_float_type (alloc, -1, "selftest_float", pair, BFD_ENDIAN_BIG);
+}
+
+/* Encode integer BITS independently of the floating-point encoder.  */
+
+static std::vector<gdb_byte>
+subnormal_bytes (const gdb_mpz &bits, const type *ftype)
+{
+  std::vector<gdb_byte> bytes (ftype->length ());
+  bfd_endian order
+	= (floatformat_from_type (ftype)->byteorder == floatformat_big
+	   ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
+  bits.write (bytes, order, true);
+  return bytes;
+}
+
+/* Spell COEFFICIENT * 2^EXPONENT exactly, without host floating-point
+   math.  */
+
+static std::string
+subnormal_string (const gdb_mpz &coefficient, int exponent)
+{
+  return coefficient.hex () + "p" + std::to_string (exponent);
+}
+
+/* Check exact subnormals, text round trips, byte-order conversion, and the
+   boundary between normal and subnormal arithmetic.  */
+
+static void
+subnormal_test ()
+{
+  mpfr_float_ops ops;
+  for (const auto &formats : subnormal_formats)
+    for (int endian = 0; endian < 2; ++endian)
+      {
+	const floatformat *fmt = formats[endian];
+	type *ftype = subnormal_type (fmt);
+	type *opposite = subnormal_type (formats[1 - endian]);
+	int quantum = 1 - fmt->exp_bias - (int) fmt->man_len;
+	gdb_mpz normal = gdb_mpz (1) << fmt->man_len;
+	gdb_mpz sign = gdb_mpz (1) << (fmt->totalsize - 1);
+	for (const gdb_mpz &magnitude : {gdb_mpz (1), gdb_mpz (2),
+				       normal - gdb_mpz (1), normal})
+	  for (bool negative : {false, true})
+	    {
+	      gdb_mpz bits = negative ? magnitude | sign : magnitude;
+	      auto expected = subnormal_bytes (bits, ftype);
+	      std::vector<gdb_byte> actual (ftype->length ());
+	      std::string text = subnormal_string (magnitude, quantum);
+	      if (negative)
+		text.insert (0, "-");
+	      SELF_CHECK (ops.from_string (actual.data (), ftype, text));
+	      SELF_CHECK (actual == expected);
+	      text = ops.to_string (expected.data (), ftype, nullptr);
+	      SELF_CHECK (ops.from_string (actual.data (), ftype, text));
+	      SELF_CHECK (actual == expected);
+	      ops.convert (expected.data (), ftype, actual.data (), opposite);
+	      SELF_CHECK (actual == subnormal_bytes (bits, opposite));
+	    }
+
+	auto least = subnormal_bytes (gdb_mpz (1), ftype);
+	auto largest = subnormal_bytes (normal - gdb_mpz (1), ftype);
+	auto minimum = subnormal_bytes (normal, ftype);
+	std::vector<gdb_byte> actual (ftype->length ());
+	ops.binop (BINOP_SUB, minimum.data (), ftype, least.data (), ftype,
+		   actual.data (), ftype);
+	SELF_CHECK (actual == largest);
+	ops.binop (BINOP_ADD, largest.data (), ftype, least.data (), ftype,
+		   actual.data (), ftype);
+	SELF_CHECK (actual == minimum);
+      }
+}
+
+/* Test halfway values and both sides of each tie, including digits lost by
+   rounding to normal precision before subnormal rounding.  Expected results
+   follow round-to-nearest, ties-to-even, without using MPFR as an oracle.  */
+
+static void
+subnormal_rounding_test ()
+{
+  mpfr_float_ops ops;
+  mpfr_exp_t saved_emin = mpfr_get_emin (), saved_emax = mpfr_get_emax ();
+  type *wide = subnormal_type (&floatformat_ieee_quad_big);
+  for (const auto &formats : subnormal_formats)
+    for (const floatformat *fmt : formats)
+      {
+	type *ftype = subnormal_type (fmt);
+	int quantum = 1 - fmt->exp_bias - (int) fmt->man_len;
+	int tail = fmt->man_len + 9;
+	gdb_mpz normal = gdb_mpz (1) << fmt->man_len;
+	gdb_mpz sign = gdb_mpz (1) << (fmt->totalsize - 1);
+	for (const gdb_mpz &lower : {gdb_mpz (0), gdb_mpz (1), gdb_mpz (2),
+				   normal - gdb_mpz (1)})
+	  for (int side : {-1, 0, 1})
+	    for (bool negative : {false, true})
+	      {
+		gdb_mpz coefficient = ((lower * gdb_mpz (2) + 1) << (tail - 1))
+				       + gdb_mpz (side);
+		gdb_mpz expected = lower;
+		if (side > 0 || (side == 0 && (lower & gdb_mpz (1)) == 1))
+		  expected += 1;
+		if (negative)
+		  expected = expected | sign;
+		auto bytes = subnormal_bytes (expected, ftype);
+		std::string text
+		  = subnormal_string (coefficient, quantum - tail);
+		if (negative)
+		  text.insert (0, "-");
+		std::vector<gdb_byte> actual (ftype->length ());
+		SELF_CHECK (ops.from_string (actual.data (), ftype, text));
+		SELF_CHECK (actual == bytes);
+
+		/* Binary128 represents these binary16/32/64 cases exactly.
+		   Check the ternary result from narrowing and each operation,
+		   as well as parsing directly at the destination
+		   precision.  */
+		if (fmt->man_len < floatformat_ieee_quad_big.man_len)
+		  {
+		    std::vector<gdb_byte> source (wide->length ());
+		    SELF_CHECK (ops.from_string (source.data (), wide, text));
+		    ops.convert (source.data (), wide, actual.data (), ftype);
+		    SELF_CHECK (actual == bytes);
+		    for (exp_opcode op : {BINOP_ADD, BINOP_SUB, BINOP_MUL,
+					  BINOP_DIV, BINOP_EXP, BINOP_MIN,
+					  BINOP_MAX})
+		      {
+			std::vector<gdb_byte> right (wide->length ());
+			LONGEST rhs = op == BINOP_ADD || op == BINOP_SUB ? 0
+				      : op == BINOP_MAX ? -1 : 1;
+			ops.from_longest (right.data (), wide, rhs);
+			ops.binop (op, source.data (), wide, right.data (),
+				   wide, actual.data (), ftype);
+			SELF_CHECK (actual == bytes);
+		      }
+		  }
+		SELF_CHECK (mpfr_get_emin () == saved_emin);
+		SELF_CHECK (mpfr_get_emax () == saved_emax);
+	      }
+      }
+}
+
+/* Also check encoding with explicit integer bits and preserve the existing
+   flush-to-zero policy of formats without subnormal support.  */
+
+static void
+subnormal_other_formats_test ()
+{
+  mpfr_float_ops ops;
+  {
+    const floatformat *fmt = &floatformat_i387_ext;
+    type *ftype = subnormal_type (fmt);
+    std::vector<gdb_byte> actual (ftype->length ());
+    std::vector<gdb_byte> expected (ftype->length ());
+    expected[0] = 1;
+    int quantum = 2 - fmt->exp_bias - floatformat_precision (fmt);
+    SELF_CHECK (ops.from_string (actual.data (), ftype,
+				 subnormal_string (gdb_mpz (1), quantum)));
+    SELF_CHECK (actual == expected);
+  }
+
+  type *ftype = subnormal_type (&floatformat_vax_f);
+  std::vector<gdb_byte> actual (ftype->length ());
+  std::vector<gdb_byte> zero (ftype->length ());
+  SELF_CHECK (ops.from_string (actual.data (), ftype, "0x1p-200"));
+  SELF_CHECK (actual == zero);
+  SELF_CHECK (ops.from_string (actual.data (), ftype, "0.125"));
+  SELF_CHECK (actual == std::vector<gdb_byte> ({0, 0x3f, 0, 0}));
+}
 
 } /* namespace selftests */
 #endif /* GDB_SELF_TEST */
@@ -2585,5 +2823,11 @@ INIT_GDB_FILE (target_float)
 #if GDB_SELF_TEST
   selftests::register_test ("target-float-put-field",
 			   selftests::put_field_test);
+  selftests::register_test ("target-float-subnormal",
+			   selftests::subnormal_test);
+  selftests::register_test ("target-float-subnormal-rounding",
+			   selftests::subnormal_rounding_test);
+  selftests::register_test ("target-float-subnormal-other-formats",
+			   selftests::subnormal_other_formats_test);
 #endif
 }
-- 
2.34.1


^ permalink raw reply	[flat|nested] 6+ messages in thread

* [PATCH v5 3/5] gdb: Preserve signed zero in MPFR target conversions
  2026-11-12 18:52 [PATCH v5 0/5] gdb: Fix target floating-point encoding and signed-zero negation Robert Dubner
  2026-11-12 18:52 ` [PATCH v5 1/5] gdb: Preserve neighboring bits when writing floating-point fields Robert Dubner
  2026-11-12 18:52 ` [PATCH v5 2/5] gdb: Preserve subnormal values in target floating-point operations Robert Dubner
@ 2026-11-12 18:52 ` Robert Dubner
  2026-11-12 18:52 ` [PATCH v5 4/5] gdb: Preserve signed zero in floating-point unary negation Robert Dubner
  2026-11-12 18:52 ` [PATCH v5 5/5] gdb: Avoid oversized shifts when writing floating-point fields Robert Dubner
  4 siblings, 0 replies; 6+ messages in thread
From: Robert Dubner @ 2026-11-12 18:52 UTC (permalink / raw)
  To: gdb-patches; +Cc: stephan.rohr

The MPFR encoder returns for zero before examining its sign, turning
negative zero into positive zero during conversions and arithmetic.

Process the sign before returning for zero, using mpfr_signbit to
recognize negative zero.  Retain all-zero encodings for formats without
signed-zero support.

Add unit tests in target-float.c covering both signs of zero through
parsing, printing, host conversion, arithmetic, and target-format
conversion across floating-point formats and byte orders.

Reviewed-By: Rohr, Stephan <stephan.rohr@intel.com>
Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=34927
---
 gdb/target-float.c | 123 +++++++++++++++++++++++++++++++++++++++++++--
 1 file changed, 118 insertions(+), 5 deletions(-)

diff --git a/gdb/target-float.c b/gdb/target-float.c
index a267330d192..1d7fe55fa3b 100644
--- a/gdb/target-float.c
+++ b/gdb/target-float.c
@@ -1391,9 +1391,6 @@ mpfr_float_ops::to_target (const struct floatformat *fmt,
 
   gdb_mpfr tmp (from);
 
-  if (mpfr_zero_p (from.val))
-    goto finalize_byteorder;	/* Result is zero */
-
   mpfr_set (tmp.val, from.val, MPFR_RNDN);
 
   if (mpfr_nan_p (tmp.val))	/* Result is NaN */
@@ -1408,13 +1405,19 @@ mpfr_float_ops::to_target (const struct floatformat *fmt,
     }
 
   /* If negative, set the sign bit.  */
-  if (mpfr_sgn (tmp.val) < 0)
+  if (mpfr_signbit (tmp.val))
     {
-      put_field (to, order, fmt->totalsize, fmt->sign_start, 1, 1);
+      /* Keep zero encodings unchanged for formats that do not have
+	 signed zero, e.g. VAX.  */
+      if (!mpfr_zero_p (tmp.val) || fmt->exp_nan != 0)
+	put_field (to, order, fmt->totalsize, fmt->sign_start, 1, 1);
       mpfr_neg (tmp.val, tmp.val, MPFR_RNDN);
       inexact = -inexact;
     }
 
+  if (mpfr_zero_p (tmp.val))
+    goto finalize_byteorder;
+
   /* MPFR represents a nonzero finite value as M * 2^E, where
      0.5 <= abs (M) < 1.  The smallest normal target value is
      2^(1 - exp_bias), so its MPFR exponent is 2 - exp_bias.
@@ -1440,6 +1443,8 @@ mpfr_float_ops::to_target (const struct floatformat *fmt,
       mpfr_subnormalize (tmp.val, inexact, MPFR_RNDN);
     }
 
+  /* Check again for zero because mpfr_check_range and mpfr_subnormalize can
+     turn a non-zero input into zero.  */
   if (mpfr_zero_p (tmp.val))
     goto finalize_byteorder;
 
@@ -2815,6 +2820,112 @@ subnormal_other_formats_test ()
   SELF_CHECK (actual == std::vector<gdb_byte> ({0, 0x3f, 0, 0}));
 }
 
+/* Exercise the MPFR backend directly so these checks do not depend on the
+   host's floating-point formats.  Check both signs of zero through parsing,
+   host conversion, arithmetic, and conversion between target formats.  */
+
+static void
+signed_zero_test ()
+{
+  struct test_case
+  {
+    const floatformat *fmt;
+    unsigned int sign_byte;
+  };
+
+  static const test_case tests[] =
+    {
+      {&floatformat_ieee_half_big, 0},
+      {&floatformat_ieee_half_little, 1},
+      {&floatformat_ieee_single_big, 0},
+      {&floatformat_ieee_single_little, 3},
+      {&floatformat_ieee_double_big, 0},
+      {&floatformat_ieee_double_little, 7},
+      {&floatformat_ieee_quad_big, 0},
+      {&floatformat_ieee_quad_little, 15},
+      {&floatformat_i387_ext, 9},
+      {&floatformat_m68881_ext, 0},
+      {&floatformat_ieee_double_littlebyte_bigword, 3},
+      {&floatformat_ibm_long_double_big, 0},
+      {&floatformat_ibm_long_double_little, 7},
+      /* VAX has no signed zero.  Its negative-zero inputs must still
+	 produce the all-zero encoding.  */
+      {&floatformat_vax_f, 1}
+    };
+
+  type_allocator alloc (get_current_arch ());
+  std::vector<type *> types;
+  for (const test_case &test : tests)
+    {
+      const floatformat *pair[] = {test.fmt, test.fmt};
+      types.push_back (init_float_type (alloc, -1, "selftest_float", pair,
+				       BFD_ENDIAN_BIG));
+    }
+
+  mpfr_float_ops ops;
+  for (size_t i = 0; i < ARRAY_SIZE (tests); ++i)
+    {
+      type *ftype = types[i];
+      std::vector<gdb_byte> zero (ftype->length ());
+      std::vector<gdb_byte> one (ftype->length ());
+      ops.from_ulongest (one.data (), ftype, 1);
+      auto minus_one = one;
+      minus_one[tests[i].sign_byte] |= 0x80;
+
+      for (bool negative : {false, true})
+	{
+	  bool signed_negative = negative && tests[i].fmt->exp_nan != 0;
+	  auto expected = zero;
+	  if (signed_negative)
+	    expected[tests[i].sign_byte] = 0x80;
+	  std::vector<gdb_byte> actual (ftype->length (), 0xa5);
+
+	  SELF_CHECK (ops.from_string (actual.data (), ftype,
+				       negative ? "-0" : "0"));
+	  SELF_CHECK (actual == expected);
+	  ops.from_host_double (actual.data (), ftype, negative ? -0.0 : 0.0);
+	  SELF_CHECK (actual == expected);
+	  SELF_CHECK (std::signbit (ops.to_host_double (expected.data (),
+							ftype))
+		      == signed_negative);
+
+	  std::string text = ops.to_string (expected.data (), ftype, nullptr);
+	  SELF_CHECK (ops.from_string (actual.data (), ftype, text));
+	  SELF_CHECK (actual == expected);
+
+	  for (exp_opcode op : {BINOP_MUL, BINOP_DIV})
+	    {
+	      ops.binop (op, expected.data (), ftype, one.data (), ftype,
+			 actual.data (), ftype);
+	      SELF_CHECK (actual == expected);
+	    }
+	  ops.binop (BINOP_ADD, expected.data (), ftype,
+		     expected.data (), ftype, actual.data (), ftype);
+	  SELF_CHECK (actual == expected);
+
+	  for (size_t j = 0; j < ARRAY_SIZE (tests); ++j)
+	    {
+	      std::vector<gdb_byte> converted (types[j]->length (), 0xa5);
+	      std::vector<gdb_byte> wanted (types[j]->length ());
+	      if (signed_negative && tests[j].fmt->exp_nan != 0)
+		wanted[tests[j].sign_byte] = 0x80;
+	      ops.convert (expected.data (), ftype,
+			   converted.data (), types[j]);
+	      SELF_CHECK (converted == wanted);
+	    }
+	}
+
+      /* Produce negative zero from nonnegative zero, without relying on
+	 the parser to have preserved a negative-zero input.  Construct -1
+	 from its sign bit to avoid depending on other encoder fixes.  */
+      ops.binop (BINOP_MUL, zero.data (), ftype, minus_one.data (), ftype,
+		 one.data (), ftype);
+      if (tests[i].fmt->exp_nan != 0)
+	zero[tests[i].sign_byte] = 0x80;
+      SELF_CHECK (one == zero);
+    }
+}
+
 } /* namespace selftests */
 #endif /* GDB_SELF_TEST */
 
@@ -2823,6 +2934,8 @@ INIT_GDB_FILE (target_float)
 #if GDB_SELF_TEST
   selftests::register_test ("target-float-put-field",
 			   selftests::put_field_test);
+  selftests::register_test ("target-float-signed-zero",
+			   selftests::signed_zero_test);
   selftests::register_test ("target-float-subnormal",
 			   selftests::subnormal_test);
   selftests::register_test ("target-float-subnormal-rounding",
-- 
2.34.1


^ permalink raw reply	[flat|nested] 6+ messages in thread

* [PATCH v5 4/5] gdb: Preserve signed zero in floating-point unary negation
  2026-11-12 18:52 [PATCH v5 0/5] gdb: Fix target floating-point encoding and signed-zero negation Robert Dubner
                   ` (2 preceding siblings ...)
  2026-11-12 18:52 ` [PATCH v5 3/5] gdb: Preserve signed zero in MPFR target conversions Robert Dubner
@ 2026-11-12 18:52 ` Robert Dubner
  2026-11-12 18:52 ` [PATCH v5 5/5] gdb: Avoid oversized shifts when writing floating-point fields Robert Dubner
  4 siblings, 0 replies; 6+ messages in thread
From: Robert Dubner @ 2026-11-12 18:52 UTC (permalink / raw)
  To: gdb-patches; +Cc: stephan.rohr

value_neg implements negation as zero minus the operand.  For positive
floating-point zero, this produces positive zero rather than negative
zero.

Multiply floating-point operands by -1 instead.  Preserve the existing
integer and fixed-point negation paths.

Add regression tests distinguishing integer -0 from floating-point -0.
and -.0, including assignments to float, double, and long double.  Also
cover negation of both zero signs, nested negation, nonzero values, and
integer controls.

Reviewed-By: Rohr, Stephan <stephan.rohr@intel.com>
Bug: https://sourceware.org/bugzilla/show_bug.cgi?id=34927
---
 gdb/testsuite/gdb.base/float-neg.c   | 38 +++++++++++++
 gdb/testsuite/gdb.base/float-neg.exp | 79 ++++++++++++++++++++++++++++
 gdb/valarith.c                       |  8 ++-
 3 files changed, 124 insertions(+), 1 deletion(-)
 create mode 100644 gdb/testsuite/gdb.base/float-neg.c
 create mode 100644 gdb/testsuite/gdb.base/float-neg.exp

diff --git a/gdb/testsuite/gdb.base/float-neg.c b/gdb/testsuite/gdb.base/float-neg.c
new file mode 100644
index 00000000000..e27b177fe8f
--- /dev/null
+++ b/gdb/testsuite/gdb.base/float-neg.c
@@ -0,0 +1,38 @@
+/* This test program is part of GDB, the GNU debugger.
+
+   Copyright 2026 Free Software Foundation, Inc.
+
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 3 of the License, or
+   (at your option) any later version.
+
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+
+   You should have received a copy of the GNU General Public License
+   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
+
+/* Compiler-initialized negative zero provides an input independent of
+   GDB's unary-negation implementation.  */
+double positive_zero = 0.0;
+double negative_zero = -0.0;
+float f = 1.0f;
+double d = 1.0;
+long double ld = 1.0L;
+#ifdef __FLT128_MAX__
+/* This variable is used for regression testing of assignment of -0.0 to a
+   128-bit floating point variable.  */
+_Float128 f128 = 1.0;
+int have_float128 = 1;
+#else
+int have_float128 = 0;
+#endif
+
+int
+main (void)
+{
+  return 0;
+}
diff --git a/gdb/testsuite/gdb.base/float-neg.exp b/gdb/testsuite/gdb.base/float-neg.exp
new file mode 100644
index 00000000000..f8b522d583b
--- /dev/null
+++ b/gdb/testsuite/gdb.base/float-neg.exp
@@ -0,0 +1,79 @@
+# Copyright 2026 Free Software Foundation, Inc.
+
+# This program is free software; you can redistribute it and/or modify
+# it under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with this program.  If not, see <http://www.gnu.org/licenses/>.
+
+# Check that floating-point negation changes the sign of zero, while
+# integer -0 remains integer zero.
+
+standard_testfile
+
+if {![allow_float_test]} {
+    return
+}
+if {[prepare_for_testing "failed to prepare" $testfile $srcfile]} {
+    return
+}
+if {![runto_main]} {
+    return
+}
+
+# Do not require signed zero on targets whose floating-point format lacks it.
+set have_signed_zero 0
+gdb_test_multiple "print negative_zero" "target supports signed zero" {
+    -re -wrap " = -0" {
+	pass $gdb_test_name
+	set have_signed_zero 1
+    }
+    -re -wrap " = 0" {
+	unsupported $gdb_test_name
+    }
+}
+if {!$have_signed_zero} {
+    return
+}
+
+set variables {f d ld}
+if {[get_integer_valueof "have_float128" 0]} {
+    lappend variables f128
+}
+
+foreach {literal expected literal_type negated} {
+    -0   0 int    -0
+    -0. -0 double  0
+    -.0 -0 double  0
+} {
+    with_test_prefix "literal $literal" {
+	gdb_test "whatis $literal" "type = $literal_type"
+	gdb_test "print $literal" " = $expected"
+	foreach var $variables {
+	    with_test_prefix $var {
+		gdb_test "print $var = $literal" " = $expected" "assign"
+		gdb_test "print $var" " = $expected" "read back"
+		gdb_test "print -$var" " = $negated" "negate"
+	    }
+	}
+    }
+}
+
+gdb_test "print -positive_zero" " = -0"
+gdb_test "print -negative_zero" " = 0"
+gdb_test "print -(-negative_zero)" " = -0"
+gdb_test "print -1.5" { = -1\.5}
+gdb_test "print -(-1.5)" { = 1\.5}
+
+# Integer negation, including unsigned arithmetic, retains its behavior.
+gdb_test "print -5" " = -5"
+gdb_test "print -(-5)" " = 5"
+gdb_test "print -0u" " = 0"
+gdb_test "print -5u == 0u - 5u" " = 1"
diff --git a/gdb/valarith.c b/gdb/valarith.c
index 62a35841f1f..0052ed269b2 100644
--- a/gdb/valarith.c
+++ b/gdb/valarith.c
@@ -1743,8 +1743,14 @@ value_neg (struct value *arg1)
   arg1 = coerce_ref (arg1);
   type = check_typedef (arg1->type ());
 
-  if (is_integral_type (type) || is_floating_type (type))
+  if (is_integral_type (type))
     return value_binop (value_from_longest (type, 0), arg1, BINOP_SUB);
+  else if (is_floating_type (type))
+    {
+      /* Subtracting from zero does not change the sign of positive zero.
+	 Multiplication by -1 negates both signs of floating-point zero.  */
+      return value_binop (arg1, value_from_longest (type, -1), BINOP_MUL);
+    }
   else if (is_fixed_point_type (type))
     return value_binop (value::zero (type, not_lval), arg1, BINOP_SUB);
   else if (type->code () == TYPE_CODE_ARRAY && type->is_vector ())
-- 
2.34.1


^ permalink raw reply	[flat|nested] 6+ messages in thread

* [PATCH v5 5/5] gdb: Avoid oversized shifts when writing floating-point fields
  2026-11-12 18:52 [PATCH v5 0/5] gdb: Fix target floating-point encoding and signed-zero negation Robert Dubner
                   ` (3 preceding siblings ...)
  2026-11-12 18:52 ` [PATCH v5 4/5] gdb: Preserve signed zero in floating-point unary negation Robert Dubner
@ 2026-11-12 18:52 ` Robert Dubner
  4 siblings, 0 replies; 6+ messages in thread
From: Robert Dubner @ 2026-11-12 18:52 UTC (permalink / raw)
  To: gdb-patches; +Cc: stephan.rohr

put_field can write fields wider than unsigned long, such as the
112-bit binary128 fraction field used when encoding infinities and
NaNs. Its loop can shift stuff_to_put by its width or more, which is
undefined even when the value is zero.

Use zero once the shift reaches the width of unsigned long.  Apply
the guarded value to both full-byte and partial-byte writes,
preserving the existing neighboring-bit masks.

Add unit tests in target-float.c covering wide fields, alignment,
both byte orders, neighboring bits, buffer guards, and binary128
infinity and NaN encodings.

Reviewed-By: Rohr, Stephan <stephan.rohr@intel.com>
---
 gdb/target-float.c | 104 ++++++++++++++++++++++++++++++++++++++++++---
 1 file changed, 97 insertions(+), 7 deletions(-)

diff --git a/gdb/target-float.c b/gdb/target-float.c
index 1d7fe55fa3b..e21e905f038 100644
--- a/gdb/target-float.c
+++ b/gdb/target-float.c
@@ -245,6 +245,7 @@ put_field (unsigned char *data, enum floatformat_byteorders order,
 {
   unsigned int cur_byte;
   int cur_bitshift;
+  constexpr int value_bits = sizeof (stuff_to_put) * FLOATFORMAT_CHAR_BIT;
 
   /* Caller must byte-swap words before calling this routine.  */
   gdb_assert (order == floatformat_little || order == floatformat_big);
@@ -282,17 +283,21 @@ put_field (unsigned char *data, enum floatformat_byteorders order,
   /* Move towards the most significant part of the field.  */
   while (cur_bitshift < len)
     {
+      /* Fields such as a binary128 fraction can be wider than STUFF_TO_PUT.
+	 Zero-extend rather than shifting by the width of unsigned long or
+	 more.  */
+      unsigned long shifted
+	= cur_bitshift < value_bits ? stuff_to_put >> cur_bitshift : 0;
       if (len - cur_bitshift < FLOATFORMAT_CHAR_BIT)
 	{
 	  /* This is the last byte.  Make sure we don't OR in extra high-order
 	     bits when STUFF_TO_PUT violates the LEN restriction.  */
 	  unsigned int mask = (1U << (len - cur_bitshift)) - 1;
 	  *(data + cur_byte) &= ~mask;
-	  *(data + cur_byte) |= (stuff_to_put >> cur_bitshift) & mask;
+	  *(data + cur_byte) |= shifted & mask;
 	}
       else
-	*(data + cur_byte) = ((stuff_to_put >> cur_bitshift)
-			      & ((1 << FLOATFORMAT_CHAR_BIT) - 1));
+	*(data + cur_byte) = shifted & ((1 << FLOATFORMAT_CHAR_BIT) - 1);
       cur_bitshift += FLOATFORMAT_CHAR_BIT;
       if (order == floatformat_little)
 	++cur_byte;
@@ -2853,13 +2858,10 @@ signed_zero_test ()
       {&floatformat_vax_f, 1}
     };
 
-  type_allocator alloc (get_current_arch ());
   std::vector<type *> types;
   for (const test_case &test : tests)
     {
-      const floatformat *pair[] = {test.fmt, test.fmt};
-      types.push_back (init_float_type (alloc, -1, "selftest_float", pair,
-				       BFD_ENDIAN_BIG));
+      types.push_back (subnormal_type(test.fmt));
     }
 
   mpfr_float_ops ops;
@@ -2926,6 +2928,90 @@ signed_zero_test ()
     }
 }
 
+/* Check zero extension when a field is wider than unsigned long.  Build
+   expected bytes with arbitrary-precision integer operations, independently
+   of put_field and get_field, and preserve neighboring bits and guards.  */
+
+static void
+put_field_wide_test ()
+{
+  constexpr unsigned int value_bits
+    = sizeof (unsigned long) * FLOATFORMAT_CHAR_BIT;
+  struct test_case
+  {
+    unsigned int start;
+    unsigned int len;
+  };
+  const test_case tests[] =
+    {
+      {0, 128},
+      {16, 112},                /* The binary128 fraction field.  */
+      {15, 112},
+      {12, 113},
+      {8, value_bits},
+      {7, value_bits},
+      {7, value_bits + 1},
+      {0, value_bits + 8}
+    };
+
+  for (auto order : {floatformat_big, floatformat_little})
+    for (const test_case &test : tests)
+      for (unsigned long value : {0UL, 1UL, 0xa5UL, ~0UL,
+				  1UL << (value_bits - 1)})
+	for (gdb_byte initial : {0x00, 0xa5, 0xff})
+	  {
+	    gdb_byte data[18];
+	    memset (data, initial, sizeof (data));
+	    data[0] = 0x3c;
+	    data[17] = 0xc3;
+	    std::vector<gdb_byte> expected (16, initial);
+	    bfd_endian byte_order = (order == floatformat_big
+				     ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
+	    unsigned int shift = 128 - test.start - test.len;
+	    gdb_mpz image;
+	    image.read (expected, byte_order, true);
+	    gdb_mpz mask = ((gdb_mpz (1) << test.len) - gdb_mpz (1)) << shift;
+	    mask.complement ();
+	    image = (image & mask) | (gdb_mpz (value) << shift);
+	    image.write (expected, byte_order, true);
+
+	    put_field (data + 1, order, 128, test.start, test.len, value);
+	    SELF_CHECK (data[0] == 0x3c);
+	    SELF_CHECK (std::equal (expected.begin (), expected.end (),
+				   data + 1));
+	    SELF_CHECK (data[17] == 0xc3);
+	  }
+}
+
+/* The MPFR encoder writes a complete binary128 fraction for infinities and
+   NaNs.  Exercise that caller as well as the field writer itself.  */
+
+static void
+wide_special_test ()
+{
+  mpfr_float_ops ops;
+  for (const floatformat *fmt : {&floatformat_ieee_quad_big,
+				&floatformat_ieee_quad_little})
+    {
+      type *ftype = subnormal_type(fmt);
+      bfd_endian order = (fmt->byteorder == floatformat_big
+			  ? BFD_ENDIAN_BIG : BFD_ENDIAN_LITTLE);
+      for (const char *text : {"inf", "-inf", "nan"})
+	{
+	  gdb_mpz bits = gdb_mpz (0x7fff) << 112;
+	  if (text[0] == '-')
+	    bits = bits | (gdb_mpz (1) << 127);
+	  else if (text[0] == 'n')
+	    bits += 1;
+	  std::vector<gdb_byte> expected (16);
+	  bits.write (expected, order, true);
+	  std::vector<gdb_byte> actual (16, 0xa5);
+	  SELF_CHECK (ops.from_string (actual.data (), ftype, text));
+	  SELF_CHECK (actual == expected);
+	}
+    }
+}
+
 } /* namespace selftests */
 #endif /* GDB_SELF_TEST */
 
@@ -2936,6 +3022,10 @@ INIT_GDB_FILE (target_float)
 			   selftests::put_field_test);
   selftests::register_test ("target-float-signed-zero",
 			   selftests::signed_zero_test);
+  selftests::register_test ("target-float-put-field-wide",
+			   selftests::put_field_wide_test);
+  selftests::register_test ("target-float-wide-specials",
+			   selftests::wide_special_test);
   selftests::register_test ("target-float-subnormal",
 			   selftests::subnormal_test);
   selftests::register_test ("target-float-subnormal-rounding",
-- 
2.34.1


^ permalink raw reply	[flat|nested] 6+ messages in thread

end of thread, other threads:[~2026-11-12 18:54 UTC | newest]

Thread overview: 6+ messages (download: mbox.gz / follow: Atom feed)
-- links below jump to the message on this page --
2026-11-12 18:52 [PATCH v5 0/5] gdb: Fix target floating-point encoding and signed-zero negation Robert Dubner
2026-11-12 18:52 ` [PATCH v5 1/5] gdb: Preserve neighboring bits when writing floating-point fields Robert Dubner
2026-11-12 18:52 ` [PATCH v5 2/5] gdb: Preserve subnormal values in target floating-point operations Robert Dubner
2026-11-12 18:52 ` [PATCH v5 3/5] gdb: Preserve signed zero in MPFR target conversions Robert Dubner
2026-11-12 18:52 ` [PATCH v5 4/5] gdb: Preserve signed zero in floating-point unary negation Robert Dubner
2026-11-12 18:52 ` [PATCH v5 5/5] gdb: Avoid oversized shifts when writing floating-point fields Robert Dubner

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox