Search code examples
c++visual-c++clangsseintrinsics

Accessing components of __m128d intrinsics in Visual Studio vs. Xcode doesn't work the same way?


The below code works fine with Xcode:

const __m128d source      = { x, y };
const double  destination = source[0];    // Read the "x" from "source"

In latest version of Visual Studio I get the following error message from the compiler: ---> No operator "[]" matches these operands.

According to all examples I've found from the web the above should be the standard way of accessing those components inside __m128d, so what is causing the error and how to fix it?


Solution

  • The source[i] syntax is a GCC/Clang extension which does not work with MSVC.

    To extract the lower double component of a __m128d vector use

    double lower = _mm_cvtsd_f64(source);
    

    For the upper component, you need to first move it to the lower part, e.g., using:

    double higher = _mm_cvtsd_f64( // extract value
                      _mm_castps_pd( // reinterpret as __m128d
                        _mm_movehl_ps( // move high half of second argument to lower half
                          _mm_setzero_ps(), // could be an arbitrary vector 
                          _mm_castpd_ps(source)
                    ) ) );
    

    Instead of _movehl_ps you could also use a _mm_shuffle_pd instruction. Also, if you actually intend to store the upper element to memory, you could use:

    double dest;   // target somewhere in memory
    _mm_storeh_pd(&dest, source);