by TekMol · 3y ago · 0 comments
Doesn't all CPUs offer a different set of opcodes? How can a compiler then work for different CPUs?
For example, this Wikipedia page is listing the CPUs that support instructions for fast SHA calculations:
https://en.wikipedia.org/wiki/Intel_SHA_extensions
How could a compiler ever use those, when not all CPUs support them?
In principle, you could distribute many different binaries optimized for different CPUs. However, the more common approach in high-performance software is to compile most of the program for a generic instruction set and write several versions of the hottest parts. Then you detect the supported CPU features at runtime and dispatch appropriately.
It generates code that works on 1) one CPU, or 2) a family of CPUs, or 3) (less commonly) multiple families of CPUs.
But not all CPUs.
I think you can see how 1) works. Plus, improved versions of a CPU are often backwards compatible, so if the program works on an older Intel x86-64 CPU than it very likely works on a newer one, or on an AMD x86-64 CPU or other compatible CPU.
2) works because programs can query the processor to see which additional features are supported. In your SHA extension example, https://www.intel.com/content/www/us/en/developer/articles/t... says:
> Availability of the Intel® SHA Extensions on a particular processor can be determined by checking the SHA CPUID bit in CPUID.(EAX=07H, ECX=0):EBX.SHA [bit 29].
It gives an example C function with inline assembly which uses the "cpuid" instruction to get that information:
int CheckForIntelShaExtensions() {
int a, b, c, d;
// Look for CPUID.7.0.EBX[29]
// EAX = 7, ECX = 0
a = 7;
c = 0;
asm volatile ("cpuid"
:"=a"(a), "=b"(b), "=c"(c), "=d"(d)
:"a"(a), "c"(c)
);
// Intel® SHA Extensions feature bit is EBX[29]
return ((b >> 29) & 1);
}
A compiler (or programmer) can have one code path execute if CheckForIntelShaExtensions() is true, and another if it's false.3) works in collaboration with the operating system. For example, on macOS the compiler can compile once for x86-64 and again for its "M" series chips and bundle the results into a single binary. The OS knows the CPU and can select the right compiled code to start.
Do note that Nuitka doesn't do any of this. It compiles Python to C code, then lets the C compiler handle the above.
and anything in .NET land since .NET Core will have a ton of SIMD in it
Though for highly specialized calculations like that. they're often written into popular libraries like OpenSSL with inline assembly for all relevant architectures.
https://stackoverflow.com/questions/47299458/how-can-i-deter...