rust-lang / rust-lang/rust

Missed optimization: bounds checks on slices

Open
#162,834 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-optimization T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code:

const N: usize = 32768;

#[unsafe(no_mangle)]
pub fn foo<'a>(input: &[bool], out: &'a mut [u32; N]) -> &'a [u32] {
    let mut n = 0;

    for &c in input {
        if c {
            // Bounds check unless `>=` is used below despite being clearly in-bounds
            out[n] = 1;
            n += 1;

            // if n >= N {
            if n == N {
                break;
            }
        }
    }

    // Bounds check always despite being clearly in-bounds
    &out[..n]
}

https://rust.godbolt.org/z/hdcrP4zP5

The code I had originally was an array with MaybeUninit elements of upper-bound size and returned initialized prefix out of it.

I expected to see this happen: no bounds checks on either out[n] or out[..n].

Instead, this happened:

out[n] gets bounds check unless n == N is replaced with n >= N, which for the purposes of stopping this loop is equivalent.

In out[..n] bounds check is always present even though it is clear that n will never exceed N. n >= N doesn't save it either.

Meta

rustc --version --verbose:

rustc 1.100.0-nightly (574ff7d98 2026-09-14)
binary: rustc
commit-hash: 574ff7d98bd6d037e5236a8453029173b32631fd
commit-date: 2026-09-14
host: x86_64-unknown-linux-gnu
release: 1.100.0-nightly
LLVM version: 23.1.1

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

Start by reproducing the foo example with the reported nightly rustc version and compare its generated output using the linked Rust Compiler Explorer example. Investigate the compiler's bounds-check optimization for out[n] and &out[..n]; done means both checks are eliminated when the compiler can prove the indices remain within the fixed-size array.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.