gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:26:24 25 4
gpt4 key购买 nike

谁能帮我理解使用 asm block 进行 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 instructionEDX:EAX / (src) => 商(EAX)和除数(EDX)。参见 When and why do we sign extend and use cdq with mul/div?

"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 ,或将输入转换为无符号。或者,也许出于某些奇怪的原因,他们真的想要带有负输入的奇怪结果。

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

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

关于c++ - 在 c++ 中使用 x86 DIV 的这个 asm block 有什么用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52635251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com