Skip to content

Redundant instructions involving indexing with bools #123216

@alion02

Description

@alion02

I tried this code:

fn f(a: u32, b: bool, c: bool, d: &mut [u128; 2]) {
    let mut a = a & 1 != 0;
    if b {
        a ^= c;
        d[0] |= 1;
    }
    d[a as usize] |= 1;
}

It compiles to the following assembly:

f:
        test    esi, esi
        je      .LBB0_1
        xor     dil, dl
        or      byte ptr [rcx], 1
        jmp     .LBB0_3
.LBB0_1:
        and     dil, 1
.LBB0_3:
        movzx   eax, dil
        and     eax, 1
        shl     eax, 4
        or      byte ptr [rcx + rax], 1
        ret

The jmp .LBB0_3 and and dil, 1 instructions are useless, because dil is moved to eax and anded with 1 there anyway, and dil is not used anywhere.

The output improves if you avoid using bools.

godbolt

Meta

rustc --version --verbose:

rustc 1.79.0-nightly (c9f8f3438 2024-03-27)
binary: rustc
commit-hash: c9f8f3438a8134a413aa5d4903e0196e44e37bbc
commit-date: 2024-03-27
host: x86_64-unknown-linux-gnu
release: 1.79.0-nightly
LLVM version: 18.1.2
Compiler returned: 0

@rustbot modify labels: -C-bug +C-optimization +A-codegen +A-LLVM +I-slow +I-heavy

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.A-codegenArea: Code generationC-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchE-needs-testCall for participation: An issue has been fixed and does not reproduce, but no test has been added.I-heavyIssue: Problems and improvements with respect to binary size of generated code.I-slowIssue: Problems and improvements with respect to performance of generated code.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions