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

    C-bugCategory: This is a bug.needs-triageThis issue may need triage. Remove it if it has been sufficiently triaged.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions