One framework to rule us all…
WPF

VS2012 XMTransposeMatrix memory alignment error

Working on a simple 3D engine I occasionally stumbled upon an invalid access exception on a XMMATRIX transpose operation while invoking rendering in dirty state shapes in my scene. At first I thought it was something on my side, and rolled back some code to sort things out. But I realized the issue persisted. I ended up reducing the scope scope of the problem to the the XMTransposeMatrix call. Here’s an extract of the DirectXMatrix library code where the error is being raised:

SSE needs data to be aligned on 16 bytes boundary, not 16 bits, that’s why the shifting is taking place there. But somehow, when byte shuffling is executing to transpose all matrix values, the values aren’t aligned. Inspecting XMMATRIX:

We can see that XMMATRIX structure is declared with _declspec(align(16)). In case you don’t know, this attribute is convenient because writing applications that use the latest processor instructions introduces some new constraints and issues. In particular, many new instructions require that data must be aligned to 16-byte boundaries. Additionally, by aligning frequently used data to the cache line size of a specific processor, you improve cache performance.

If besides this declaration I’m still experiencing  alignment errors, I’m guessing something went wrong along the way. Not understanding the reason for this erratic behavior I googled a bit and turns out to be a known issue, already reported and fixed by Microsoft. It will supposedly be released in a next version of the compiler. The next question is… What can I do about it in the meantime?

For starters, compiling in x64 could fix the issue since data would be 32bit aligned. Or, I could try using _declspec() myself. I guess I’ll go with the first, since I want to work in 64 bit instruction set either way.

Digg This
Reddit This
Stumble Now!
Buzz This
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Kick It on DotNetKicks.com
Shout it
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)

Leave a Reply