[4/6] Add overload of fits_in_type

Message ID 20230328-expr-128-bit-v1-4-f9eeb0143318@adacore.com
State New
Headers
Series Add 128-bit integers to Ada and Rust parsers |

Commit Message

Tom Tromey March 28, 2023, 3:49 p.m. UTC
  This adds an overload of fits_in_type that accepts a gdb_mpz.  A
subsequent patch will use this.
---
 gdb/parse.c       | 26 ++++++++++++++++++++++++++
 gdb/parser-defs.h |  2 ++
 2 files changed, 28 insertions(+)
  

Patch

diff --git a/gdb/parse.c b/gdb/parse.c
index 24db3ca57d9..23545e32160 100644
--- a/gdb/parse.c
+++ b/gdb/parse.c
@@ -648,6 +648,32 @@  fits_in_type (int n_sign, ULONGEST n, int type_bits, bool type_signed_p)
   else
     gdb_assert_not_reached ("");
 }
+
+/* Return true if the number N_SIGN * N fits in a type with TYPE_BITS and
+   TYPE_SIGNED_P.  N_SIGNED is either 1 or -1.  */
+
+bool
+fits_in_type (int n_sign, const gdb_mpz &n, int type_bits, bool type_signed_p)
+{
+  /* N must be nonnegative.  */
+  gdb_assert (n.sgn () >= 0);
+
+  /* Zero always fits.  */
+  /* Normalize -0.  */
+  if (n.sgn () == 0)
+    return true;
+
+  if (n_sign == -1 && !type_signed_p)
+    /* Can't fit a negative number in an unsigned type.  */
+    return false;
+
+  gdb_mpz max = gdb_mpz::pow (2, (type_signed_p
+				  ? type_bits - 1
+				  : type_bits));
+  if (n_sign == -1)
+    return n <= max;
+  return n < max;
+}
 
 /* This function avoids direct calls to fprintf 
    in the parser generated debug code.  */
diff --git a/gdb/parser-defs.h b/gdb/parser-defs.h
index 1780d856744..62829a86f9a 100644
--- a/gdb/parser-defs.h
+++ b/gdb/parser-defs.h
@@ -414,6 +414,8 @@  extern bool parse_float (const char *p, int len,
 			 const struct type *type, gdb_byte *data);
 extern bool fits_in_type (int n_sign, ULONGEST n, int type_bits,
 			  bool type_signed_p);
+extern bool fits_in_type (int n_sign, const gdb_mpz &n, int type_bits,
+			  bool type_signed_p);
 
 
 /* Function used to avoid direct calls to fprintf