rust-lang / rust-lang/rust

Missed optimization when checking slice index greater than accessed slice index

Open
#125,826 5 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-LLVM C-optimization I-slow
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

For the following code:

pub fn larger_margin(v: &[u8], index: usize) -> bool {
    if index + 1 < v.len() {
        (v[index + 0] & 0xFF) == 0xED
    } else {
        false
    }
}

Rustc outputs this:

larger_margin:
        lea     rax, [rdx + 1]
        cmp     rax, rsi
        jae     .LBB0_1
        cmp     rdx, rsi
        jae     .LBB0_5
        cmp     byte ptr [rdi + rdx], -19
        sete    al
        ret
.LBB0_1:
        xor     eax, eax
        ret
.LBB0_5:
        push    rax
        lea     rax, [rip + .L__unnamed_1]
        mov     rdi, rdx
        mov     rdx, rax
        call    qword ptr [rip + core::panicking::panic_bounds_check::h9bb22f08a42e1ac8@GOTPCREL]

I would expect the following, because I would have expected the compiler to elide the bounds check.

larger_margin:
        lea     rax, [rdx + 1]
        cmp     rax, rsi
        jae     .LBB1_1
        cmp     byte ptr [rdi + rdx], -19
        sete    al
        ret
.LBB1_1:
        xor     eax, eax
        ret

The compiler does elide the bounds check in the following:

pub fn larger_margin(v: &[u8], index: usize) -> bool {
    if index < v.len() {
        (v[index + 0] & 0xFF) == 0xED
    } else {
        false
    }
}

Rustc appears to miss this optimization in all versions.

Godbolt: https://godbolt.org/z/zqYn7z7h8

Meta

The above is built with:
rustc 1.80.0-nightly (6f3df08aa 2024-05-30) binary: rustc commit-hash: 6f3df08aadf71e8d4bf7e49f5dc10dfa6f254cb4 commit-date: 2024-05-30 host: x86_64-unknown-linux-gnu release: 1.80.0-nightly LLVM version: 18.1.6

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 two Rust snippets and comparing their generated assembly through the linked Godbolt example. Investigate why the first form retains a bounds check while the second does not; done means the redundant check is eliminated without changing the reported behavior.

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
Stale
Clarity
Mostly clear
Newbie friendliness
32/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.