Skip to content

Bounds check not elided when indexing array with enum discriminant #106158

@pozix604

Description

@pozix604

Given an array with known size N, and an enum with discriminants 0..N, indexing the array with the enum's discriminants does not elide bounds checking when out-of-bounds is impossible.

I tried this code:

pub enum E { A, B, C, D, E, F }

pub fn index(xs: [u64; 6], ix: E) -> u64 {
    xs[ix as usize]
}

I expected to see this happen: Assembly output does not have bounds checking.

Instead, this happened: https://godbolt.org/z/EMsjh63aj

example::index:
        push    rax
        mov     rax, rdi
        movzx   edi, sil
        cmp     sil, 5
        ja      .LBB0_2
        mov     rax, qword ptr [rax + 8*rdi]
        pop     rcx
        ret
.LBB0_2:
        lea     rdx, [rip + .L__unnamed_1]
        mov     esi, 6
        call    qword ptr [rip + core::panicking::panic_bounds_check@GOTPCREL]
        ud2

.L__unnamed_2:
        .ascii  "/app/example.rs"

.L__unnamed_1:
        .quad   .L__unnamed_2
        .asciz  "\017\000\000\000\000\000\000\000\004\000\000\000\005\000\000"

rustc --version --verbose:

$ rustc --version --verbose
rustc 1.66.0 (69f9c33d7 2022-12-12)
binary: rustc
commit-hash: 69f9c33d71c871fc16ac445211281c6e7a340943
commit-date: 2022-12-12
host: x86_64-unknown-linux-gnu
release: 1.66.0
LLVM version: 15.0.2

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions