crates/kleene-sparse/src/simd/x86.rs
//! The x86_64 kernels the compiler does not write by itself from plain loops: compaction
//! of a mask (bytes of `bool`, or the bits of words) or of a range compare to the row
//! numbers it keeps. Each function is compiled for one level and called only from
//! `Simd`'s match on a detected level; each writes only inside `out` (and panics, as the
//! plain code does, when the kept rows do not fit).
use std::arch::x86_64::*;
/// The places of the set bits of every byte, packed as eight bytes (rising, the unused
/// high bytes zero): an AVX2 compaction widens one entry to eight `u32` lanes.
static BYTE_PLACES: [u64; 256] = {
let mut t = [0u64; 256];
let mut b = 0;
while b < 256 {
let (mut packed, mut k, mut bit) = (0u64, 0, 0);
while bit < 8 {
if b >> bit & 1 == 1 {
packed |= (bit as u64) << (8 * k);
k += 1;
}
bit += 1;
}
t[b] = packed;
b += 1;
}
t
};
#[cold]
#[inline(never)]
fn no_room(len: usize) -> ! {
panic!("compaction: more kept rows than the output's {len} places")
}
// ---------------------------------------------------------------------------------------
// Compaction. Callers check `base as usize + places < 2^32`. Each writes the kept places
// at `out[n..]`, rising, and returns the new `n`; a full vector is stored only where all
// its lanes fit in `out`, else exactly the kept lanes (and a panic when they do not fit).
/// Store the first `cnt` lanes of `v` at `out[n..]`.
///
/// # Safety
/// The host has AVX-512 F.
#[inline(always)]
unsafe fn put16(out: &mut [u32], n: usize, v: __m512i, cnt: usize) {
// SAFETY: a full store only where 16 lanes fit; else a masked store of `cnt` lanes
// after checking they fit.
unsafe {
if n + 16 <= out.len() {
_mm512_storeu_si512(out.as_mut_ptr().add(n).cast(), v);
} else {
if n + cnt > out.len() {
no_room(out.len());
}
let m = ((1u32 << cnt) - 1) as u16;
_mm512_mask_storeu_epi32(out.as_mut_ptr().add(n).cast(), m, v);
}
}
}
/// The set places of a sparse run of words one at a time (fewer than about four a word:
/// the vector paths would store mostly empty lanes, and a branch per word on its count
/// mispredicts).
#[inline(always)]
fn bits_sparse(words: &[u64], base: u32, out: &mut [u32], mut n: usize) -> usize {
let room = out.len();
for (wi, &w) in words.iter().enumerate() {
let mut w = w;
let at = base + 64 * wi as u32;
while w != 0 {
*out.get_mut(n).unwrap_or_else(|| no_room(room)) = at + w.trailing_zeros();
n += 1;
w &= w - 1;
}
}
n
}
/// Whether `words` hold too few set bits for a vector path: under one in `per` bits.
#[inline(always)]
fn sparse(words: &[u64], per: usize) -> bool {
let set: usize = words.iter().map(|w| w.count_ones() as usize).sum();
set * per < words.len() * 64
}
/// The places `base + 64 w + b` of every set bit `b` of `words[w]`: sixteen places a
/// compress, every quarter of a word that has a bit (no branch on its count).
///
/// # Safety
/// The host has AVX-512 F and POPCNT.
#[target_feature(enable = "avx512f,avx512vl,avx2,popcnt")]
pub(super) unsafe fn bits_to_places_avx512(words: &[u64], base: u32, out: &mut [u32]) -> usize {
if sparse(words, 16) {
return bits_sparse(words, base, out, 0);
}
let iota = _mm512_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
let mut n = 0;
for (wi, &w) in words.iter().enumerate() {
if w == 0 {
continue;
}
let at0 = base as usize + 64 * wi;
for c in 0..4 {
let k = (w >> (16 * c)) as u16;
let at = _mm512_add_epi32(iota, _mm512_set1_epi32((at0 + 16 * c) as i32));
let packed = _mm512_maskz_compress_epi32(k, at);
let cnt = k.count_ones() as usize;
// SAFETY: AVX-512 F is enabled here.
unsafe { put16(out, n, packed, cnt) };
n += cnt;
}
}
n
}
/// The eight places of byte `b` set, widened from the table and added to `at`, stored at
/// `out[n..]`; returns the new `n`.
#[inline(always)]
fn put8_avx2(out: &mut [u32], n: usize, b: u8, at: u32) -> usize {
let cnt = b.count_ones() as usize;
if n + 8 <= out.len() {
// SAFETY: called only from AVX2 functions; eight lanes fit at `out[n..]`.
unsafe {
let packed = _mm_cvtsi64_si128(BYTE_PLACES[b as usize] as i64);
let v = _mm256_add_epi32(_mm256_cvtepu8_epi32(packed), _mm256_set1_epi32(at as i32));
_mm256_storeu_si256(out.as_mut_ptr().add(n).cast(), v);
}
} else {
if n + cnt > out.len() {
no_room(out.len());
}
let mut b = b;
let mut k = n;
while b != 0 {
out[k] = at + b.trailing_zeros();
k += 1;
b &= b - 1;
}
}
n + cnt
}
/// The places `base + k` of every `keep[k]` that is true: 32 bytes to a 32-bit mask,
/// eight places a store (also the AVX-512 level's kernel: a sixteen-lane compress
/// measured slower on Tiger Lake and Zen 4).
///
/// # Safety
/// The host has AVX2 and POPCNT.
#[target_feature(enable = "avx2,popcnt")]
pub(super) unsafe fn compact_bools_avx2(keep: &[bool], base: u32, out: &mut [u32]) -> usize {
let room = out.len();
let len = keep.len();
let (mut i, mut n) = (0, 0);
while i + 32 <= len {
// SAFETY: i + 32 <= keep.len(); a bool is one byte, 0 or 1.
let v = unsafe { _mm256_loadu_si256(keep.as_ptr().add(i).cast()) };
let m = _mm256_movemask_epi8(_mm256_slli_epi16::<7>(v)) as u32;
if m != 0 {
for c in 0..4 {
n = put8_avx2(out, n, (m >> (8 * c)) as u8, base + (i + 8 * c) as u32);
}
}
i += 32;
}
for (k, &b) in keep.iter().enumerate().skip(i) {
if b {
*out.get_mut(n).unwrap_or_else(|| no_room(room)) = base + k as u32;
n += 1;
}
}
n
}
/// [`bits_to_places_avx512`] on AVX2: a byte at a time through the table, every byte of
/// a word that has a bit.
///
/// # Safety
/// The host has AVX2 and POPCNT.
#[target_feature(enable = "avx2,popcnt")]
pub(super) unsafe fn bits_to_places_avx2(words: &[u64], base: u32, out: &mut [u32]) -> usize {
if sparse(words, 4) {
return bits_sparse(words, base, out, 0);
}
let mut n = 0;
for (wi, &w) in words.iter().enumerate() {
if w == 0 {
continue;
}
let at0 = base + 64 * wi as u32;
for c in 0..8 {
n = put8_avx2(out, n, (w >> (8 * c)) as u8, at0 + 8 * c as u32);
}
}
n
}
// ---------------------------------------------------------------------------------------
// Selection by a range: the places whose value lies in (or outside) `lo..=hi`.
/// The places `base + k` where `(lo <= col[k] && col[k] <= hi) == inside`, sixteen values
/// a compress (two compares of eight wide values).
///
/// # Safety
/// The host has AVX-512 F.
#[target_feature(enable = "avx512f,avx512vl,avx2,popcnt")]
pub(super) unsafe fn select_u64_avx512(
col: &[u64],
lo: u64,
hi: u64,
inside: bool,
base: u32,
out: &mut [u32],
) -> usize {
let room = out.len();
let iota = _mm512_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
let (vlo, vhi) = (_mm512_set1_epi64(lo as i64), _mm512_set1_epi64(hi as i64));
let flip: u16 = if inside { 0 } else { u16::MAX };
let len = col.len();
let (mut i, mut n) = (0, 0);
while i + 16 <= len {
// SAFETY: i + 16 <= col.len().
let (a, b) = unsafe {
(
_mm512_loadu_si512(col.as_ptr().add(i).cast()),
_mm512_loadu_si512(col.as_ptr().add(i + 8).cast()),
)
};
let ka = _mm512_cmpge_epu64_mask(a, vlo) & _mm512_cmple_epu64_mask(a, vhi);
let kb = _mm512_cmpge_epu64_mask(b, vlo) & _mm512_cmple_epu64_mask(b, vhi);
let k = (ka as u16 | (kb as u16) << 8) ^ flip;
let at = _mm512_add_epi32(iota, _mm512_set1_epi32((base as usize + i) as i32));
let packed = _mm512_maskz_compress_epi32(k, at);
let cnt = k.count_ones() as usize;
// SAFETY: AVX-512 F is enabled here.
unsafe { put16(out, n, packed, cnt) };
n += cnt;
i += 16;
}
for (k, &x) in col.iter().enumerate().skip(i) {
if (lo <= x && x <= hi) == inside {
*out.get_mut(n).unwrap_or_else(|| no_room(room)) = base + k as u32;
n += 1;
}
}
n
}
/// [`select_u64_avx512`] on `u32` values, sixteen a compare.
///
/// # Safety
/// The host has AVX-512 F.
#[target_feature(enable = "avx512f,avx512vl,avx2,popcnt")]
pub(super) unsafe fn select_u32_avx512(
col: &[u32],
lo: u32,
hi: u32,
inside: bool,
base: u32,
out: &mut [u32],
) -> usize {
let room = out.len();
let iota = _mm512_setr_epi32(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
let (vlo, vhi) = (_mm512_set1_epi32(lo as i32), _mm512_set1_epi32(hi as i32));
let flip: u16 = if inside { 0 } else { u16::MAX };
let len = col.len();
let (mut i, mut n) = (0, 0);
while i + 16 <= len {
// SAFETY: i + 16 <= col.len().
let a = unsafe { _mm512_loadu_si512(col.as_ptr().add(i).cast()) };
let k = (_mm512_cmpge_epu32_mask(a, vlo) & _mm512_cmple_epu32_mask(a, vhi)) ^ flip;
let at = _mm512_add_epi32(iota, _mm512_set1_epi32((base as usize + i) as i32));
let packed = _mm512_maskz_compress_epi32(k, at);
let cnt = k.count_ones() as usize;
// SAFETY: AVX-512 F is enabled here.
unsafe { put16(out, n, packed, cnt) };
n += cnt;
i += 16;
}
for (k, &x) in col.iter().enumerate().skip(i) {
if (lo <= x && x <= hi) == inside {
*out.get_mut(n).unwrap_or_else(|| no_room(room)) = base + k as u32;
n += 1;
}
}
n
}
/// [`select_u64_avx512`] on AVX2: unsigned compares as signed ones after flipping the top
/// bit, eight values to a byte of mask, eight places a store.
///
/// # Safety
/// The host has AVX2 and POPCNT.
#[target_feature(enable = "avx2,popcnt")]
pub(super) unsafe fn select_u64_avx2(
col: &[u64],
lo: u64,
hi: u64,
inside: bool,
base: u32,
out: &mut [u32],
) -> usize {
let room = out.len();
let top = _mm256_set1_epi64x(i64::MIN);
let (vlo, vhi) = (
_mm256_set1_epi64x((lo ^ (1 << 63)) as i64),
_mm256_set1_epi64x((hi ^ (1 << 63)) as i64),
);
let flip: u8 = if inside { 0 } else { u8::MAX };
// outside of lo..=hi: below lo or above hi
let out4 = |v: __m256i| -> u8 {
let s = _mm256_xor_si256(v, top);
let o = _mm256_or_si256(_mm256_cmpgt_epi64(vlo, s), _mm256_cmpgt_epi64(s, vhi));
_mm256_movemask_pd(_mm256_castsi256_pd(o)) as u8
};
let len = col.len();
let (mut i, mut n) = (0, 0);
while i + 8 <= len {
// SAFETY: i + 8 <= col.len().
let (a, b) = unsafe {
(
_mm256_loadu_si256(col.as_ptr().add(i).cast()),
_mm256_loadu_si256(col.as_ptr().add(i + 4).cast()),
)
};
let k = !(out4(a) | out4(b) << 4) ^ flip;
n = put8_avx2(out, n, k, base + i as u32);
i += 8;
}
for (k, &x) in col.iter().enumerate().skip(i) {
if (lo <= x && x <= hi) == inside {
*out.get_mut(n).unwrap_or_else(|| no_room(room)) = base + k as u32;
n += 1;
}
}
n
}
/// [`select_u64_avx2`] on `u32` values: eight a compare (by unsigned max and min).
///
/// # Safety
/// The host has AVX2 and POPCNT.
#[target_feature(enable = "avx2,popcnt")]
pub(super) unsafe fn select_u32_avx2(
col: &[u32],
lo: u32,
hi: u32,
inside: bool,
base: u32,
out: &mut [u32],
) -> usize {
let room = out.len();
let (vlo, vhi) = (_mm256_set1_epi32(lo as i32), _mm256_set1_epi32(hi as i32));
let flip: u8 = if inside { 0 } else { u8::MAX };
let len = col.len();
let (mut i, mut n) = (0, 0);
while i + 8 <= len {
// SAFETY: i + 8 <= col.len().
let a = unsafe { _mm256_loadu_si256(col.as_ptr().add(i).cast()) };
let ge = _mm256_cmpeq_epi32(_mm256_max_epu32(a, vlo), a);
let le = _mm256_cmpeq_epi32(_mm256_min_epu32(a, vhi), a);
let m = _mm256_movemask_ps(_mm256_castsi256_ps(_mm256_and_si256(ge, le))) as u8;
n = put8_avx2(out, n, m ^ flip, base + i as u32);
i += 8;
}
for (k, &x) in col.iter().enumerate().skip(i) {
if (lo <= x && x <= hi) == inside {
*out.get_mut(n).unwrap_or_else(|| no_room(room)) = base + k as u32;
n += 1;
}
}
n
}
/// A T0 prefetch of the cache line holding `entry` (a hint: nothing is read or written).
#[inline(always)]
pub(super) fn prefetch_t0<T>(entry: &T) {
// SAFETY: `_mm_prefetch` needs SSE, which every x86_64 target has; a prefetch reads and
// writes no memory and cannot fault, and the pointer comes from a live reference.
unsafe { _mm_prefetch::<_MM_HINT_T0>((entry as *const T).cast()) };
}