Consider the following code:
#include <limits>
#include <cstdint>
using T = uint32_t; // or uint64_t
T shift(T x, T y, T n)
{
return (x >> n) | (y << (std::numeric_limits<T>::digits - n));
}
According to godbolt, clang 3.8.1 generates the following assembly code for -O1, -O2, -O3:
shift(unsigned int, unsigned int, unsigned int):
movb %dl, %cl
shrdl %cl, %esi, %edi
movl %edi, %eax
retq
While gcc 6.2 (even with -mtune=haswell
) generates:
shift(unsigned int, unsigned int, unsigned int):
movl $32, %ecx
subl %edx, %ecx
sall %cl, %esi
movl %edx, %ecx
shrl %cl, %edi
movl %esi, %eax
orl %edi, %eax
ret
This seems far less optimized, since SHRD is very fast on Intel Sandybridge and later. Is there anyway to rewrite the function to facilitate optimization by compilers (and in particular gcc) and to favor the use of SHLD/SHRD assembly instructions?
Or are there any gcc -mtune
or other options that would encourage gcc to tune better for modern Intel CPUs?
With -march=haswell
, it emits BMI2 shlx / shrx, but still not shrd.
shrd
takes 4 cycles to resolve.sal
takes 2. My guess is that gcc takes 7 cycles and clang takes 5. (Skylake) On e.g. Bulldozer gcc is faster becausesal/shr
is a single cycle andshrd
is 8.SHL/SHR r,cl
is 3 uops, 2c latency, one per 2c throughput. I forget if clang's silly 8bit mov can be eliminated at register-rename time, so clang's code is either 4c or 3c latency on SKL, with much better throughput.shrd r,r,i
, notshrd r,r,cl
. The variable-count version is still 4 uops, with 4c latency, and not the best option when BMI2 is available..ods
format, OpenOffice, but you could easily convert it to Excel if you want). My mistake was that I remembered testing SHRD specifically on my own SnB hardware, and that it was efficient on SnB (and that IACA was wrong for SHRD/SHLD on SnB). But what I was remembering was the immediate-count version, so I only saw what I was expecting to see in Agner's spreadsheet. :/