Skip to content
systemcoding.dev
Performance

Get GCC and Clang to Auto-Vectorise Your Loops

Turn on auto-vectorization in GCC and Clang, read the optimization reports that say why a loop was skipped, and set the flags that matter, including -march.

7 min read
Summarize in AI
Flat illustration of source code passing through a compiler and linker into a binary, with the GNU, LLVM and C logos.

Before writing intrinsics, check whether the compiler will do the job. GCC and Clang both contain loop vectorizers that turn a simple scalar loop into SIMD code, and for loops of the form "do the same arithmetic on each element of an array" they usually succeed. The skill is knowing how to ask for it, how to find out what happened, and how to read the reasons the compiler gives when it declines. This post covers the flags, the reports in both compilers, and the habits that make a loop easy to vectorize. We use GCC 15 and Clang 20 on x86-64, and the same flags apply on AArch64 with a different -march. The next post in this cluster covers restructuring loops that fail.

Which flags turn it on

GCC enables the loop vectorizer at -O3, and since GCC 12 also at -O2 with a very cheap cost model, which vectorizes only when it can prove the result needs no extra code, such as a runtime check or a scalar epilogue larger than the savings. The pass is -ftree-vectorize, and -fno-tree-vectorize turns it off, which is the way to produce a scalar baseline for comparison. Clang enables the loop vectorizer and the SLP vectorizer, which combines independent scalar operations into vectors, at -O2 and above, controlled by -fvectorize and -fslp-vectorize.

The target matters as much as the optimization level. By default on x86-64, both compilers assume only SSE2, so they produce 128-bit vector code and no AVX2. Tell the compiler what your machine supports:

Shell
gcc   -O3 -march=native -o prog prog.c
clang -O3 -march=native -o prog prog.c

-march=native selects every instruction set the build machine supports, which makes the binary run only on similar machines, so use it for local experiments and choose an explicit level such as -march=x86-64-v3 for distribution. The x86-64-v2, v3 and v4 levels are defined in the x86-64 psABI and supported by GCC 11 and Clang 12 and later. Level v3 means AVX2, FMA and BMI2. On AArch64, -march=armv8.2-a+dotprod and similar strings pick extensions, and base NEON needs nothing.

See what the compiler did

Do not guess. Both compilers emit reports. GCC prints vectorization decisions with -fopt-info-vec:

Shell
gcc -O3 -march=native -fopt-info-vec-optimized -fopt-info-vec-missed -c loop.c

Consider a simple loop:

loop.cc
void saxpy(float *restrict y, const float *restrict x, float a, int n)
{
    for (int i = 0; i < n; ++i)
        y[i] = a * x[i] + y[i];
}

GCC reports a successful vectorization with a line of this form, the width depending on your target:

Text
loop.c:4:5: optimized: loop vectorized using 32 byte vectors

For a loop it cannot vectorize, -fopt-info-vec-missed prints a line with the reason, for example missed: couldn't vectorize loop followed by missed: not vectorized: unsupported data-type or not vectorized: control flow in loop. The messages come from the vectorizer's dependency and cost analysis, and the GCC internals documentation describes them. For more detail use -fopt-info-vec-all, and to dump the full analysis use -fdump-tree-vect-details, which writes a file next to the object.

Clang uses remark flags. -Rpass=loop-vectorize reports loops that were vectorized, -Rpass-missed=loop-vectorize reports loops that were not, and -Rpass-analysis=loop-vectorize explains why:

Shell
clang -O3 -march=native -Rpass=loop-vectorize -Rpass-missed=loop-vectorize -Rpass-analysis=loop-vectorize -c loop.c
Text
loop.c:4:5: remark: vectorized loop (vectorization width: 8, interleaved count: 4) [-Rpass=loop-vectorize]

The width is the number of elements per vector operation, and the interleaved count is how many independent vector chains the compiler unrolls to hide latency. A skipped loop reports a message such as loop not vectorized: could not determine number of loop iterations or loop not vectorized: cannot identify array bounds, and the analysis remark explains the blocker, such as an unsafe dependence or an unvectorizable call.

Finally, confirm in the assembly. Compile with -S and look for packed instructions such as vaddps with ymm registers, vfmadd231ps or mulps with xmm registers, which prove a vector loop exists. A scalar loop uses addss and mulss, with the s for scalar.

Habits that help the vectorizer

Use simple counted loops. A loop with a known trip count and a unit stride, for (i = 0; i < n; ++i), is the easy case. Loops whose exit depends on data, that modify the loop variable inside the body, or that use a non-unit stride are harder, and some are refused.

Give the compiler alias information. If the compiler cannot prove that the output array does not overlap the inputs, it must either insert a runtime check that compares addresses and chooses between a vector loop and a scalar one, or give up. Qualify pointers with restrict in C, or __restrict in C++, when it is true, as in the saxpy above. Mismatched promises are undefined behavior, so only add them when you know the arrays are distinct. The next post in this cluster goes into aliasing in detail.

Avoid function calls in the loop body. A call to an opaque function stops vectorization. Calls to math library functions such as sinf can be vectorized only if the compiler has a vector math library, such as GCC's -fno-math-errno together with libmvec on glibc, or the -fveclib option in Clang. Mark small helpers static inline so they inline.

Prefer arrays and indices over pointers that move. Pointer arithmetic in the loop is fine, but writing through a pointer that the compiler cannot relate to the base address hides the stride.

Keep the body free of data-dependent control flow. A simple if that selects a value, as in y[i] = x[i] > 0 ? x[i] : 0, vectorizes through a blend or a masked operation. A branch containing a function call, a loop or an early exit usually does not.

Use the right types. Mixing a 32-bit index with 64-bit arrays or a short with a float creates conversions that cost lanes. Use size_t or ptrdiff_t as the index type when the target is 64-bit, and keep element types uniform where you can.

Floating-point reductions need permission

A sum of floats is a reduction: sum += a[i]. Vectorizing it means keeping several partial sums and adding them in a different order, and floating-point addition is not associative, so the result can change. GCC and Clang therefore refuse to vectorize a float reduction by default, and the report says so, for example not vectorized: unsafe fp math optimization or cannot prove it is safe to reorder floating-point operations. You can allow it with -fassociative-math, which also requires -fno-signed-zeros and -fno-trapping-math in GCC, or by using -ffast-math, which enables those and more, including assumptions that NaNs and infinities do not occur. Clang accepts -fassociative-math with the same caveats, and offers #pragma clang loop vectorize(enable) and a reassociate fast-math flag per loop.

Because -ffast-math changes semantics across the whole translation unit, we prefer to enable only what the loop needs: write the reduction with several accumulators by hand, or use #pragma omp simd reduction(+:sum) with -fopenmp-simd, which grants permission for that loop alone, as the omp simd post in this cluster shows. Integer reductions have no such problem, since integer addition is associative, so those vectorize without any flag.

Checking the speed honestly

A vectorized loop is not automatically faster. Measure with and without: build once with -fno-tree-vectorize -fno-slp-vectorize and once with them on, with the same -march, and time them on arrays of realistic size. If the data does not fit in cache, both versions wait for memory, and the difference shrinks. We publish no numbers because they depend on your CPU, the array size and the compiler version.

Remember to check alignment and the tail. The compiler generates a scalar epilogue for the leftover elements and may generate a prologue to reach alignment, which for very short loops costs more than the vector body saves. Loop counts that the compiler cannot know, such as small n, benefit from the very cheap cost model in GCC 12 and later, which declines when the extra code would not pay off.

When the report says no

Read the reason, then change the code. Typical messages and their fixes: "unsafe dependence" means the compiler found two accesses that might overlap, so add restrict or restructure; "control flow in loop" means the body has a branch it cannot turn into a blend; "unsupported data type" means an operation like a 64-bit integer multiply that your target lacks in vector form; "number of iterations cannot be computed" means the loop exit depends on data. The restructuring post in this cluster works through the hard cases.

Share

Keep reading

Flat illustration of two options weighed side by side, with the C, C++ and Rust logos.
Performance

Spinlocks vs Mutexes: When Spinning Wins

A spinlock burns a core while it waits and a mutex sleeps. Compare their costs, write a correct C11 spinlock, and see when user-space spinning beats a mutex.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.