superbriggs
superbriggs

Reputation: 659

C: Writing code which can be auto vectorized, nested loop, GCC

I am trying to write some C code which can be vectorized. This is the loop I am trying:

for(jj=0;jj<params.nx;jj++)
    for(kk=0;kk<NSPEEDS;kk++)
        local_density_vec[jj] += tmp_cells_chunk[jj].speeds[kk];

GCC gives me the following message when run with the -ftree-vectorizer-verbose=5 flag http://pastebin.com/RfCc04aS.

How can I rewrite it in order that it can be auto vectorized. NSPEEDS is 5.

EDIT:

I've continued to work on it, and I don't seem to be able to vectorize anything with .speeds[kk]. Is there a way of restructuring it so that it can?

Upvotes: 4

Views: 4271

Answers (1)

hdante
hdante

Reputation: 8020

for (jj = 0; jj < nx; jj++) {
        partial = 0.0f;
        fp = c[jj].speeds;
        for (kk = 0; kk < M; kk++)
                partial += fp[kk];
        out[jj] = partial;
}
(...)
Calculated minimum iters for profitability: 12

36:   Profitability threshold = 11

Vectorizing loop at autovect.c:36

36: Profitability threshold is 11 loop iterations.
36: LOOP VECTORIZED.

Important points:

1) In your dump, the loop was considered "complicated access pattern" (see the last line of your log). As already commented, this is related to the compiler being unable to verify aliasing. For "simple" access patterns, see: http://gcc.gnu.org/projects/tree-ssa/vectorization.html#vectorizab

2) My example loop required 12 iterations for vectorization to be useful. Since NSPEEDS == 5, the compiler would loose time if it vectorized yours.

3) I was only able to vectorize my loop after I added -funsafe-math-optimizations. I believe this is required due to either different rounding or associativity behavior with the resulting vector operations. See, for example: http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

4) If you reverse the loop you could have problems with "complicated" access patterns again. As already commented, you may need to reverse the array organization. Check the gcc vectorization docs about strided accesses to check if you can match one of the patterns.

For completeness, here is the complete example: http://pastebin.com/CWhyqUny

Upvotes: 4

Related Questions