Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 405
BadProgrammer99 Avatar asked Jul 06 '18 20:07

BadProgrammer99


People also ask

Is it safe to use reinterpret_cast?

The reinterpret_cast operator can be used for conversions such as char* to int* , or One_class* to Unrelated_class* , which are inherently unsafe. The result of a reinterpret_cast cannot safely be used for anything other than being cast back to its original type.

Can reinterpret_cast throw exception?

No. It is a purely compile-time construct.


1 Answers

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);
like image 164
rustyx Avatar answered Oct 11 '22 12:10

rustyx