Re: detecting integer constant expressions in macros
From: Uecker, Martin
Date: Tue Mar 20 2018 - 20:18:12 EST
Am Dienstag, den 20.03.2018, 16:08 -0700 schrieb Linus Torvalds:
> On Tue, Mar 20, 2018 at 3:13 PM, Uecker, Martin
> <Martin.Uecker@xxxxxxxxxxxxxxxxxxxxx> wrote:
> >
> > here is an idea:
>
> That's not "an idea".
>
> That is either genius, or a seriously diseased mind.
>
> I can't quite tell which.
>
> > a test for integer constant expressions which returns an
> > integer constant expression itself which should be suitable
> > for passing to __builtin_choose_expr might be:
> >
> > #define ICE_P(x) (sizeof(int) == sizeof(*(1 ? ((void*)((x) * 0l)) :
> > (int*)1)))
...
> So now the end result is (sizeof(*(void *)(x)), which on gcc is
> generally *different* from 'int'.
>
> So I see two issues:
>
> Â- "sizeof(*(void *)1)" is not necessalily well-defined. For gcc it
> is
> 1. But it could cause warnings.
It is a documented extension which enables pointer arithmetic
on void pointers, so I am sure neither gcc nor
clang has any problem with it. But one could also use
__builtin_types_compatible_p instead.
> Â- this will break the minds of everybody who ever sees that
> expression.
>
> Those two issues might be fine, though.
>
> > This also does not evaluate x itself on gcc although this is
> > not guaranteed by the standard. (And I haven't tried any older
> > gcc.)
>
> Oh, I think it's guaranteed by the standard that 'sizeof()' doesn't
> evaluate the argument value, only the type.
It has to evaluate the expression for the length of an array,
but it is not specified whether this is done if it does not have
any effect on the result. I would assume that any sane compiler
does not.
> I'm in awe of your truly marvelously disgusting hack. That is truly a
> work of art.
>
> I'm sure it doesn't work or causes warnings for various reasons, but
> it's still a thing of beaty.
I thought you might like it ;-)
Martin