BadProgrammer99
BadProgrammer99

Reputation: 847

Is reinterpret_cast<> safe or undefined on sse/avx types?

Is something like

__m128 a = something;
__m128i b = reinterpret_cast<__m128i>(a);

safe or undefined? If it is undefined, will it at least work on all of the major compilers (gcc,clang,msvc,icc)? I tested it on my computer with gcc and it works, but I'm not sure if its portable. I know that I can use _mm_castps_si128(), but because of templates, the first way happens to be more convenient.

Upvotes: 5

Views: 494

Answers (2)

rustyx
rustyx

Reputation: 85462

No it's not portable and the behavior is undefined; __m128 is for float and __m128i is for integer types, these are not compatible types.

In fact, it doesn't even compile in MSVC 2017:

error C2440: 'reinterpret_cast': cannot convert from '__m128' to '__m128i'

Use the cast intrinsic:

__m128 a = something;
__m128i b = _mm_castps_si128(a);

Upvotes: 4

Drew Dormann
Drew Dormann

Reputation: 63911

An integer type may be reinterpret_cast-ed to a pointer, a reference, or its own type.

Therefore, casting between two integer types is only well-defined if the compiler considers them to be the same type.

Upvotes: 0

Related Questions