by neonsunset · 2y ago · 0 comments
https://github.com/dotnet/runtime/blob/main/docs/coding-guid...
Here's an example of "checked" sum over a span of integers that uses platform-specific vector width:
https://github.com/dotnet/runtime/blob/main/src/libraries/Sy...
Other examples:
CRC64 https://github.com/dotnet/runtime/blob/main/src/libraries/Sy...
Hamming distance https://github.com/dotnet/runtime/blob/main/src/libraries/Sy...
Default syntax is a bit ugly in my opinion, but it can be significantly improved with helper methods like here where the code is a port of simdutf's UTF-8 code point counting: https://github.com/U8String/U8String/blob/main/Sources/U8Str...
There are more advanced scenarios. Bepuphysics2 engine heavily leverages SIMD to perform as fast as PhysX's CPU back-end: https://github.com/bepu/bepuphysics2/blob/master/BepuPhysics...
Note that practically none of these need to reach out to platform-specific intrinsics (except for replacing movemask emulation with efficient ARM64 alternative) and use the same path for all platforms, varied by vector width rather than specific ISA.
There are no private SIMD APIs save for sequence comparison intrisic for unrolling against known lengths which JIT/ILC does for spans and strings.
Because pretty much every type that has linear memory can be represented as span, it means that every span is amenable to pointer (byref) arithmetics which you then use to write a SIMD routine. e.g.:
var text = "Hello, World! Hello, World!";
var span = MemoryMarshal.Cast<char, ushort>(text);
ref readonly var ptr = ref span[0];
var chunk = Vector128.LoadUnsafe(in ptr);
var needle = Vector128.Create((ushort)',');
var comparison = Vector128.Equals(chunk, needle);
var offset = uint.TrailingZeroCount(comparison.ExtractMostSignificantBits());
Console.WriteLine(text[..(int)offset]);
If you have doubts regarding codegen quality, take a look at: https://godbolt.org/z/b97zjfTP7
The above vector API calls are lowered to lines 17-22.You also noted the lack of ability to express numeric properties of T within generic context. This was indeed true, and this limitation was eventually addressed by generic math feature. There are INumber<T>, IBinaryInteger<T> and others to constrain the T on, which bring the comparison operators you were looking for.
In general, the knowledge around vectorized code has substantially improved within the community, and it is used quite more liberally nowadays by those who are aware of it.