有时编译器会生成含有奇怪指令重复的代码,这些指令可以安全地被删除。请看以下代码:
int gcd(unsigned x, unsigned y) {
return x == 0 ? y : gcd(y % x, x);
}
这是汇编代码(使用启用了优化的clang 5.0生成,链接):
gcd(unsigned int, unsigned int): # @gcd(unsigned int, unsigned int)
mov eax, esi
mov edx, edi
test edx, edx
je .LBB0_1
.LBB0_2: # =>This Inner Loop Header: Depth=1
mov ecx, edx
xor edx, edx
div ecx
test edx, edx
mov eax, ecx
jne .LBB0_2
mov eax, ecx
ret
.LBB0_1:
ret
在下面的代码片段中: mov eax, ecx
jne .LBB0_2
mov eax, ecx
如果跳跃不发生,eax
会被重新分配,但没有明显的原因。
另一个例子是函数末尾有两个ret:其中一个同样可以完美地工作。
是编译器不够智能还是有理由不删除重复部分?
clang
,c
orc++
? - Khalil Khalaf