rust-lang / rust-lang/rust

Missed optimization in if with constant branches

Open
#129,144 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-LLVM C-optimization I-slow
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I assume the following two functions behave identically, and therefore should result in the same codegen. https://godbolt.org/z/vj9ornqbG

#[no_mangle]
pub fn cast(x: bool) -> f32 {
    x as u8 as f32
}

#[no_mangle]
pub fn ifelse(x: bool) -> f32 {
    if x { 1. } else { 0. }
}

However, ifelse fails to be optimised to a cast.

cast:
        cvtsi2ss        xmm0, edi
        ret

.LCPI1_0:
        .long   0x3f800000
ifelse:
        test    edi, edi
        jne     .LBB1_1
        xorps   xmm0, xmm0
        ret
.LBB1_1:
        movss   xmm0, dword ptr [rip + .LCPI1_0]
        ret

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 by reproducing the Rust example from the issue in the linked Compiler Explorer output and compare the generated assembly for cast and ifelse. Trace the compiler optimization path handling the constant branches, then add coverage showing that equivalent functions produce the expected optimized codegen.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.