Issue 237905
Summary [X86][AVX512] extend Sneller's method to scalar division by runtime constants
Labels backend:X86, missed-optimization
Assignees
Reporter Andarwinux
    x86 uses Sneller's method to lower i64 vector division. However, this is also very useful for scalar division by runtime constants, as MachineLICM can hoist the expensive division out of the loop.
https://godbolt.org/z/9d5oh31Me
```c++
#include <stdint.h>
#include <immintrin.h>

static inline uint64_t div(uint64_t a, uint64_t b) {
 constexpr int RD = _MM_FROUND_TO_NEG_INF | _MM_FROUND_NO_EXC;
    constexpr int RU = _MM_FROUND_TO_POS_INF | _MM_FROUND_NO_EXC;
    __m128d inv = _mm_div_round_sd(__m128d{1.0}, _mm_cvt_roundu64_sd(__m128d{}, b, RU), RD);
 uint64_t q = _mm_cvt_roundsd_u64(_mm_mul_round_sd(_mm_cvt_roundu64_sd(__m128d{}, a, RD), inv, RD), RD);
    uint64_t r = a - q * b;
    uint64_t q1 = _mm_cvt_roundsd_u64(_mm_mul_round_sd(_mm_cvt_roundu64_sd(__m128d{}, r, RD), inv, RD), RD);
    q += q1;
    r -= q1 * b;
    return q + (uint64_t)(r >= b);
}

uint64_t foo(uint64_t a, uint64_t b, uint64_t c) {
    while (a > b) {
        a = div(a, c);
    }
    return a;
}

uint64_t bar(uint64_t a, uint64_t b, uint64_t c) {
    while (a > b) {
        a = a / c;
    }
    return a;
}
```
```asm
.LCPI0_0:
        .quad 0x3ff0000000000000
foo(unsigned long, unsigned long, unsigned long):
 cmp     rdi, rsi
        jbe     .LBB0_1
        vmovsd  xmm2, qword ptr [rip + .LCPI0_0]
        vxorpd  xmm0, xmm0, xmm0
        vcvtusi2sd xmm1, xmm0, {ru-sae}, rdx
        vdivsd  xmm1, xmm2, xmm1, {rd-sae}
.LBB0_3:
        vcvtusi2sd      xmm2, xmm0, {rd-sae}, rdi
 vmulsd  xmm2, xmm2, xmm1, {rd-sae}
        vcvtsd2usi      rax, xmm2, {rd-sae}
        mov     rcx, rax
        imul    rcx, rdx
        sub rdi, rcx
        vcvtusi2sd      xmm2, xmm0, {rd-sae}, rdi
        vmulsd xmm2, xmm2, xmm1, {rd-sae}
        vcvtsd2usi      rcx, xmm2, {rd-sae}
 add     rax, rcx
        imul    rcx, rdx
        sub     rdi, rcx
 cmp     rdi, rdx
        sbb     rax, -1
        mov     rdi, rax
 cmp     rax, rsi
        ja      .LBB0_3
        ret
.LBB0_1:
 mov     rax, rdi
        ret

bar(unsigned long, unsigned long, unsigned long):
        mov     rax, rdi
        cmp     rdi, rsi
        jbe .LBB1_6
        mov     rcx, rdx
        jmp     .LBB1_2
.LBB1_4:
 xor     edx, edx
        div     rcx
        cmp     rax, rsi
        jbe .LBB1_6
.LBB1_2:
        mov     rdx, rax
        or      rdx, rcx
 shr     rdx, 32
        jne     .LBB1_4
        xor     edx, edx
 div     ecx
        cmp     rax, rsi
        ja      .LBB1_2
.LBB1_6:
 ret
```
_______________________________________________
llvm-bugs mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-bugs

Reply via email to