/
simd.rs
400 lines (339 loc) · 10.8 KB
/
simd.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
//! A custom SIMD-accelerated bit-set.
//!
//! Implementation is largely derived from the `bitsvec` crate: <https://github.com/psiace/bitsvec>
//!
//! The main difference is I made a much more efficient iterator that computes the indices
//! of the 1-bits.
//!
//! **WARNING:** this module makes liberal use of unsafe code and has not been thoroughly vetted,
//! so use it at your own risk.
use crate::{
bitset::BitSet,
pointer::{ArcFamily, RcFamily, RefFamily},
};
use std::{
mem::size_of,
ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign, Not},
simd::{LaneCount, Simd, SimdElement, SupportedLaneCount},
slice,
};
/// Capabilities of an element that represent a SIMD lane
pub trait SimdSetElement:
SimdElement
+ BitOr<Output = Self>
+ BitAnd<Output = Self>
+ Not<Output = Self>
+ BitOrAssign
+ BitAndAssign
+ PartialEq
+ 'static
{
/// The `0` value.
const ZERO: Self;
/// The `1` value.
const ONE: Self;
/// The largest value.
const MAX: Self;
/// Efficient bit-shift-left.
///
/// # Safety
/// `rhs < size_of::<Self>()`
unsafe fn unchecked_shl(self, rhs: u32) -> Self;
/// Efficient bit-shift-right.
///
/// # Safety
/// `rhs < size_of::<Self>()`
unsafe fn unchecked_shr(self, rhs: u32) -> Self;
/// The number of zeros before the first 1 bit, counting from LSB.
fn trailing_zeros(self) -> u32;
/// The number of 1 bits in the element.
fn count_ones(self) -> u32;
}
macro_rules! simd_set_element_impl {
($n:ty) => {
impl SimdSetElement for $n {
const ZERO: Self = 0;
const ONE: Self = 1;
const MAX: Self = Self::MAX;
#[inline]
unsafe fn unchecked_shl(self, rhs: u32) -> Self {
self.unchecked_shl(rhs)
}
#[inline]
unsafe fn unchecked_shr(self, rhs: u32) -> Self {
self.unchecked_shr(rhs)
}
#[inline]
fn trailing_zeros(self) -> u32 {
self.trailing_zeros()
}
#[inline]
fn count_ones(self) -> u32 {
self.count_ones()
}
}
};
}
simd_set_element_impl!(u8);
simd_set_element_impl!(u16);
simd_set_element_impl!(u32);
simd_set_element_impl!(u64);
/// A dense bit-set with SIMD-accelerated operations.
#[derive(PartialEq, Clone)]
pub struct SimdBitset<T, const N: usize>
where
T: SimdSetElement,
LaneCount<N>: SupportedLaneCount,
{
chunks: Vec<Simd<T, N>>,
nbits: usize,
}
impl<T: SimdSetElement, const N: usize> SimdBitset<T, N>
where
LaneCount<N>: SupportedLaneCount,
{
const fn chunk_size() -> usize {
Self::lane_size() * N
}
const fn lane_size() -> usize {
size_of::<T>() * 8
}
#[inline(always)]
const fn coords(&self, index: usize) -> (usize, usize, u32) {
let (chunk, index) = (index / Self::chunk_size(), index % Self::chunk_size());
let (lane, index) = (index / Self::lane_size(), index % Self::lane_size());
(chunk, lane, index as u32)
}
#[inline(always)]
fn get(&self, chunk_idx: usize, lane_idx: usize, bit: u32) -> bool {
debug_assert!(chunk_idx < self.chunks.len());
debug_assert!(lane_idx < N);
debug_assert!(bit < Self::lane_size() as u32);
unsafe {
let chunk = self.chunks.get_unchecked(chunk_idx);
let lane = chunk.as_array().get_unchecked(lane_idx);
lane.unchecked_shr(bit) & T::ONE == T::ONE
}
}
#[inline(always)]
fn zip_mut(&mut self, other: &Self, mut op: impl FnMut(&mut Simd<T, N>, &Simd<T, N>)) {
debug_assert!(other.chunks.len() == self.chunks.len());
let mut dst = self.chunks.as_mut_ptr();
let mut src = other.chunks.as_ptr();
unsafe {
let dst_end = dst.add(self.chunks.len());
while dst != dst_end {
op(&mut *dst, &*src);
dst = dst.add(1);
src = src.add(1);
}
}
}
}
/// Iterator over the 1-bits of a [`SimdBitset`].
pub struct SimdSetIter<'a, T, const N: usize>
where
T: SimdSetElement,
LaneCount<N>: SupportedLaneCount,
{
set: &'a SimdBitset<T, N>,
index: usize,
chunk_iter: slice::Iter<'a, Simd<T, N>>,
lane_iter: slice::Iter<'a, T>,
bit: u32,
lane: T,
}
impl<'a, T, const N: usize> SimdSetIter<'a, T, N>
where
T: SimdSetElement,
LaneCount<N>: SupportedLaneCount,
{
#[inline]
fn new(set: &'a SimdBitset<T, N>) -> Self {
let mut chunk_iter = set.chunks.iter();
let chunk = chunk_iter.next().unwrap();
let mut lane_iter = chunk.as_array().iter();
let lane = *lane_iter.next().unwrap();
SimdSetIter {
set,
index: 0,
chunk_iter,
lane_iter,
bit: 0,
lane,
}
}
}
impl<'a, T, const N: usize> Iterator for SimdSetIter<'a, T, N>
where
T: SimdSetElement,
LaneCount<N>: SupportedLaneCount,
{
type Item = usize;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
if self.index >= self.set.nbits {
return None;
}
let lane_size = SimdBitset::<T, N>::lane_size() as u32;
loop {
let zeros = self.lane.trailing_zeros();
let idx = self.index;
let incr_amt = if zeros == 0 {
1
} else {
zeros.min(lane_size - self.bit)
};
self.bit += incr_amt;
self.index += incr_amt as usize;
debug_assert!(incr_amt <= lane_size);
if incr_amt < lane_size {
self.lane = unsafe { self.lane.unchecked_shr(incr_amt) };
}
if self.bit == lane_size {
self.bit = 0;
loop {
match self.lane_iter.next() {
Some(lane) => {
self.lane = *lane;
}
None => match self.chunk_iter.next() {
Some(chunk) => {
self.lane_iter = chunk.as_array().iter();
self.lane = *self.lane_iter.next().unwrap();
}
None => return (zeros == 0).then_some(idx),
},
}
if self.lane != T::ZERO {
break;
} else {
self.index += lane_size as usize;
}
}
}
if zeros == 0 {
return Some(idx);
}
}
}
}
impl<T: SimdSetElement, const N: usize> BitSet for SimdBitset<T, N>
where
LaneCount<N>: SupportedLaneCount,
Simd<T, N>: for<'a> BitOr<&'a Simd<T, N>, Output = Simd<T, N>>,
Simd<T, N>: for<'a> BitAnd<&'a Simd<T, N>, Output = Simd<T, N>>,
{
type Iter<'a> = SimdSetIter<'a, T, N>;
#[inline]
fn empty(nbits: usize) -> Self {
let n_chunks = (nbits + Self::chunk_size() - 1) / Self::chunk_size();
SimdBitset {
chunks: vec![Simd::from([T::ZERO; N]); n_chunks],
nbits,
}
}
#[inline]
fn insert(&mut self, index: usize) -> bool {
let (chunk_idx, lane_idx, bit) = self.coords(index);
debug_assert!(chunk_idx < self.chunks.len());
debug_assert!(lane_idx < N);
debug_assert!(bit < Self::lane_size() as u32);
unsafe {
let chunk = self.chunks.get_unchecked_mut(chunk_idx);
let lane = chunk.as_mut_array().get_unchecked_mut(lane_idx);
*lane |= T::ONE.unchecked_shl(bit);
}
true
}
#[inline]
fn contains(&self, index: usize) -> bool {
let (chunk_idx, lane_idx, bit) = self.coords(index);
self.get(chunk_idx, lane_idx, bit)
}
#[inline]
fn iter(&self) -> Self::Iter<'_> {
SimdSetIter::new(self)
}
#[inline]
fn len(&self) -> usize {
let mut n = 0;
for chunk in &self.chunks {
for lane in chunk.as_array() {
n += lane.count_ones();
}
}
n as usize
}
#[inline]
fn union(&mut self, other: &Self) {
self.zip_mut(other, |dst, src| *dst |= src);
}
#[inline]
fn intersect(&mut self, other: &Self) {
self.zip_mut(other, |dst, src| *dst &= src);
}
#[inline]
fn subtract(&mut self, other: &Self) {
let mut other = other.clone();
other.invert();
self.intersect(&other);
}
#[inline]
fn invert(&mut self) {
for chunk in self.chunks.iter_mut() {
for lane in chunk.as_mut_array() {
*lane = !*lane;
}
}
}
#[inline]
fn clear(&mut self) {
for chunk in self.chunks.iter_mut() {
for lane in chunk.as_mut_array() {
*lane = T::ZERO;
}
}
}
#[inline]
fn insert_all(&mut self) {
for chunk in self.chunks.iter_mut() {
for lane in chunk.as_mut_array() {
*lane = T::MAX;
}
}
}
#[inline]
fn copy_from(&mut self, other: &Self) {
self.zip_mut(other, |dst, src| *dst = *src);
}
}
/// [`IndexSet`](crate::IndexSet) specialized to the [`SimdBitset`] implementation.
pub type IndexSet<T> = crate::IndexSet<'static, T, SimdBitset<u64, 4>, RcFamily>;
/// [`IndexSet`](crate::IndexSet) specialized to the [`SimdBitset`] implementation with the [`ArcFamily`].
pub type ArcIndexSet<'a, T> = crate::IndexSet<'a, T, SimdBitset<u64, 4>, ArcFamily>;
/// [`IndexSet`](crate::IndexSet) specialized to the [`SimdBitset`] implementation with the [`RefFamily`].
pub type RefIndexSet<'a, T> = crate::IndexSet<'a, T, SimdBitset<u64, 4>, RefFamily<'a>>;
/// [`IndexMatrix`](crate::IndexMatrix) specialized to the [`SimdBitset`] implementation.
pub type IndexMatrix<R, C> = crate::IndexMatrix<'static, R, C, SimdBitset<u64, 4>, RcFamily>;
/// [`IndexMatrix`](crate::IndexMatrix) specialized to the [`SimdBitset`] implementation with the [`ArcFamily`].
pub type ArcIndexMatrix<R, C> = crate::IndexMatrix<'static, R, C, SimdBitset<u64, 4>, ArcFamily>;
/// [`IndexMatrix`](crate::IndexMatrix) specialized to the [`SimdBitset`] implementation with the [`RefFamily`].
pub type RefIndexMatrix<'a, R, C> = crate::IndexMatrix<'a, R, C, SimdBitset<u64, 4>, RefFamily<'a>>;
#[test]
fn test_simd_bitset() {
const N: usize = 64 * 7 + 63;
let mut bitset = SimdBitset::<u64, 4>::empty(N);
for i in 0..N {
bitset.clear();
for j in 0..i {
bitset.insert(j);
}
assert_eq!(
bitset.iter().collect::<Vec<_>>(),
(0..i).collect::<Vec<_>>()
);
assert_eq!(bitset.len(), i);
}
crate::test_utils::impl_test::<SimdBitset<u64, 4>>();
}