Skip to content

Compiler doesn't optimize out no-op loop. #147610

@theemathas

Description

@theemathas

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 

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.C-bugCategory: This is a bug.C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing such

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions