Skip to content

Indexing with bool generates suboptimal assembly #122121

Open
@alion02

Description

@alion02

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

godbolt

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-codegenArea: Code generationC-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchI-slowIssue: Problems and improvements with respect to performance of generated code.O-x86_64Target: x86-64 processors (like x86_64-*) (also known as amd64 and x64)S-has-mcveStatus: A Minimal Complete and Verifiable Example has been found for this issue

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions