rust-lang / rust-lang/rust

Return branches not correctly merged in size-optimized x86-64 assembly

Open
#127,376 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-codegen A-LLVM C-optimization I-heavy T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

Godbolt link (includes this and another buggy example)

I tried this code:

pub fn parse_u32_digit(acc: u32, byte: u8) -> Option<u32> {
    let max = if acc == 429496729 { 5 } else { 9 };
    if acc <= 429496729 {
        let v = (byte as u32).wrapping_sub(b'0' as u32);
        if v <= max {
            return Some(acc.wrapping_mul(10).wrapping_add(v));
        }
    }
    None
}

I expected to see this happen: assembly that looks something like this:

parse_u32_digit:
        xor     eax, eax
        cmp     edi, 429496729
        ja      .LBB1_1
        setne   cl
        movzx   ecx, cl
        lea     r8d, [4*rcx + 5]
        movzx   ecx, sil
        add     ecx, -48
        cmp     ecx, r8d
        ja      .LBB1_4
        lea     eax, [rdi + 4*rdi]
        lea     edx, [rcx + 2*rax]
        mov     eax, 1
.LBB1_1:
.LBB1_4:
        ret

Instead, this happened: the following assembly:

parse_u32_digit:
        xor     eax, eax
        cmp     edi, 429496729
        ja      .LBB1_1
        setne   cl
        movzx   ecx, cl
        lea     r8d, [4*rcx + 5]
        movzx   ecx, sil
        add     ecx, -48
        cmp     ecx, r8d
        ja      .LBB1_4
        lea     eax, [rdi + 4*rdi]
        lea     edx, [rcx + 2*rax]
        mov     eax, 1
.LBB1_4:
        ret
.LBB1_1:
        ret
Meta

rustc --version --verbose:

rustc 1.79.0 (129f3b996 2024-06-10)
binary: rustc
commit-hash: 129f3b9964af4d4a709d1383930ade12dfe7c081
commit-date: 2024-06-10
host: x86_64-unknown-linux-gnu
release: 1.79.0
LLVM version: 18.1.7
Compiler returned: 0

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the Rust reproducer in the issue and the linked Godbolt example, using rustc 1.79.0 with -C opt-level=s on x86-64. Compare the generated branch layout with the expected and actual assembly, then trace the relevant compiler optimization path. Done means the return branches are correctly merged without changing the reported behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
38/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.