Skip to content

Redundant length check needed to optimize out panicking bounds check in loop #147953

@okaneco

Description

@okaneco

While working on #147436, I noticed the following code has a panicking bounds check in the loop body that is removed when both slice lengths received from as_chunks are checked.

The slices are checked to be equal length at the start of the function, so the number of chunks and loop iterations is known to be equal.

I tried this code, which manually zips two instances of as_chunks array slices together with a while-loop:

#[inline(never)]
pub const fn all_less_than(s: &[u8], other: &[u8]) -> bool {
    if s.len() != other.len() {
        return false;
    }

    const N: usize = 16;
    let (a, _) = s.as_chunks::<N>();
    let (b, _) = other.as_chunks::<N>();

    let mut i = 0;
    while i < a.len() {
        let mut less_than = true;
        let mut j = 0;
        while j < N {
            less_than &= a[i][j] < b[i][j];
            j += 1;
        }

        if !less_than {
            return false;
        }

        i += 1;
    }

    true
}

I expected to not need to check the length for b since it's known to be equal.

When I change the loop condition from while i < a.len() to while i < a.len() && i < b.len(), the panic branch is removed.
https://rust.godbolt.org/z/azrbYq4Gv

while i < a.len() while i < a.len() && i < b.len()
.LBB0_4:
        sub     r8, 1
        jb      .LBB0_8
        movdqu  xmm0, xmmword ptr [rdi + rcx]
        movdqu  xmm1, xmmword ptr [rdx + rcx]
        pmaxub  xmm1, xmm0
        pcmpeqb xmm1, xmm0
        pmovmskb        eax, xmm1
        test    eax, eax
        sete    al
        jne     .LBB0_7
        add     rcx, 16
        cmp     r9, 1
        mov     r9, r8
        jne     .LBB0_4
.LBB0_4:
        movdqu  xmm0, xmmword ptr [rdi + rcx]
        movdqu  xmm1, xmmword ptr [rdx + rcx]
        pmaxub  xmm1, xmm0
        pcmpeqb xmm1, xmm0
        pmovmskb        eax, xmm1
        add     rsi, -1
        setb    r8b
        test    eax, eax
        sete    al
        jne     .LBB0_6
        add     rcx, 16
        test    r8b, r8b
        jne     .LBB0_4

Meta

Playground nightly

Nightly channel
Build using the Nightly version: 1.92.0-nightly
(2025-10-20 4068bafedd8ba724e332)

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.C-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchneeds-triageThis issue may need triage. Remove it if it has been sufficiently triaged.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions