As the title reads, I am trying to use STL vector with SIMD intrinsic data type. I know it is not a good practice due to the potential overhead of load/store, but I encountered a quite weird fault. Here is the code:
#include "immintrin.h"
#include <vector>
#include <stdio.h>
#define VL 8
int main () {
std::vector<__m256> vec_1(10);
std::vector<__m256> vec_2(10);
float * tmp_1 = new float[VL];
printf("vec_1[0]:\n");
_mm256_storeu_ps(tmp_1, vec_1[0]); // seems to go as expected
for (int i = 0; i < VL; ++i)
printf("%f ", tmp_1[i]);
printf("\n");
delete tmp_1;
float * tmp_2 = new float[VL];
printf("vec_2[0]:\n");
_mm256_storeu_ps(tmp_2, vec_2[0]); // segmentation fault
for (int i = 0; i < VL; ++i)
printf("%f ", tmp_2[i]);
printf("\n");
delete tmp_2;
return 0;
}
I compiled it using g++ -O3 -g -std=c++11 -mavx2 test.cpp -o test
. vec_1[0]
is printed as expected (all zeros), but segmentation fault happens when it comes to vec_2[0]
. I thought it was the alignment issue, but instead of _mm256_store_ps
, I used _mm256_storeu_ps
, which does not require alignment.
It is a Intel Haswell architecture with AVX2 extension. GCC version is 4.8.5.
Any possible clue is welcome.
fill_n
on misaligned__m256
, I suppose. If I wrap your__m256
instd::aligned_storage<sizeof(__m256), alignof(__m256)>
(andreinterpret_cast
where appropriate), it runs fine and prints all zeroes. So presumably, yes, it is an alignment issue. I'm not sure how these things work, but_mm256_storeu_ps
takes its 2nd argument by value, which is hence copied from the underlying vector byoperator[]
, whose elements aren't aligned!typedef std::aligned_storage<sizeof(__m256), alignof(__m256)>::type __m256_pod;
thenstd::vector<__m256_pod> vec_2(10);
and_mm256_storeu_ps(tmp_2, reinterpret_cast<__m256&>(vec_2[0]));
but segmentation fault still happens at the same line. Did I do something wrong? I am sorry I am new to this.aligned_allocator
and pass it as template argument to your vector.vec_2[0]
requires the memory used byvec_2
to be aligned, since gcc will emit aligned loads/stores when dereferencing__m256*
. If you check with a debugger, you should see the segfault on a load insn. If you use a vector offloat
, you could use unaligned load intrinsics on it. (But it would be more sensible to avoid the overhead of dynamically allocating memory at all for small fixed sizes. Just use a local array. If it's an array of float, usealignas(32) float foo[VL*8]
, otherwise__m256 foo[VL]
should correctly inherit the alignment requirement of__m256
).