Skip to content

Missed bounds check optimization #46516

Closed
@davidbolvansky

Description

@davidbolvansky
Bugzilla Link 47172
Version trunk
OS Linux
CC @efriedma-quic,@fhahn,@jrmuizel,@nikic

Extended Description

From rust-lang github (rust-lang/rust#75525):

#include <stddef.h>
#include <stdint.h>


uint8_t f1(size_t idx) {
    if (idx < 8) {
        // it's ok that this has a bounds check
        return (idx - 1) < 10;
    } else {
        return 0;
    }
}

Clang:

f1:                                     # @&#8203;f1
        cmp     rdi, 8
        setb    cl
        add     rdi, -1
        cmp     rdi, 10
        setb    al
        and     al, cl
        ret

GCC:

f1:
        sub     rdi, 1
        cmp     rdi, 6
        setbe   al
        ret

Modified test case:

uint8_t f2(size_t idx) {
    if (idx <= 9) {
       return (idx - 1) > 10;
    } else {
        return 0;
    }
}

Clang:

f2:                                     # @&#8203;f2
        cmp     rdi, 10
        setb    cl
        add     rdi, -1
        cmp     rdi, 10
        seta    al
        and     al, cl
        ret

GCC:

f2:
        test    rdi, rdi
        sete    al
        ret

https://godbolt.org/z/vahzbo

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions