rust-lang / rust-lang/rust

Compiler doesn't optimize out no-op loop.

Open
#147,610 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

I tried this code:

#[unsafe(no_mangle)]
pub fn foo() -> u64 {
    let mut a = 0u64;
    for _ in 0..1024 {
        a ^= 1;
    }
    a
}

I compiled it with -Copt-level=3 on godbolt, and got this assembly:

foo:
        mov     eax, 1024
.LBB0_1:
        add     eax, -32
        jne     .LBB0_1
        xor     eax, eax
        ret

For some reason, the generated assembly counts from 1024 to 0 in a loop that does nothing. This seems wasteful.

Other operations that flip-flop between two states also have a similar effect. For example, a = -a;, or a = !a;.

Meta

Compiler version on godbolt:

rustc 1.90.0 (1159e78c4 2025-09-14)
binary: rustc
commit-hash: 1159e78c4747b02ef996e55082b704c09b970588
commit-date: 2025-09-14
host: x86_64-unknown-linux-gnu
release: 1.90.0
LLVM version: 20.1.8
Internal compiler ID: r1900

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

Reproduce the Rust 1.90.0 example from the issue on Godbolt with -Copt-level=3, then compare the generated x86 assembly for the XOR, negation, and complement cases. Trace why the optimizer retains the loop; done means these no-op loop patterns no longer produce a runtime loop while preserving the shown function results.

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.