Skip to content

Bounds check eliminated only when array length is a constant #141671

Open
@DaniPopes

Description

@DaniPopes

I tried this code (godbolt):

#[no_mangle]
pub fn shift_left(arr: &mut [u64], n: usize) {
    let len = arr.len();
    if n >= len {
        arr.fill(0);
    } else {
        let c = len - n;
        for i in 0..c {
            arr[i] = arr[i + n];
        }
        arr[c..].fill(0);
    }
}

#[no_mangle]
pub fn shift_left_4(arr: &mut [u64; 4], n: usize) {
    shift_left(arr, n);
}

I expected to see this happen: no bound checks in both functions

Instead, this happened: bounds check present in the generic shift_left (the arr[i + n])

Meta

rustc --version --verbose:

rustc 1.89.0-nightly (5e16c6620 2025-05-24)
binary: rustc
commit-hash: 5e16c662062fd6dee91f0fe2a1580483488d80cf
commit-date: 2025-05-24
host: x86_64-unknown-linux-gnu
release: 1.89.0-nightly
LLVM version: 20.1.5
Backtrace

<backtrace>

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchT-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