2

When using SSE2 intrinsic functions to do bit-wise operations, one has to cast pointers from int* to __m128i*. Does this code break strict aliasing rule?

void bit_twiddling_func(int size, int const* input, int* output) {
    const __m128* x = (const __m128*)input;
    const __m128* y = (const __m128*)output;

    for (int i=0; i < size/4; ++i, ++x, ++y) {
        __m128i x4 = _mm_load_si128(x); // load 4 integers

        // do some bit twiddling

        _mm_store_si128(y, x4); // store 4 integers
    }
}

Thank you!

pic11
  • 14,267
  • 21
  • 83
  • 119

1 Answers1

2

Yes; it breaks strict aliasing rules. Two different types can't point to the same location in memory. Here you have x pointing to input and y pointing to output, but they're of differing types.

You could change the signature of your function to take __m128* parameters, but it's probably easiest to leave it be. It'll likely work just fine if you're careful that the input/output arguments point to memory with the proper alignment and size constraints (i.e. they should each point to something where your loop doesn't index off the end or load uninitialized data.)

brandx
  • 1,053
  • 12
  • 10
  • 2
    Technically it only breaks the strict aliasing rules when the type is actually accessed through the pointer, not when the pointer is created - so in this case it would be within `_mm_load_si128()`. – caf Jun 23 '11 at 04:29
  • 1
    Technically it also only breaks strict aliasing rules when in C99 -- C89 and C++ do not have such restrictions. – Billy ONeal Jun 23 '11 at 05:19
  • 1
    @Billy: both C89 and C++ have those restrictions. – zvrba Jun 23 '11 at 07:31
  • @zvrba: Can you find a reference then? I don't see any such restrictions in my copy of the standard. The word "alias" is used only to refer to namespace aliases. The word "pun" (e.g. type punning) exists only as a part of the word "punct". It's also not mentioned during the discussion of the casting operators. – Billy ONeal Jun 23 '11 at 16:43
  • 1
    The following PDF has a citation and a reference to the standard: http://dbp-consulting.com/StrictAliasing.pdf ; the relevant section is 6.5 Expressions. – zvrba Jun 23 '11 at 18:50