3 ms·
One unfortunate issue / question: are compilers smart enough to emit tests for CPU support for these extensions? I see no mention of that, and if the answer is
by api 7y ago
One unfortunate issue / question: are compilers smart enough to emit tests for CPU support for these extensions? I see no mention of that, and if the answer is "no" you will find yourself being still forced to hand-roll this stuff.
Let's say I build a binary with AVX support. Will it run on a CPU without AVX support?
It's less of an issue with older SSE stuff that is effectively universal across all X64 chips, but it's a big issue with late SSE and AVX extensions.
- klodolph 7y agoHand-rolling is unnecessary and error-prone. It is better to leverage the compiler. There are a couple relevant GCC flags: -mcpu and -mtune. The -mcpu flag will specify which features it is allowed to assume are present. The blog post is using SSE instructions, I’m thinking SSE2 but that’s just from memory, and these days most people consider it eccentric to try and support CPUs without SSE2. There are a couple ways you can do the feature testing in your own program. You can make multiple copies of the function and compile them with different CPU targets, and then use something like void xor512a_avx(...) __attribute__((target("avx"))) { ... } if (__builtin_cpu_supports("avx")) { xor512a_avx(dst, src); } Alternatively, you can use something called function multiversioning, which will write the branch for you. I think this feature is present in both GCC and Clang. Also note that there are some unusual edge cases you may not have considered with feature detection. There’s a strong case to say that instructions like CPUID are the wrong way to go about it, and you should do things like use sysctl() on macOS. The risks in using CPUID are a bit esoteric in my opinion, though.
- mkj 7y agoIntel compilers have an -ax flag which will compile functions into several versions for different instructions. GCC has target_clones which can be set for particular functions. Both ways will choose the function to use at runtime based on the cpu.