我在clang优化中发现了一个奇怪的错误。这是代码:
#include <iostream>
unsigned int rot2(unsigned int a, size_t k) {
return (a >> k) | (a << (sizeof(unsigned int) * 8 - k));
}
int main() {
unsigned int x;
std::cin >> x;
auto n = rot2(x, 5);
std::cout << n;
}
这是使用-O3
选项(来自godbolt)为clang 8.0.0和9.0.0生成的程序集:
rot2(unsigned int, unsigned long): # @rot2(unsigned int, unsigned long)
mov rcx, rsi
mov eax, edi
ror eax, cl
ret
main: # @main
push rax
lea rsi, [rsp + 4]
mov edi, offset std::cin
call std::basic_istream<char, std::char_traits<char> >& std::basic_istream<char, std::char_traits<char> >::_M_extract<unsigned int>(unsigned int&)
mov esi, dword ptr [rsp + 4]
mov rax, rsi
shr rax, 5
shl esi, 27
or rsi, rax
mov edi, offset std::cout
call std::basic_ostream<char, std::char_traits<char> >& std::basic_ostream<char, std::char_traits<char> >::_M_insert<unsigned long>(unsigned long)
xor eax, eax
pop rcx
ret
如您所见,rot2
方法已正确优化,并使用了ror
指令。但是令我惊讶的是,main()
中未使用此指令,并且整个代码都使用shift和or指令。
知道这个奇怪的错误为什么会发生吗? gcc和msvc不会犯这个奇怪的错误。