Bad codegen with functions returning `Result`.
I tried this code: https://godbolt.org/z/WGK9WTKec
type Result<T> = core::result::Result<T, u32>;
// ^--- note: all other integer types compile as expected
fn map<T, F, U>(value: Result<T>, op: F) -> Result<U>
where
F: FnOnce(T) -> U
{
value.map(op)
}
pub fn assign(val: [u8; 4], out: &mut u32) -> Result<()> {
let val = map(Ok(val), u32::from_le_bytes)?;
*out = val;
Ok(())
}
I expected to see this:
example[91f12ae00899f36c]::assign:
mov dword ptr [rsi], edi
xor eax, eax
ret
Instead, this happened:
example[91f12ae00899f36c]::assign:
mov eax, edi
shr eax, 24 ; elaborate no-op
shl edi, 8 ; elaborate no-op
shrd edi, eax, 8 ; elaborate no-op
; edi = edi (when the call started)
mov dword ptr [rsi], edi
xor eax, eax
ret
Meta
rustc --version --verbose:
nightly on godbolt
Possibly related https://github.com/rust-lang/rust/issues/148461.
Well there's no niche here, and also I think this happens with u16 too: https://godbolt.org/z/MGrxfMEex
Managed to get even worse codegen.
type Result<T> = core::result::Result<T, u32>;
fn map<T, F, U>(value: Result<T>, op: F) -> Result<U>
where
F: FnOnce(T) -> U
{
value.map(op)
}
pub fn assign_aligned(val: u32, out: &mut u32) -> Result<()> {
let val = map(Ok(val), |val| val)?;
*out = val;
Ok(())
}
// note: type U32Align1 = [u8; 4] produces the same result
#[repr(packed)]
struct U32Align1(u32);
pub fn assign_packed(val: U32Align1, out: &mut U32Align1) -> Result<()> {
let val = map(Ok(val), |val| val)?;
*out = val;
Ok(())
}
pub fn assign_with_input_u32(val: u32, out: &mut U32Align1) -> Result<()> {
let val = map(Ok(val), U32Align1)?;
*out = val;
Ok(())
}
example::assign_aligned:
mov dword ptr [rsi], edi
xor eax, eax
ret
example::assign_packed:
mov eax, edi
shr eax, 24
shl edi, 8
shrd edi, eax, 8
mov eax, edi
shr eax, 24
shl rax, 32
shl edi, 8
or rdi, rax
shr rdi, 8
mov dword ptr [rsi], edi
xor eax, eax
ret
example::assign_with_input_u32:
mov dword ptr [rsi], edi
shr edi, 24
xor eax, eax
mov edx, edi
ret
No, this is a separate pattern. PR: llvm/llvm-project#196887
https://github.com/rust-lang/rust/issues/156423#issuecomment-4417126438 needs more handling... Please consider filing an issue with llvm-project.
@rustbot claim
No, this is a separate pattern.
Yeah, realized that when I looked into the opt passes last night. Thanks for the patches though!
Upstream fixed
Confirmed fixed in 1.99 with LLVM 23: https://godbolt.org/z/5Pro53qoo
A codegen test probably wouldn't hurt.
Hi @nikic , I saw this issue was reopened so i raised a PR with a regression test since there was the label E-needs-test
#164786 added the test for this, so I think it can be closed