Re: [PATCH] lib/clz_ctz.c: Fix __clzdi2() and __ctzdi2() for 32-bit kernels
From: Linus Torvalds
Date: Fri Aug 25 2023 - 21:16:26 EST
On Fri, 25 Aug 2023 at 17:52, Nick Desaulniers <ndesaulniers@xxxxxxxxxx> wrote:
>
> So 2 concerns where "I'll do it in inline asm" can pessimize codegen:
> 1. You alluded to this, but what happens when one of these functions
> is called with a constant?
This is why our headers have a lot of __builtin_constant_p()'s in them..
In this particular case, see the x86 asm/bitops.h code:
#define ffs(x) (__builtin_constant_p(x) ? __builtin_ffs(x) :
variable_ffs(x))
but this is actually quite a common pattern, and it's often not about
something like __builtin_ffs() at all.
See all the other __builtin_constant_p()'s that we have in that same
file because we basically just use different code sequences for
constants.
And that file isn't even unusual. We use it quite a lot when we care
about code generation for some particular case.
> 2. by providing the definition of a symbol typically provided by libc
> (and then not building with -ffreestanding) pessimizes libcall
> optimization.
.. and this is partly why we often avoid libgcc things, and do certain
things by hand.
The classic rule is "Don't do 64-bit divisions using the C '/' operator".
So in the kernel you have to use do_div() and friends, because the
library versions are often disgusting and might not know that 64/32 is
much much cheaper and is what you want.
And quite often we simply use other names - but then we also do *not*
build with -freestanding, because -freestanding has at least
traditionally meant that the compiler won't optimize the simple and
obvious cases (typically things like "memcpy with a constant size").
So we mix and match and pick the best option.
The kernel really doesn't care about architecture portability, because
honestly, something like "ffs()" is entirely *trivial* to get right,
compared to the real differences between architectures (eg VM and IO
differences etc).
Linus