gmp's c++ interface / mpz_class

Pedro Alves
Fri Oct 14 20:42:10 GMT 2022

On 2022-10-14 7:11 p.m., Pedro Alves wrote:

> Zoran and I found a potential need for an integer type with precision of 64-bit + 8-bit, in order to
> store bit offsets that can span a whole 64-bits address space.  Instead of rolling our own,
> I guess it makes sense to use libgmp, since, well, we already depend on it.  I see that we have:
>  /* A class to make it easier to use GMP's mpz_t values within GDB.  */
>  struct gdb_mpz
>  {
> In gdb/gmp-utils.h.  However, we need do to arithmetic on the type, and this wrapper
> type doesn't implement operator+, operator-, etc, etc.  I guess we could add those,
> as wrappers around mpz_add, etc.  Or use raw mpz_add, etc. directly.  However, I just found
> out that GMP already has its own C++ interface:
> Before we explore this further, is there an already known reason we shouldn't be using
> that interface?

I played with this a bit.  So gmp implements infinite precision by heap-allocating a growing
buffer to hold the value storage.  That's not surprising.  However, what surprised
me was that it _always_ heap-allocates, even for "regular" 8-bytes precision.  I.e., it doesn't
employ SBO (Small Buffer Optimization) to avoid heap allocation until the held value grows
big.  Like, this:

  mpz_class val;

... already calls malloc in the ctor.

Hmm.  Since we don't need infinite precision, it will end up a lot more efficient to roll our
own type, with fixed (or templated) storage size.  Like a simplified version of GCC's wide_int.
Not sure yet whether efficiency really matters in practice, but I suspect it does.

I'd still be curious about GMP's native C++ interface.

Pedro Alves

More information about the Gdb mailing list