【发布时间】:2018-09-20 12:35:36
【问题描述】:
在 OSX High Sierra 上使用 clang 编译带有 -O3 的代码时遇到了一个有趣的问题。代码是这样的:
#include <stdint.h>
#include <limits.h> /* for CHAR_BIT */
#include <stdio.h> /* for printf() */
#include <stddef.h> /* for size_t */
uint64_t get_morton_code(uint16_t x, uint16_t y, uint16_t z)
{
/* Returns the number formed by interleaving the bits in x, y, and z, also
* known as the morton code.
*
* See https://graphics.stanford.edu/~seander/bithacks.html#InterleaveTableO
bvious.
*/
size_t i;
uint64_t a = 0;
for (i = 0; i < sizeof(x)*CHAR_BIT; i++) {
a |= (x & 1U << i) << (2*i) | (y & 1U << i) << (2*i + 1) | (z & 1U << i)
<< (2*i + 2);
}
return a;
}
int main(int argc, char **argv)
{
printf("get_morton_code(99,159,46) = %llu\n", get_morton_code(99,159,46));
return 0;
}
使用cc -O1 -o test_morton_code test_morton_code.c 编译时,我得到以下输出:
get_morton_code(99,159,46) = 4631995
这是正确的。但是,使用cc -O3 -o test_morton_code test_morton_code.c 编译时:
get_morton_code(99,159,46) = 4294967295
这是错误的。
同样奇怪的是,当从-O2 切换到-O3 时,这个错误出现在我的代码中,而在上面的最小工作示例中,它出现在从-O1 切换到-O2 时。
这是编译器优化中的一个错误,还是我做了一些愚蠢的事情,只有在编译器更积极地优化时才会出现?
我正在使用以下版本的 clang:
snotdaqs-iMac:snoFitter snoperator$ cc --version
Apple LLVM version 9.1.0 (clang-902.0.39.1)
Target: x86_64-apple-darwin17.5.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
【问题讨论】:
标签: c optimization clang compiler-optimization