__builtin_constant_p for trivial operations

Marc Glisse marc.glisse at inria.fr
Sun Feb 20 16:59:51 CET 2011

On Sun, 20 Feb 2011, Torbjorn Granlund wrote:

> Marc Glisse <marc.glisse at inria.fr> writes:
>  would something like the attached ugliness be acceptable? (don't take
>  it as a real patch, it wasn't properly tested and is incomplete)
> I think we cannot change e.g. mpz_add_ui from a function to a macro,
> since we have documented it as a function.  There are surely programs
> out there which make a function pointer, perhaps through a function
> table, to mpz_add_ui.

Ah, indeed, I didn't think of that. There would still be a way, but it 
gets ugly:

have both names __gmpz_add_ui and __gmpz_add_ui_noinline refer to the same 
function in libgmp (technically, this doesn't require changing libgmp, 
only gmp.h). Have a macro mpz_add_ui=__gmpz_add_ui. And have a C99 inline 
function __gmpz_add_ui that does the __builtin_constant_p stuff and calls 
__gmpz_add_ui_noinline if needed.

In this case, taking the address of __gmpz_add_ui should refer to the 
libgmp version.

I don't know if there are better/easier ways...

>  The goal is that, if I have a C++ mpz_class variable z, z*=-1 and z/2
>  get translated to mpz_neg and mpz_tdiv_q_2exp instead of mpz_mul_si
>  and mpz_tdiv_q_ui. With zero runtime penalty.
> Could that not be made at the C++ level?  It might seem better to do
> that also for C, but I apart from the compatibility problems, I suspect
> it to be less common that people use mul_si for negationm that it is in
> C++'s with its more seductive syntax...

Yes, it could be done at the C++ level. As you say, I thought that I might 
as well make it at the C level since that implies it also works for C++, 
and even in C you may have such things, for instance when the ui argument 
is a constant given by strange macros. But it is indeed more useful for 
C++ and can be done there.

Marc Glisse

More information about the gmp-discuss mailing list