Auto-Vectorize comparison

不想你离开。 提交于 2019-12-18 09:17:22

问题


I've problems getting my g++ 5.4 use vectorization for comparison. Basically I want to compare 4 unsigned ints using vectorization. My first approach was straight forward:

bool compare(unsigned int const pX[4]) {
    bool c1 = (temp[0] < 1);
    bool c2 = (temp[1] < 2);
    bool c3 = (temp[2] < 3);
    bool c4 = (temp[3] < 4); 
    return c1 && c2 && c3 && c4;
}

Compiling with g++ -std=c++11 -Wall -O3 -funroll-loops -march=native -mtune=native -ftree-vectorize -msse -msse2 -ffast-math -fopt-info-vec-missed told be, that it could not vectorize the comparison due to misaligned data:

main.cpp:5:17: note: not vectorized: failed to find SLP opportunities in basic block.
main.cpp:5:17: note: misalign = 0 bytes of ref MEM[(const unsigned int *)&x]
main.cpp:5:17: note: misalign = 4 bytes of ref MEM[(const unsigned int *)&x + 4B]
main.cpp:5:17: note: misalign = 8 bytes of ref MEM[(const unsigned int *)&x + 8B]
main.cpp:5:17: note: misalign = 12 bytes of ref MEM[(const unsigned int *)&x + 12B]

Thus my second attempt was to tell g++ to align the data and use a temporary array:

bool compare(unsigned int const pX[4] ) {
    unsigned int temp[4] __attribute__ ((aligned(16)));
    temp[0] = pX[0];
    temp[1] = pX[1];
    temp[2] = pX[2];
    temp[3] = pX[3];

    bool c1 = (temp[0] < 1);
    bool c2 = (temp[1] < 2);
    bool c3 = (temp[2] < 3);
    bool c4 = (temp[3] < 4); 
    return c1 && c2 && c3 && c4;
}

However, same output. AVX2 is supported by my CPU and intel intrinsic guide tells me, there is e.g. _mm256_cmpgt_epi8/16/32/64 for comparison. Any idea how to tell the g++ to use this?


回答1:


Okay, apparently the compiler does not like "unrolled loops". This works for me:

bool compare(signed int const pX[8]) {
    signed int const w[] __attribute__((aligned(32))) = {1,2,3,4,5,6,7,8};
    signed int out[8] __attribute__((aligned(32)));

    for (unsigned int i = 0; i < 8; ++i) {
        out[i] = (pX[i] <= w[i]);
    }

    bool temp = true;
    for (unsigned int i = 0; i < 8; ++i) {
        temp = temp && out[i];
        if (!temp) {
            return false;
        }
    }
    return true;
}

Please note, that out is also a signed int. Now I'll just need a fast way to combine the result saved in out



来源:https://stackoverflow.com/questions/41002949/auto-vectorize-comparison

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!