Re: [PATCH v2 1/8] minmax: Put all the clamp() definitions together

Linus Torvalds
2024-07-30T01:52:28Z

On Mon, 29 Jul 2024 at 16:21, Linus Torvalds
<torvalds@linuxfoundation.org> wrote:
>
> What we actually care about is not "constant", but "no side effects".

Ho humm..

We actually could do something like this:

#define no_side_effects(x) __builtin_constant_p((x,0))

because __builtin_constant_p() doesn't actually look at just the value
of the expression, but is defined to return 0 even if the value is
constant but the expression has side effects.

So no_side_effects(variable) returns true, but
no_side_effects(variable++) returns false.

Note that this is also why _static_assert() and
__builtin_choose_expr() are generally very dubiously useful. Because
they are limited to a "C constant expression", they fundamentally
cannot take advantage of trivial optimization things, and fall flat on
their face in many real life situations.

In contrast, __builtin_constant_p() works for arbitrary expressions,
and just says "I can easily turn this expression into a constant".

Which makes it much more powerful than the nasty syntactic "C constant
expression" thing that is very limited.

Things like __builtin_choose_expr() are ok with very simple and direct
conditionals like "is this a double", and they have their place, but
in something like min() that by definition takes many different types
- including pointer types - it's been a huge pain.

Linus