|
auveh
Auto-vectorization helpers for C++
|
This library implements a few macros and functions to assist compiler auto-vectorization. Most of our loops are simple enough that auto-vectorization does a pretty good job, effectively giving us a free optimization at -O2 or higher in recent versions of clang and GCC. We prefer auto-vectorization over explicit use of intrinsics as the former is more portable, does not introduce any third-party dependencies, and takes advantage of the compiler's cost model to determine if vectorization is actually beneficial.
Most data-parallel loops can be easily auto-vectorized but occasionally some assistance is required. Consider the following loop for updating a vector at unique indices:
Normally, the compiler cannot assume that iterations of the above loop are independent, as it does not know that indices contains only unique values. However, as we know that the indices are unique, we can instruct the compiler to ignore these potential dependencies by adding the AUVEH_NODEP macro before the loop. This expands to a compiler-specific pragma equivalent to GCC's #pragma GCC ivdep, which may be enough to induce the compiler to use scatter/gather instructions. For example, testing the code below on Godbolt indicates that clang will use vgatherdpd on recent Intel CPUs.
The AUVEH_NODEP macro can still be useful for simple loops that are obviously vectorizable. In the example below, we can guarantee that left and right are different vectors from output. Adding the macro allows both clang and GCC to omit aliasing checks for a smaller, more efficient binary.
On occasion, we might need to know the native vector width, e.g., 128 bits for SSE, 256 for AVX, and so on. We can get this by calling vector_width() with the type of interest:
For example, when processing data in blocks, we might choose a block size that is a multiple of the vector width. This improves the performance of auto-vectorized code by reducing the number of entries into an epilogue loop.
Another application is to use the native vector width to define the number of accumulators for a summation. This strongly encourages the auto-vectorizer to use the appropriate vector instructions, albeit at the cost of returning slightly different outputs for machines with different register vector widths.
FetchContentIf you're using CMake, you just need to add something like this to your CMakeLists.txt:
Then you can link to auveh to make the headers available during compilation:
find_package()You can install the library by cloning a suitable version of this repository and running the following commands:
Then you can use find_package() as usual:
If you're not using CMake, the simple approach is to just copy the files in the include/ subdirectory - either directly or with Git submodules - and include their path during compilation with, e.g., GCC's -I.