rust-lang / rust-lang/rust

Missed optimization with `*x += 0;`

Open
#149,971 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-optimization needs-triage T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

This issue was discovered by @ruriww

I tried this code:

#[unsafe(no_mangle)]
pub fn f(x: &mut u32) {
    *x = *x;
    if *x != 0 {
        *x = 0;
    }
}

#[unsafe(no_mangle)]
pub fn g(x: &mut u32) {
    *x = *x;
    if *x != 0 {
        *x = 0;
    } else {
        *x += 0;
    }
}

I expected both functions to compile to the same assembly. Note that the *x = *x; gives the compiler license to write to *x (without running into opsem questions about whether spurious writes are allowed).

Instead I got the following with -Copt-level=3 (Godbolt):

f:
        mov     dword ptr [rdi], 0
        ret

g:
        cmp     dword ptr [rdi], 0
        je      .LBB1_2
        mov     dword ptr [rdi], 0
.LBB1_2:
        ret
Meta

Godbolt compiler version:

rustc 1.94.0-nightly (fa5eda19b 2025-12-12)
binary: rustc
commit-hash: fa5eda19b95201468f5b1c5c035ec2fc06fccd66
commit-date: 2025-12-12
host: x86_64-unknown-linux-gnu
release: 1.94.0-nightly
LLVM version: 21.1.5
Internal compiler ID: nightly

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 compare the optimized assembly for functions f and g using the linked Godbolt example. Trace the compiler optimization path responsible for simplifying the two cases, then add or update a regression test if the relevant test location is identified. Done means g receives the same optimization as f without changing the intended semantics.

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
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.