optimizer discards sign information

Xi Ruoyao xry111@xry111.site
Wed Apr 10 10:17:12 GMT 2024


On Wed, 2024-04-10 at 18:07 +0800, LIU Hao wrote:
> 在 2024-04-10 17:52, Xi Ruoyao via Gcc-help 写道:
> > No, the OP is still thinking it's a wrong-code.
> 
> Would you read the Subject please?
> 
> 
>      u32 x = a * b;
>      u64 r = x;
>      return r;
> 
> This is same as
> 
>      u32 x = (int) a * (int) b;
>      u64 r = x;
>      return r;
> 
> and
> 
>      return (u64)(u32) ((int) a * (int) b);
> 
> 
> The code requests an `int` be zero-extended to a `u64` (if the result is written to EAX then this is 
> no-op), but GCC performs sign extension anyway. Do you still consider it not a bug?

It is a missed-optimization, but not wrong code.

The code does not requests an *arbitrary* int to be zero-extended to a
u64.  It requests a value which can be proven as non-negative to be
zero-extended.  Thus doing a sign-extension may be sub-optimal
(depending on the context and the target feature etc), but not wrong.

u32 x = (int) a * (int) b;

Here a and b are u16, so both (int) a and (int) b are non-negative.  And
since signed-overflow is UB, x is non-negative too.  And for a non-
negative int x, (u64)x is just same as (u64)(u32)x.

-- 
Xi Ruoyao <xry111@xry111.site>
School of Aerospace Science and Technology, Xidian University


More information about the Gcc-help mailing list