Skip to content

Bounds check elision fails when using cmp::max #113757

Closed
@SUPERCILEX

Description

@SUPERCILEX

I tried this code:

pub fn foo(v: &mut Vec<MaybeUninit<u8>>, size: usize)-> Option<&mut [MaybeUninit<u8>]> {
    if v.len() > max(1, size) {
        let start = v.len() - size;
        Some(&mut v[start..])
    } else {
        None
    }
}

Generates:

example::foo:
        push    rax
        mov     rcx, qword ptr [rdi + 16]
        test    rsi, rsi
        mov     eax, 1
        cmovne  rax, rsi
        cmp     rcx, rax
        jbe     .LBB0_1
        mov     rax, rcx
        sub     rax, rsi
        jb      .LBB0_5
        add     rax, qword ptr [rdi]
        jmp     .LBB0_4
.LBB0_1:
        xor     eax, eax
.LBB0_4:
        mov     rdx, rsi
        pop     rcx
        ret
.LBB0_5:
        lea     rdx, [rip + .L__unnamed_1]
        mov     rdi, rax
        mov     rsi, rcx
        call    qword ptr [rip + core::slice::index::slice_start_index_len_fail@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\020\000\000\000\023\000\000"

But

pub fn foo(v: &mut Vec<MaybeUninit<u8>>, size: usize)-> Option<&mut [MaybeUninit<u8>]> {
    if v.len() > 1 && v.len() > size {
        let start = v.len() - size;
        Some(&mut v[start..])
    } else {
        None
    }
}

generates super clean assembly:

example::foo:
        mov     rdx, rsi
        mov     rcx, qword ptr [rdi + 16]
        mov     rax, rcx
        sub     rax, rsi
        add     rax, qword ptr [rdi]
        xor     esi, esi
        cmp     rcx, rdx
        cmovbe  rax, rsi
        cmp     rcx, 2
        cmovb   rax, rsi
        ret

Meta

rustc --version --verbose:

rustc 1.73.0-nightly (1065d876c 2023-07-09)

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.E-needs-testCall for participation: An issue has been fixed and does not reproduce, but no test has been added.I-slowIssue: Problems and improvements with respect to performance of generated code.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions