Memory Operations & Alignment¶
SIMD performance heavily depends on efficient data movement between system memory and vector registers. MIPP provides comprehensive primitives for aligned and unaligned contiguous memory access, strided and first-faulting accesses, non-contiguous indexed loads and stores (gather/scatter), and scalar element extraction.
1. Memory Alignment Requirements¶
SIMD vector instructions operate most efficiently when data addresses align with hardware vector register boundaries.
1.1. Required Alignment per Architecture¶
MIPP provides the mipp::req_alignment<ISA>() compile-time helper (and architecture sizing macros MIPP_[ISA]_VD_SIZE_BYTE) declaring the required byte alignment:
| Architecture | Vector Register Width | Required Alignment (req_alignment) |
|---|---|---|
| x86 SSE (1..4.2) | 128-bit | 16 bytes |
| ARM NEON | 128-bit | 16 bytes |
| x86 AVX / AVX2 | 256-bit | 32 bytes |
| x86 AVX-512 | 512-bit | 64 bytes |
| RISC-V Vector (RVV) | VLEN bits |
MIPP_RVV_VD_SIZE_BYTE |
| ARM SVE | VL bits |
MIPP_SVE_VD_SIZE_BYTE |
| Scalar Target | Sized to MIPP_SCALAR_SIZE |
MIPP_SCALAR_VD_SIZE_BYTE |
1.2. Allocating Aligned Memory¶
MIPP allocates memory aligned for its aligned loads and stores (on the register size of the target, MIPP_REQUIRED_ALIGNMENT bytes):
// Aligned on mipp::required_alignment() bytes (the register size, e.g. 32 bytes on AVX2):
float* data = mipp::malloc<float>(n_elements);
mipp::free(data);
// std::vector whose storage is aligned (mipp::allocator):
mipp::vector<float> v(n_elements);
const bool aligned = mipp::is_aligned(v.data()); // true
In C: mipp_malloc(bytes) (the size is rounded up to a multiple of the alignment, NULL on failure), mipp_free(p) and mipp_is_aligned(p). MIPP_REQUIRED_ALIGNMENT is MIPP_VD_SIZE_BYTE.
2. Contiguous Memory Operations¶
MIPP distinguishes between aligned (load, store) and unaligned (loadu, storeu) operations.
2.1. Aligned vs. Unaligned Access¶
| Operation | C API | C++ Functional API | C++ Object API | Pointer Requirement |
|---|---|---|---|---|
| Aligned Load | mipp_load_[type]_[lmul] |
mipp::load<T, LMUL>(ptr) |
mipp::load_obj<T, LMUL>(ptr) |
Aligned on the register size (§1.1) |
| Unaligned Load | mipp_loadu_[type]_[lmul] |
mipp::loadu<T, LMUL>(ptr) |
mipp::loadu_obj<T, LMUL>(ptr) or Vd<T, LMUL>(ptr) |
Any address |
| Aligned Store | mipp_store_[type]_[lmul] |
mipp::store(ptr, r) |
mipp::store(ptr, r) |
Aligned on the register size (§1.1) |
| Unaligned Store | mipp_storeu_[type]_[lmul] |
mipp::storeu(ptr, r) |
mipp::storeu(ptr, r) |
Any address |
Alignment is a precondition
Passing a misaligned pointer to load or store is undefined behavior. On x86 (SSE, AVX, AVX-512), the aligned instructions fault. On ARM and RISC-V, the hardware does not distinguish aligned and unaligned vector accesses, so the same code may run there and fail on x86: respect the contract on every target, and use loadu / storeu whenever alignment is not guaranteed. On modern CPUs, loadu / storeu on data that happens to be aligned cost the same as load / store.
For a multi-register vector (LMUL > 1), the alignment required is still the size of one register: each register is loaded from an aligned address.
2.2. Masked Loads & Stores¶
Loads exist in the Zero-Masked (Z, inactive lanes set to 0) and Source-Masked (S, inactive lanes taken from src) variants, stores in the Merge-Masked (M, memory of inactive lanes left unchanged) and Zero-Masked (Z, 0 written in the memory of inactive lanes) variants. The masked loads and the Merge-Masked stores read or write the active lanes only: inactive lanes are never accessed, so a mask can guard the end of an array (see the masked remainder example). The Zero-Masked store is a full store: it writes every lane, so it cannot guard the end of an array. The alignment contract of §2.1 is unchanged: masked load / store require an aligned pointer, masked loadu / storeu accept any address.
vm_float32_t m = mipp_cmplt_float32(va, vlimit);
vd_float32_t v_z = mipp_load_float32_maskz(m, ptr); // inactive lanes: 0
vd_float32_t v_s = mipp_load_float32_masks(m, v_src, ptr); // inactive lanes: v_src
mipp_store_float32_maskm(m, out_ptr, v_z); // inactive lanes: memory unchanged
// LMUL = 2:
vm_float32_m2_t vm2 = mipp_cmplt_float32_m2(wa, wlimit);
vd_float32_m2_t w_z = mipp_loadu_float32_maskz_m2(vm2, uptr);
mipp_storeu_float32_maskm_m2(vm2, uout, w_z);
mipp::vm<float> m = mipp::cmplt(va, vlimit);
mipp::vd<float> v_z = mipp::load<mipp::Z>(m, ptr); // inactive lanes: 0
mipp::vd<float> v_s = mipp::load<mipp::S>(m, v_src, ptr); // inactive lanes: v_src
mipp::store<mipp::M>(m, out_ptr, v_z); // inactive lanes: memory unchanged
// LMUL = 2:
mipp::vm<float, 2> vm2 = mipp::cmplt(wa, wlimit);
mipp::vd<float, 2> w_z = mipp::loadu<mipp::Z, float, 2>(vm2, uptr);
mipp::storeu<mipp::M, float, 2>(vm2, uout, w_z);
mipp::Vm<float> m = (va < vlimit);
mipp::Vd<float> v_z = mipp::load_obj<mipp::Z>(m, ptr); // inactive lanes: 0
mipp::Vd<float> v_s = mipp::load_obj<mipp::S>(m, v_src, ptr); // inactive lanes: v_src
mipp::store<mipp::M>(m, out_ptr, v_z); // inactive lanes: memory unchanged
// LMUL = 2:
mipp::Vm<float, 2> vm2 = (wa < wlimit);
mipp::Vd<float, 2> w_z = mipp::loadu_obj<mipp::Z>(vm2, uptr);
mipp::storeu<mipp::M>(vm2, uout, w_z);
In the Object API, loads are named load_obj / loadu_obj (masked or not) so that they return a Vd; stores keep the names store / storeu.
In the C++ Functional API, a masked access deduces T from the pointer and assumes LMUL = 1: the mask type does not allow the deduction of LMUL, so give T and LMUL for a multi-register vector (mipp::loadu<mipp::Z, float, 2>). In the C++ Object API, T and LMUL are deduced from the Vm mask.
2.3. Non-Temporal Stores & Prefetch¶
A large array that is written once and not read soon fills the caches, and evicts the data that the program reuses. storent stores a register with a non-temporal hint: the data goes to memory without staying in the caches, when the target allows it. Its contract is the one of store: an address aligned on the register size, and the Merge-Masked (M) and Zero-Masked (Z) variants.
| Operation | C API | C++ Functional API | C++ Object API |
|---|---|---|---|
| Non-temporal store | mipp_storent_[type]_[lmul] |
mipp::storent(ptr, r) |
mipp::storent(ptr, r) |
| Order the non-temporal stores | mipp_storent_fence() |
mipp::storent_fence() |
mipp::storent_fence() |
| Prefetch (read, write) | mipp_prefetch(p), mipp_prefetchw(p) |
mipp::prefetch(p), mipp::prefetchw(p) |
mipp::prefetch(p), mipp::prefetchw(p) |
- Targets.
storentismovntps/movntdqon SSE, AVX and AVX-512,stnt1on SVE andstnpon NEON with Clang (a builtin of the compiler: GCC has no equivalent). The half-vectors of AVX and AVX-512 use the non-temporal store of the narrower register (SSE, AVX). Elsewhere (NEON with GCC, RVV, the half-vectors of SSE, NEON, SVE and RVV), it is an ordinary store: the result is the same, the hint is lost. - Ordering. On x86, the non-temporal stores bypass the caches and are weakly ordered: another thread can see a later ordinary store (for instance the flag that says that the data is ready) before the streamed data. Call
storent_fence()(sfence) after the loop ofstorent, before publishing the data. It does nothing on the other targets, whose non-temporal stores keep the order of the ordinary stores. - Prefetch.
prefetch(p)andprefetchw(p)load the cache line ofpin advance, before a read or a write:prefetcht0/prefetchwon x86 (prefetcht0for both without PRFCHW, i.e. before Broadwell, and with MSVC),prfm pldl1keep/prfm pstl1keepon Arm,prefetch.r/prefetch.won RISC-V with Zicbop, nothing elsewhere (RISC-V without Zicbop, MSVC on Arm, other compilers). They take an address, not a register, so they are utilities and not functions of a type and an LMUL. They are hints: they never fault, even on an invalid address, and may do nothing. The hardware prefetchers already follow the sequential accesses: measure before adding them, they help on irregular accesses (a list, a gather) or on strides that the hardware does not follow.
const int N = MIPP_N_FLOAT32;
for (int i = 0; i + N <= n; i += N) {
if (i + 16 * N < n)
mipp_prefetch(src + i + 16 * N); // 16 registers ahead
vd_float32_t v = mipp_load_float32(src + i);
mipp_storent_float32(dst + i, mipp_mul_float32(v, mipp_set1_float32(2.f))); // dst aligned, not cached
}
mipp_storent_fence(); // before another thread reads dst
const int N = (int)mipp::N<float>();
for (int i = 0; i + N <= n; i += N) {
if (i + 16 * N < n)
mipp::prefetch(src + i + 16 * N); // 16 registers ahead
mipp::vd<float> v = mipp::load<float>(src + i);
mipp::storent(dst + i, mipp::mul(v, mipp::set1<float>(2.f))); // dst aligned, not cached
}
mipp::storent_fence(); // before another thread reads dst
const int N = mipp::Vd<float>::N();
for (int i = 0; i + N <= n; i += N) {
if (i + 16 * N < n)
mipp::prefetch(src + i + 16 * N); // 16 registers ahead
mipp::Vd<float> v = mipp::load_obj<float>(src + i);
mipp::storent(dst + i, v * 2.f); // dst aligned, not cached
}
mipp::storent_fence(); // before another thread reads dst
2.4. Strided, First-Faulting and Structured Accesses¶
Other loads and stores access memory with another pattern than one register of consecutive elements. They require no alignment and have no masked variant.
| Operation | C API | C++ Functional API | C++ Object API | Elements accessed |
|---|---|---|---|---|
| Strided load | mipp_loadu_strided_[type]_[lmul](ptr, stride) |
mipp::loadu_strided<T, LMUL>(ptr, stride) |
mipp::loadu_strided_obj<T, LMUL>(ptr, stride) |
Lane i is ptr[i * stride], stride (int32_t) counted in elements; 0 broadcasts ptr[0]; a negative stride is undefined behavior |
| Strided store | mipp_storeu_strided_[type]_[lmul](ptr, r, stride) |
mipp::storeu_strided(ptr, r, stride) |
mipp::storeu_strided(ptr, r, stride) |
Lane i goes to ptr[i * stride], stride \(> 0\) (0 and a negative stride are undefined behavior); the elements in between are left unchanged |
| First-faulting load | mipp_loadu_ff_[type]_[lmul](ptr, &n) |
mipp::loadu_ff<T, LMUL>(ptr, &n) |
mipp::loadu_ff_obj<T, LMUL>(ptr, &n) |
The lanes from ptr that can be read without a fault, at least one, their number written to n (NULL / nullptr, the C++ default, to ignore it) |
| Structures of 2 to 4 fields | mipp_loadu_unzip2_[type]_[lmul](ptr, &a, &b), mipp_storeu_zip2_[type]_[lmul](ptr, a, b) |
mipp::loadu_unzip2(ptr, a, b), mipp::storeu_zip2(ptr, a, b) |
mipp::loadu_unzip2(ptr, a, b), mipp::storeu_zip2(ptr, a, b) |
\(2N\) consecutive elements, one register per field (also 3 and 4 fields) |
- Strided accesses. A field of an array of structures is a strided access with the size of the structure as stride. They are native on RVV (
vlse/vsse). Elsewhere,loadu_stridedreads contiguous registers and separates them (loadufor a stride of 1,loadu_unzip2toloadu_unzip4for 2 to 4) when the elements read stay in the page of the last lane (MIPP_PAGE_SIZE, below), and is a gather otherwise for the 32-bit and 64-bit types (an element by element copy for the 8-bit and 16-bit types, whose indices would be too narrow).storeu_stridedis a scatter for the 32-bit and 64-bit types and an element by element copy otherwise: it never writes the elements in between. -
First-faulting load. It reads a buffer whose length is unknown and whose end is marked in the data: the
0of a string, a sentinel at the end of a list. On every target,loadu_ffreads at least the first lane (ptrmust be accessible, as for any load), never faults on the next ones, writes their number \(1 \le n \le N\) ton, and leaves the lanes after the firstnunspecified.nsays how far the load could go without risk, not where the data ends: it can be lower than \(N\) while the memory after is readable, and equal to \(N\) while the last lanes are past the end of the data. The end is found in the data: the loop looks for the sentinel in thenlanes; when it is not there, the buffer goes on, soptr + nis accessible and the next iteration starts from there:size_t strlen_simd(const char* str) { const int8_t* p = reinterpret_cast<const int8_t*>(str); size_t len = 0; for (;;) { int32_t n; mipp::vd<int8_t> v = mipp::loadu_ff<int8_t>(p, &n); // n >= 1 lanes, read without a fault mipp::vm<int8_t> z = mipp::andb(mipp::cmpeq(v, mipp::set0<int8_t>()), // the lanes equal to 0... mipp::firstn<int8_t>(n)); // ...among the n lanes read int32_t i = mipp::findfirst(z); if (i >= 0) return len + i; // the end, found in the data p += n; // no 0 in the n lanes: the string goes on, p + n is accessible len += n; } }It is native on RVV (
vle<n>ff) and SVE (ldff1and the first-fault register): in practice the lanes up to the first one that would fault, but both architectures allow a core to stop earlier, so a program must not expect \(n = N\) when the memory is readable. Elsewhere, MIPP reads the lanes up to the end of the page ofptr(MIPP_PAGE_SIZE, below), which cannot fault sinceptris accessible, and stops there even when the next page is readable. The loop gives the same result; it only has more iterations, and few: whenptris aligned on the size of its elements, the load cut at the end of a page makes the next one start at the beginning of a page, and the following ones never straddle two pages (the size of a register divides the size of a page), so a traversal is cut once at most, at its first page boundary. -
Page size. The emulations of
loadu_ffandloadu_strided(Level 2) rely on the size of the memory pages, the macroMIPP_PAGE_SIZEin bytes: 4096 by default, the smallest page of the targets, and safe everywhere. A larger value, defined before including MIPP (-DMIPP_PAGE_SIZE=16384, the page of macOS and iOS on Apple Silicon), makes these emulations stop less often, but the program then faults on a machine whose pages are smaller (Linux on AArch64 often uses 4 KiB pages): define it only for machines whose page is at least this size. It must be a power of two (checked at compile time). - Memory checkers. Since they read up to the end of the page, the emulations of
loadu_ffandloadu_stridedmay read past the end of the object that holds the data:loadu_ffup to one register after the sentinel,loadu_strided(stride of 2 to 4) up tos0 - 1elements after the last lane. These reads cannot fault and do not change the result, but they are outside the object for the language: AddressSanitizer reports them (heap-buffer-overflow) and stops the program, and Valgrind (Memcheck) reports invalid reads, or uses of uninitialised values when these lanes reach a comparison. To check a program with these tools, allocate the buffers with a margin of one register (mipp::N<T>()elements) after the data. The native versions (loadu_ffon SVE and RVV,loadu_stridedon RVV) are not concerned. - Structures.
loadu_unzip2toloadu_unzip4separate the fields of \(N\) structures into one register each, andstoreu_zip2tostoreu_zip4store them back (array of structures to structure of arrays and back): see Rearrangements §4.loadu_expandandstoreu_compress/storeuf_compressread or write as many consecutive elements as the mask has active lanes: see Rearrangements §6.
3. Non-Contiguous Memory Access: Gather & Scatter¶
When data elements reside at non-sequential memory addresses, MIPP provides vectorized gather and scatter operations using index vectors. The index vector holds unsigned integers counted in elements, not in bytes (uint32_t indices for float data, uint64_t indices for double data). The C names give the type of the data then the type of the index: mipp_gather_float32_uint32. For the masked variants, the mask has the type of the data (vm<float> for a float gather, as for the masked loads); a mask computed on the indices is converted with cast_k. In the C++ Functional API, the masked variants cannot deduce the types: give T and the index type (mipp::gather<mipp::Z, float, uint32_t>). In the C++ Object API, they are deduced from the arguments.
3.0. Indices of Another Width than the Data¶
The indices can also be uint32_t or uint64_t whatever the width of the data: uint32_t indices for double data (mipp_gather_float64_uint32), uint64_t indices for float or int8_t data, etc. There is one index per element of data, so the index register then has its own LMUL: the LMUL of the data times \(\text{size(index)} / \text{size(data)}\). With double data at LMUL 1, the uint32_t indices are a half-vector (d2); with float data at LMUL 1, the uint64_t indices are an LMUL 2 register. The LMUL in the name of the function is the one of the data, and the function only exists where the LMUL of the index does: from m1 to m8 for 32-bit indices of 64-bit data, from m1 to m4 for 64-bit indices of 32-bit data, etc. (not for the half-vectors of the data).
| Data | Index | Index LMUL for data at m1 |
Native |
|---|---|---|---|
float64, int64, uint64 |
uint32 |
d2 |
AVX2, AVX-512 (vgatherdpd, vscatterdpd), SVE (svunpklo + gather), RVV |
| 32, 16 or 8-bit types | uint64 |
m2, m4 or m8 |
RVV |
| 16 or 8-bit types | uint32 |
m2 or m4 |
RVV |
Elsewhere the scalar fallback applies, as for the gathers of 8 and 16-bit elements on x86. With the C++ Object API, the LMUL of the result is deduced from the index (mipp::gather(table, idx) with a Vd<uint32_t, -2> gives a Vd<double, 1>); with the C++ Functional API, it is the LMUL of the data (mipp::gather<mipp::Z, double, uint32_t, 1>).
Range of the indices
Every index must address an element of the array. The 8-bit and 16-bit indices can take any value of their type. The 32-bit indices must be lower than \(2^{31}\): the x86 gather and scatter instructions read them as signed integers. On RVV, the byte offset of a 32-bit element, \(\text{index} \times 4\), is computed on 32 bits: the indices must be lower than \(2^{30}\) (arrays of at most 4 GiB). Two active lanes of a scatter with the same index write the same element: undefined behavior, the value that remains depends on the target (a gather may read the same element several times).
3.1. Gather (Vectorized Indirect Load)¶
Loads elements from a base address using a vector of indices:
Masked variants: Zero-Masked (Z) and Source-Masked (S). Inactive lanes are not read.
3.2. Scatter (Vectorized Indirect Store)¶
Writes elements of a vector into memory locations specified by a vector of indices:
Masked variants: Merge-Masked (M), where the inactive lanes are not written, and Zero-Masked (Z), where they write zeros.
4. Scalar Element Extraction¶
MIPP provides primitives to extract individual scalar values from vector and mask registers:
| Operation | C API | C++ Functional API | C++ Object API | Returns |
|---|---|---|---|---|
| Extract Element | mipp_get_[type]_[lmul](v, idx) |
mipp::get(v, idx) |
v[idx] or mipp::get(v, idx) |
Element idx, type T, with \(0 \le \text{idx} < N\) and \(N\) = mipp::N<T, LMUL>() (all the lanes of all the registers of the group) |
| Get First Element | mipp_getfirst_[type]_[lmul](v) |
mipp::getfirst(v) |
mipp::getfirst(v) |
Element 0, type T, without shuffle |
| Extract Mask Lane | mipp_get_k_[type]_[lmul](m, idx) |
mipp::get(m, idx) |
m[idx] or mipp::get(m, idx) |
C++ APIs: bool (true for an active lane). C: see the warning below |
In C++, the mask-lane extraction has no _k suffix: it is the get overload taking a mask. Both C++ APIs also take a lane index known at compile time, checked by a static_assert: mipp::get<2>(v), mipp::get<2>(m).
Mask-lane extraction in the C API
mipp_get_k_* currently returns the raw lane with the element type T: zero for an inactive lane, all bits set for an active one (on every target, the scalar one included), which is NaN for float / double, -1 for signed and the maximum value for unsigned types. Do not convert this value to an integer (converting a NaN is undefined behavior). Until it returns a 0 / 1 value, read mask lanes with the C++ APIs (mipp::get(m, idx) and m[idx] return a bool).
vd_float32_t v = mipp_load_float32(ptr);
float32_t first_val = mipp_getfirst_float32(v);
float32_t third_val = mipp_get_float32(v, 2);
// LMUL = 2: idx goes up to MIPP_N_FLOAT32_M2 - 1
vd_float32_m2_t w = mipp_load_float32_m2(ptr);
float32_t w_first = mipp_getfirst_float32_m2(w);
float32_t w_last = mipp_get_float32_m2(w, MIPP_N_FLOAT32_M2 - 1);
mipp::vd<float> v = mipp::load<float>(ptr);
float first_val = mipp::getfirst(v);
float third_val = mipp::get(v, 2);
// LMUL = 2: idx goes up to mipp::N<float, 2>() - 1
mipp::vd<float, 2> w = mipp::load<float, 2>(ptr);
float w_first = mipp::getfirst(w);
float w_last = mipp::get(w, mipp::N<float, 2>() - 1);