__m128i variables - members of class , alignment

__m128i variables - members of class , alignment

I have a class, where several members of the class are __m128i variables.The compiler somehow aligns this members to 8 bytes border instead of 16.When the code runs, it expects of course the variables to be aligned on 16 bytes border, so it crashes.Any idea why it behaves in this way? Any way to correct the problem?ThanksSorin

5 posts / 0 new
Last post
For more complete information about compiler optimizations, see our Optimization Notice.

Thanks Sorin,

Could you look at this URL http://msdn.microsoft.com/en-us/library/708ya3be(v=vs.80).aspx to see if it can help you? OR could you provide me a sample code that crashed with your code so that I can check here for you.

Thanks,
Wise

It is too big of a code to provide it.The link is not relevant.Try to understand!!!If a __m128i variable is local - in a function, then it is allocated on the boundaries of 16 bytes.But as a member of a class , the compiler aligns it to 8 bytes boundary.But SSE operations need to operate with 16 bytes alignment.The question - why does the compiler allocate at wrong alignment.ThanksSorin

If you aren't willing to tell anything about how you defined your class, it will be difficult to help you. If you want to compile with packed attributes, or to make it interoperable among various compilers, you will likely need to place all objects in descending order of alignment requirement (all 16-byte-aligned objects ahead of 8-byte aligned ones, .....) Alternately, you could assure that each object occupies a multiple of 16 bytes, but don't rely on the compiler and linker supplying padding.

Sorin,

Yelling at other people won't encourage them to help you.

If a __m128i variable is local and it is aligned to 16 bytes then it is most likely so by accident. To align local or global variables on Windows platform you need to use __declspec(align(n)) attribute where n is the desired alignment to be sure that the variable will always be aligned.

Class members cannot be aligned with __declspec(align(n)) because class objects can be allocated dynamically via new operator. It is actually new operator which returns 8 byte aligned memory so the object ends up unaligned.

The only solution is to overload new [] and delete [] operators with your own code which will allocate and return aligned memory for class object.

@Intel:
This question gets asked every few months on the forum (I already answered it once here). Someone should put the answer in some FAQ or sticky the thread.

Regards,
Igor Levicki

Leave a Comment

Please sign in to add a comment. Not a member? Join today