LLVM Bugzilla is read-only and represents the historical archive of all LLVM issues filled before November 26, 2021. Use github to submit LLVM bugs

Bug 47172 - Missed bounds check optimization
Summary: Missed bounds check optimization
Status: NEW
Alias: None
Product: libraries
Classification: Unclassified
Component: Scalar Optimizations (show other bugs)
Version: trunk
Hardware: PC Linux
: P enhancement
Assignee: Unassigned LLVM Bugs
URL:
Keywords:
Depends on:
Blocks:
 
Reported: 2020-08-14 13:15 PDT by David Bolvansky
Modified: 2020-12-17 09:23 PST (History)
5 users (show)

See Also:
Fixed By Commit(s):


Attachments

Note You need to log in before you can comment on or make changes to this bug.
Description David Bolvansky 2020-08-14 13:15:50 PDT
From rust-lang github (https://github.com/rust-lang/rust/issues/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:                                     # @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:                                     # @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
Comment 1 Florian Hahn 2020-08-14 14:19:51 PDT
Variants of this should be able to be handled using the approach suggested here https://reviews.llvm.org/D84547

Although in the C source, `idx - 1` can wrap. I'm not entirely sure about the rust case, but I assume there might be some wrapping flags?
Comment 2 Eli Friedman 2020-08-14 14:42:00 PDT
gcc is optimizing assuming the subtraction can wrap.

rustc generally doesn't generate nsw/nuw flags in the frontend; integer overflow is defined to either wrap or trap.
Comment 3 David Bolvansky 2020-08-14 14:54:02 PDT
One more test case for CE pass:

uint8_t f3(size_t idx) {
    if (idx <= 9) {
       return (idx + 1) > 16;
    } else {
        return 0;
    }
}

Clang:
f3:                                    
        cmp     rdi, 10
        setb    cl
        add     rdi, 1
        cmp     rdi, 16
        seta    al
        and     al, cl
        ret

GCC:
f3:
        xor     eax, eax
        ret