在 c++ 中使用 x86 DIV 的这个 asm 块有什么用?

What is the use of this asm block using x86 DIV in c++?

有人可以帮助我了解使用 asm 块进行 unsigned long long 乘法在性能方面的好处。它与竞争性编程优化有关。我猜它使乘法更快,但实际上我无法理解代码。

const int md = 998244353;
inline int mul(int a, int b)
{
#if !defined(_WIN32) || defined(_WIN64)
    return (int) ((long long) a * b % md);
#endif
    unsigned long long x = (long long) a * b;
    unsigned xh = (unsigned) (x >> 32), xl = (unsigned) x, d, m;
    asm(
            "divl %4; \n\t"
            : "=a" (d), "=d" (m)
            : "d" (xh), "a" (xl), "r" (md)
    );
    return m;
}

此代码实际上是 32 位的加速(其中 64x64 => 128 乘法不可用,因此编译器使用实际除法,但在 64 位上损失严重,其中编译器确实使用乘法逆来避免缓慢的硬件完全划分。Why does GCC use multiplication by a strange number in implementing integer division?

此外,如果任一输入在内联和常量传播后不是编译时常量,它应该真正使用 __builtin_constant_p 仅使用内联 asm。


但无论如何,x86's div instruction does EDX:EAX / (src) => quotient(EAX) and divisor(EDX). See

"a""d" 约束要求分别将 EAX 和 EDX 中的 64 位乘积的低半部分和高半部分作为输入。

来自Godbolt compiler explorer:

const int md = 998244353;
int mul(int a, int b)
{
#ifdef __x86_64__ // FIXME: just use the asm if defined(i386) to exclude all others
    return (int) ((long long) a * b % md);
#else
    if(__builtin_constant_p(a) && __builtin_constant_p(b))
        return (int) ((long long) a * b % md);
      // clang's builtin_constant_p is evaled before inlining, derp

    unsigned long long x = (long long) a * b;
    unsigned xh = (unsigned) (x >> 32), xl = (unsigned) x, d, m;
    asm(
            "divl %4; \n\t"
            : "=a" (d), "=d" (m)
            : "d" (xh), "a" (xl), "r" (md)
    );
    return m;
#endif
}

int main() {
    return mul(1,2);
}

gcc8.2 -O3 -m32编译如下:

mul(int, int):
    mov     eax, DWORD PTR [esp+8]
    mov     ecx, 998244353
    imul    DWORD PTR [esp+4]     # one-operand imul does EDX:EAX = EAX * src
    divl ecx;                     # EDX:EAX / ecx => EAX and EDX

    mov     eax, edx              # return the remainder
    ret

main:
    mov     eax, 2     # builtin_constant_p used the pure C, allowing constant-propagation
    ret

注意div无符号除法,所以这与C不匹配。C正在做有符号乘法和有符号除法. 这可能应该使用 idiv,或将输入转换为无符号。或者,也许出于某些奇怪的原因,他们真的想要带有负输入的奇怪结果。

那么,为什么编译器不能在没有内联 asm 的情况下自行发出它?因为如果商溢出目标寄存器 (al/ax/eax/rax),它会出现 #DE(除法异常)错误,而不是像所有其他整数指令一样静默截断。

64 位/32 位 => 32 位除法只有在您知道除数对于可能的被除数足够大时才是安全的。 (但即使是这样,gcc 仍然不知道寻找这种优化。例如,如果使用单个 muldiva * 7ULL / 9 不可能导致 #DE,如果a 是 32 位类型。但 gcc 仍会发出对 libgcc 辅助函数的调用。)