[PATCH] x86: Don't left shift negative values

H.J. Lu hjl.tools@gmail.com
Fri Mar 13 01:17:45 GMT 2026


On Thu, Mar 12, 2026 at 6:14 PM Collin Funk <collin.funk1@gmail.com> wrote:
>
> GCC warns about this with -Wshift-negative-value:
>
>     In file included from ../sysdeps/x86/cpu-features.c:24:
>     ../sysdeps/x86/dl-cacheinfo.h: In function ‘get_common_cache_info’:
>     ../sysdeps/x86/dl-cacheinfo.h:913:45: warning: left shift of negative value [-Wshift-negative-value]
>       913 |                           count_mask = ~(-1 << (count_mask + 1));
>           |                                             ^~
>     ../sysdeps/x86/dl-cacheinfo.h:930:45: warning: left shift of negative value [-Wshift-negative-value]
>       930 |                           count_mask = ~(-1 << (count_mask + 1));
>           |                                             ^~
>
> This is because C23 § 6.5.8 specifies that this is undefined behavior.
> We can cast it to unsigned which would be equivelent to UINT_MAX.
> ---
>  sysdeps/x86/dl-cacheinfo.h | 4 ++--
>  1 file changed, 2 insertions(+), 2 deletions(-)
>
> diff --git a/sysdeps/x86/dl-cacheinfo.h b/sysdeps/x86/dl-cacheinfo.h
> index fd2e60fa38..b6e17b0e32 100644
> --- a/sysdeps/x86/dl-cacheinfo.h
> +++ b/sysdeps/x86/dl-cacheinfo.h
> @@ -910,7 +910,7 @@ get_common_cache_info (long int *shared_ptr, long int * shared_per_thread_ptr, u
>                            /* Compute count mask.  */
>                            asm ("bsr %1, %0"
>                                 : "=r" (count_mask) : "g" (threads_l2));
> -                          count_mask = ~(-1 << (count_mask + 1));
> +                          count_mask = ~(-1U << (count_mask + 1));
>                            threads_l2 = (shipped - 1) & count_mask;
>                            count &= ~0x1;
>                          }
> @@ -927,7 +927,7 @@ get_common_cache_info (long int *shared_ptr, long int * shared_per_thread_ptr, u
>                            /* Compute count mask.  */
>                            asm ("bsr %1, %0"
>                                 : "=r" (count_mask) : "g" (threads_core));
> -                          count_mask = ~(-1 << (count_mask + 1));
> +                          count_mask = ~(-1U << (count_mask + 1));
>                            threads_core = (shipped - 1) & count_mask;
>                            if (level == 2)
>                              threads_l2 = threads_core;
> --
> 2.53.0
>

LGTM.

Reviewed-by: H.J. Lu <hjl.tools@gmail.com>

Thanks.

-- 
H.J.


More information about the Libc-alpha mailing list