4

我正在尝试让 VC++ 2012 自动矢量化一个看起来有点像这样的循环(实际上正在进行有趣的计算,但为了尽可能地提出问题,它们被省略了)。

parameters:
int period;
unsigned char* out_array;
unsigned char* in_array1;
unsigned char* in_array2;
unsigned char* in_array3;

for (int x = 0; x < width; ++x)
{
   int index = period * (x / 2);

   out_array[0] = in_array1[x];
   out_array[1] = in_array2[index];
   out_array[2] = in_array3[index];
   out_array += 4;
}

我认为唯一阻碍矢量化的是out_array += 4,所以我做了一个内部“展开”循环,希望至少可以矢量化一个:

for (int x = 0; x < width; ++x)
{
   for (int xx = 0; xx < 4; ++xx)
   {
       int index = period * ((xx + x) / 2);

       unsigned char* pout_array = out_array + (4 * xx);
       pout_array[0] = in_array1[xx + x];
       pout_array[1] = in_array2[index];
       pout_array[2] = in_array3[index];
   }
   out_array += 16;
}

但是当我使用 运行编译器时/Qvect-report:2,它告诉我由于错误代码 1200 无法对内部循环进行矢量化。错误代码 1200 指出:

循环包含阻止矢量化的循环携带的数据依赖性。循环的不同迭代相互干扰,因此对循环进行矢量化会产生错误的答案,并且自动矢量化器无法向自己证明不存在这种数据依赖性。

我不明白这一点。显然,这个循环的每次迭代都是独立的。如何让 Visual Studio 对其进行矢量化?

4

1 回答 1

3

它不能向量化的主要原因是,正如所写的那样,编译器不能消除 out_array[n] 不是 in_arrayX[m] 的可能性,所以它必须坚持你的顺序排序。

您可以使用“__restrict”或“restrict”关键字为编译器解决此问题,这是对编译器的承诺,您只会以确保 out_array 与其他三个指针中的任何一个都不相同的方式调用它。您可能还想慷慨地使用“const”修饰符来帮助编译器:

void func(const int period,
    unsigned char* __restrict out_array,
    const unsigned char* in_array1,
    const unsigned char* in_array2,
    const unsigned char* in_array3)
{
   ...
   //mark 'width' as 'const' if possible:
   const int width = ...;
   for (int x = 0; x < width; ++x)
   {
       const int index = period * (x / 2);

       out_array[(x* 4) + 0] = in_array1[x];
       out_array[(x* 4) + 1] = in_array2[index];
       out_array[(x* 4) + 2] = in_array3[index];
   }
}
于 2013-05-21T04:02:58.643 回答