Indexing with `bool` generates suboptimal assembly
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
I tried this code:
fn f(a: &[u32; 2], c: bool) -> u32 {
a[c as usize]
}
I expected to see this assembly:
f:
mov eax, dword ptr [rdi + 4*rsi]
ret
Instead, I got this assembly:
f:
mov eax, esi ; zero-extend esi (bool param)
mov eax, dword ptr [rdi + 4*rax]
ret
I believe the ABI does not allow the upper 32 bits of rsi to be dirty when passing arguments smaller than 8 bytes, but I could be mistaken or otherwise misunderstanding the problem.
I could not find a workaround other than changing the type of c to usize and adding an unreachable_unchecked.
Meta
rustc --version --verbose:
rustc 1.78.0-nightly (d18480b84 2024-03-04)
binary: rustc
commit-hash: d18480b84fdbf1efc34f62070951334aa833d761
commit-date: 2024-03-04
host: x86_64-unknown-linux-gnu
release: 1.78.0-nightly
LLVM version: 18.1.0
Compiler returned: 0
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Run the supplied Rust reproducer and compare its generated assembly with the Godbolt example. Trace rustc's code-generation and ABI handling for converting the bool index, then add regression coverage showing the expected indexing assembly and verify the compiler output no longer performs the unnecessary zero-extension.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers, performance
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 38/100