Search code examples
c++visual-c++intrinsics

MSVC 2019 _fxrstor64 and _fxsave64 intrinsics availability


What are the minimum preprocessor checks I need to make to be sure the compiler is MSVC2019 and that the _fxrstor64 and _fxsave64 intrinsics are available for use?


Solution

  • To check that you have (at least) the MSVC 2019 compiler, you should use the following:

    #if !defined(_MSC_VER) || (_MSC_VER < 1900)
    #error "Not MSVC or MSVC is too old"
    #endif
    

    For the _fxrstor64 and _fxsave64 intrinsics to be available to MSVC, you need to check that the "immintrin.h" header has been included:

    #ifndef _INCLUDED_IMM
    #error "Haven't included immintrin.h"
    #endif
    

    You also (perhaps obviously) need to be compiling for the x64 architecture:

    #ifndef _M_X64
    #error "Wrong target architetcture!"
    #endif
    

    You could put all those checks into one test, as follows:

    #if defined(_MSC_VER) && (_MSC_VER >= 1900) && defined(_INCLUDED_IMM) && defined(_M_X64)
        // OK
    #else
        #error "Wrong compiler or target architecture, or missing header file."
    #endif
    

    Note that the _INCLUDED_IMM token is specific to the MSVC compiler; for example, clang-cl uses __IMMINTRIN_H. So, if you also want to enable other, MSVC-compatible compilers, you'll need to add optional checks for each of their own tokens (by looking in the "immintrin.h" header each one uses).


    As noted in the comments, it would likely be more sensible to explicitly #include <immintrin.h> once the other three checks have been made and passed (the include guards in that header would handle any multiple inclusions). So:

    #if defined(_MSC_VER) && (_MSC_VER >= 1900) && defined(_M_X64)
        #include <immintrin.h> // All good!
    #else
       // TODO: allow GCC / clang / ICC which also provide _fxsave64 in immintrin.h
        #error "Wrong compiler/version, or not x86-64."
    #endif
    

    (This also gets round the issue of different implementations using different tokens to signal inclusion of that header file.)