Re: [PATCH] riscv/atomic: Do proper sign extension also for unsigned in arch_cmpxchg

Maciej W. Rozycki
2025-02-04T16:44:38Z

On Mon, 3 Feb 2025, Jessica Clarke wrote:

> > Umm, that would be a compiler bug then, as inlining is supposed not to
> > change language semantics. IOW the compiler is expected to explicitly
> > sign-extend the arguments of an inlined function at their evaluation point
> > just as it would at an actual function call unless the compiler is able to
> > prove they have come out sign-extended already from previous operations.
>
> No it’s not. The calling convention is there so that each side of the
> call know how the data is being passed between them. When inlining
> occurs there is no such call and compilers can do whatever they like.

Right, I guess I got influenced too much by my MIPS experience here.

The contract here is to pass a 32-bit integer as an argument through a
function call boundary and with the RISC-V ISA saying the upper 32-bits of
an input hardware register are don't-cares for 32-bit integer operations
this contract is still met if inlining discards the sign-extension madated
by the psABI. And consequently a piece of inline assembly cannot expect
an incoming 32-bit integer in a register to be correctly interpreted as a
64-bit integer of equal value instead.

Although I find it odd in these circumstances that the psABI mandates
sign-extension here. And honestly I think an explicit cast ought to be
added to the relevant assembly input operands (or a temporary variable of
the appropriate type added and used to convert between the incoming value
and the input operands); it will be a no-op for an optimising compiler
when it knows the value has been sign-extended already and will carry the
semantics information for a human code reader even if sign-extension has
been implicitly ensured by the psABI despite the data type itself not
making it evident.

Thanks for correcting me overall.

Maciej