Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
pozix604 opened this issue Dec 26, 2022 · 3 comments
Closed

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

pozix604 opened this issue Dec 26, 2022 · 3 comments
Labels
C-bug Category: This is a bug.

Comments

@pozix604
Copy link

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
@pozix604 pozix604 added the C-bug Category: This is a bug. label Dec 26, 2022
@saethlin
Copy link
Member

This is a duplicate of #102303, and the fix is in beta so it should be fixed on stable in the next release.

@pozix604
Copy link
Author

Excellent!

@pozix604 pozix604 closed this as not planned Won't fix, can't repro, duplicate, stale Dec 26, 2022
@leonardo-m
Copy link

If you want the best performance I think you should use #[repr(usize)] on the enum.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-bug Category: This is a bug.
Projects
None yet
Development

No branches or pull requests

3 participants