Skip to content
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

Compiler does not propagate integer bounds information; misses bounds-check removal opportunities #71919

Open
karwa opened this issue Feb 27, 2024 · 0 comments
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. triage needed This issue needs more specific labels

Comments

@karwa
Copy link
Contributor

karwa commented Feb 27, 2024

Description

Consider the following snippet:

func test_0(_ i: UInt) -> UInt {
    precondition(i <= Int.max)
    return i + 8
}

When compiling with -O, it produces the following assembly:

output.test_0(Swift.UInt) -> Swift.UInt:
        test    rdi, rdi
        js      .LBB1_2
        add     rdi, 8
        mov     rax, rdi
        ret
.LBB1_2:
        ud2

Note that there is one trap, which occurs before the addition (corresponding to the explicit precondition). The compiler is able to recognise that the addition cannot overflow.

Now consider the following snippet:

func test_1(_ i: UInt, _ k: UInt) -> UInt {
    precondition(i <= Int.max && k < i)
    return k + 8
}

From the first snippet, we know that i + 8 cannot overflow, and now we have introduced a variable k, which is even less than i. Therefore, k + 8 also cannot overflow. However, the compiler is not able to recognise this:

output.test_1(Swift.UInt, Swift.UInt) -> Swift.UInt:
        test    rdi, rdi
        js      .LBB2_4
        cmp     rsi, rdi
        jae     .LBB2_4
        add     rsi, 8
        jb      .LBB2_5   ; this overflow check shouldn't exist
        mov     rax, rsi
        ret
.LBB2_4:
        ud2
.LBB2_5:
        ud2

Reproduction

See description.

Alternatively, Goldbolt of those snippets.

Expected behavior

Expect the overflow check noted in the description to be optimised away.

Environment

Swift version 5.11-dev (LLVM 48dba337c6a2104, Swift 823db1f)
Target: x86_64-unknown-linux-gnu

Additional information

No response

@karwa karwa added bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. triage needed This issue needs more specific labels labels Feb 27, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug A deviation from expected or documented behavior. Also: expected but undesirable behavior. triage needed This issue needs more specific labels
Projects
None yet
Development

No branches or pull requests

1 participant