Search code examples
c++creferenceclangsimd

What is __ext_vector_type__ and simd?


I'm playing with Apple Metal API along with so called simd library. There's such code in a header:

typedef __attribute__((__ext_vector_type__(3))) float vector_float3;

And I'm curious what it actually does and why the compiler doesn't allow references to vector_float3 in a function's argument or in the next manner:

vector_float3  v;
vector_float3& ref = v;

Solution

  • It appears to be a clang extension to GNU C vector extensions, where something like this would be normal:

    typedef int v4si __attribute__ ((vector_size (16)));
    

    Googling for ext_vector_type without the leading/trailing underscores found the Clang docs. (The underscores version is usable in headers even if some program had used #define on the non-underscores version of the token. But names with leading underscores in the global namespace are reserved for the implementation.)

    My best guess is that it's a way to let the compiler know you only care about the value of the first 3 elements of a 4 element SIMD register. So it can potentially do optimizations that leave different garbage in the high element than the source would have.


    why the compiler doesn't allow references to vector_float3

    Works for me with clang3.8. Try a different compiler.

    typedef __attribute__((__ext_vector_type__(3))) float vector_float3;
    
    int foo(vector_float3 &arg) {
      vector_float3  v;
      vector_float3& ref = v;  // unused, but syntactically valid
      return arg[0];           // return the low element of the vector, converted to an integer.  GNU C vector-extensions syntax.
    }
    

    compiles to the following asm on the Godbolt compiler explorer

        # targeting x86-64 SystemV ABI (so the first integer/pointer arg is in rdi)
        cvttss2si       eax, dword ptr [rdi]
        ret