0

I have a strange behaviour when trying to cast a vector __m256i to an int array. There is no warning and this is really alarming. It happens with gcc 9/10 and with optimization higher than 1 (see below).

int main(int argc, char** argv)
{

    int array[8] = {10, 20, 30, 40, 50, 60, 70, 80};
    __m256i values = _mm256_loadu_si256((__m256i*) array);

    int* ptr = (int*) &values; // this cast seems to be problematic

    printf("WRONG:\n");

    for (int i = 0; i < 8; i++)
        printf("%d ", ptr[i]);

    printf("\n");
  
    int ptr1[8];
    _mm256_storeu_si256 ( (__m256i*)ptr1, values);

    printf("GOOD:\n");

    for (int i = 0; i < 8; i++)
      printf("%d ", ptr1[i]);
  
    printf("\n");

}

Try to compile with this:

gcc -g -O3 -march=broadwell main.c -o main

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
a.dibacco
  • 490
  • 3
  • 13
  • That's a strict-aliasing violations like `*(int*)my_float`, which GCC doesn't warn about even with `-Wall -Wextra -pedantic`. ( https://godbolt.org/z/v7PYrKTer ). See [print a \_\_m128i variable](https://stackoverflow.com/a/46752535) for details. With your original code, we can see that it's just reading uninitialized stack space. https://godbolt.org/z/Ez1T4P8r3 – Peter Cordes Mar 05 '22 at 19:07
  • Also note that you just cast an int *pointer* to point into the `__m256i` object. That's not an array. It is possible to cast something to an array type, like `*(const char (*)[]) ptr` (by casting it to a pointer-to-array and dereferencing it), but there's no much you can do with that because C arrays aren't really first-class types. Minor point, just a terminology nitpick, not a suggestion that that's in any way relevant. It's mostly useful for 2D arrays (arrays of arrays and pointers to arrays), and [inline asm](https://stackoverflow.com/q/56432259) – Peter Cordes Mar 05 '22 at 19:32

0 Answers0