Skip to content

[ER] One useless division by zero test #74917

@leonardo-m

Description

@leonardo-m

This is an enhancement request. This program scans every possible input for the foo function, showing it never gives a division by zero error:

type T = u16;

#[inline(never)]
pub fn foo(x: T, y: T) -> T {
    if x > y {
        100 / (x - y)
    } else {
        100
    }
}

fn main() {
    let mut tot: T = 0;
    for x in T::MIN ..= T::MAX {
        for y in T::MIN ..= T::MAX {
            tot = tot.wrapping_add(foo(x, y));
        }
    }
    println!("{}", tot);
}

But LLVM adds an useless division by zero test (the same happens for T = u32):

foo:
    mov     ax, 100
    sub     di, si
    jbe     .LBB0_3
    je      .LBB0_4
    mov     ax, 100
    xor     edx, edx
    div     di
.LBB0_3:
    ret
.LBB0_4:
    push    rax
    lea     rdi, [rip + str.0]
    lea     rdx, [rip + .L__unnamed_1]
    mov     esi, 25
    call    qword ptr [rip + core::panicking::panic@GOTPCREL]
    ud2

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-LLVMArea: Code generation parts specific to LLVM. Both correctness bugs and optimization-related issues.C-enhancementCategory: An issue proposing an enhancement or a PR with one.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.T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions