Search code examples
c#simdintrinsics

Are there macros for SIMD instruction sets?


Are there any macros that we can use for instruction set detection?

I know that we have the runtime ones:

if (Avx.IsSupported)
{
//...
}

but do we have defined symboles for that e.g.

#if AVX
//...
#endif

And if there are none, can we create ones or do we have a workaround for that?

NOTE

  • while playing with decompiler I found a weird "recursion ". But I think the ILSpy missed here.
.method public hidebysig specialname static 
    bool get_IsSupported () cil managed 
{
    // Method begins at RVA 0x142fa4
    // Code size 6 (0x6)
    .maxstack 8

    // return IsSupported;
    IL_0000: call bool System.Runtime.Intrinsics.X86.Avx::get_IsSupported()
    IL_0005: ret
} // end of method Avx::get_IsSupported
  • Also when I looked into a simple asm code I noticed the following:
public int F() 
{
    if (Avx.IsSupported)
        return 0;
    if (Avx2.IsSupported)
        return 1;

    return 2;
}

asm

Program.F()
    L0000: xor eax, eax
    L0002: ret

As you can see it somehow figured out that Avx is supported and didn't include the branches. Is this a normal and well defined behaviour?


Solution

  • Avx.IsSupported is a run-time feature because it needs to dynamically detect the capabilities of the target CPU where your code is actually being run.

    On the other hand, #if is a compile-time feature, conditional compilation. It's not really useful to have an AVX conditional compilation symbol and then just presume for the target CPU to do have support for AVX. It is simply better to check on run-time and behave accordingly.

    However, should you really need to use conditional compilation, you can always declare your own symbol.