Skip to content

Rust generates suboptimal code for x.div_euclid(2) #118392

Closed
@KamilaBorowska

Description

@KamilaBorowska

I tried this code:

pub fn div2(a: i32) -> i32 {
    a.div_euclid(2)
}

I expected to see this happen:

After compiling to assembly with -C opt-level=3 to generate the following x86 assembly code.

div2:
        mov     eax, edi
        sar     eax
        ret

Instead, this happened:

div2:
        mov     eax, edi
        shr     eax, 31
        add     eax, edi
        sar     eax
        not     edi
        and     edi, -2147483647
        cmp     edi, 1
        sbb     eax, 0
        ret

Meta

rustc --version --verbose:

rustc 1.74.0 (79e9716c9 2023-11-13)
binary: rustc
commit-hash: 79e9716c980570bfd1f666e3b16ac583f0168962
commit-date: 2023-11-13
host: x86_64-unknown-linux-gnu
release: 1.74.0
LLVM version: 17.0.4

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.A-codegenArea: Code generationC-bugCategory: This is a bug.E-needs-testCall for participation: An issue has been fixed and does not reproduce, but no test has been added.I-heavyIssue: Problems and improvements with respect to binary size of generated code.I-slowIssue: Problems and improvements with respect to performance of generated code.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions