Skip to main content

oxidd_cache/
direct.rs

1//! Fixed-size direct mapped apply cache
2
3use std::cell::UnsafeCell;
4use std::fmt;
5use std::hash::{Hash, Hasher};
6use std::marker::PhantomData;
7use std::mem::{ManuallyDrop, MaybeUninit};
8
9use parking_lot::lock_api::RawMutex;
10
11use oxidd_core::util::{Borrowed, DropWith};
12use oxidd_core::{ApplyCache, Edge, Manager, ManagerEventSubscriber};
13
14#[cfg(feature = "hugealloc")]
15type Box<T> = allocator_api2::boxed::Box<T, hugealloc::HugeAlloc>;
16#[cfg(feature = "hugealloc")]
17type Vec<T> = allocator_api2::vec::Vec<T, hugealloc::HugeAlloc>;
18
19/// Fixed-size direct mapped apply cache
20pub struct DMApplyCache<M: Manager, O, H, const ENTRY_CAP: usize = 3>(
21    Box<[Entry<M, O, ENTRY_CAP>]>,
22    PhantomData<H>,
23);
24
25impl<M: Manager, O, H, const ENTRY_CAP: usize> DropWith<M::Edge>
26    for DMApplyCache<M, O, H, ENTRY_CAP>
27where
28    O: Copy + Eq + Hash,
29{
30    fn drop_with(self, _drop_edge: impl Fn(M::Edge)) {
31        // The plain drop impl suffices
32    }
33}
34
35union Datum<E> {
36    edge: ManuallyDrop<E>,
37    numeric: u32,
38    uninit: (),
39}
40
41impl<E> Datum<E> {
42    const UNINIT: Self = Self { uninit: () };
43
44    /// SAFETY: `self` must be initialized as `edge`
45    unsafe fn assume_edge_ref(&self) -> &E {
46        // SAFETY: see above
47        unsafe { &self.edge }
48    }
49
50    /// SAFETY: `self` must be initialized as `numeric`
51    unsafe fn assume_numeric(&self) -> u32 {
52        // SAFETY: see above
53        unsafe { self.numeric }
54    }
55
56    fn write_edge(&mut self, edge: Borrowed<E>) {
57        // SAFETY: The referenced node lives at least until the next garbage
58        // collection / reordering. Before that operation, we clear the entire
59        // cache.
60        self.edge = unsafe { Borrowed::into_inner(edge) };
61    }
62
63    fn write_numeric(&mut self, num: u32) {
64        self.numeric = num;
65    }
66}
67
68const KIND_BITS: u32 = 4;
69const KIND_COUNT: usize = 1 << KIND_BITS;
70
71#[derive(Clone, Copy, PartialEq, Eq, Debug)]
72struct CountPair(u8);
73
74impl CountPair {
75    const NULL: Self = CountPair(0);
76
77    const fn new(edge: usize, numeric: usize) -> Self {
78        debug_assert!(edge < KIND_COUNT);
79        debug_assert!(numeric < KIND_COUNT);
80        Self((numeric << 4 | edge) as u8)
81    }
82
83    const fn edge(self) -> usize {
84        self.0 as usize & (KIND_COUNT - 1)
85    }
86
87    const fn numeric(self) -> usize {
88        (self.0 >> KIND_BITS) as usize
89    }
90}
91
92/// Entry containing key and value
93struct Entry<M: Manager, O, const ENTRY_CAP: usize> {
94    /// Mutex for all the `UnsafeCell`s in here
95    mutex: crate::util::RawMutex,
96    /// Count of operands. If 0, this entry is not occupied.
97    operands: UnsafeCell<CountPair>,
98    /// Count of values
99    values: UnsafeCell<CountPair>,
100    /// Operator of the key. Initialized if `operands != 0`.
101    operator: UnsafeCell<MaybeUninit<O>>,
102    /// Operands and values. The first `operands.edge()` elements are edges, the
103    /// following `operands.numeric()` elements are numeric. Then follow
104    /// `values.edge()` edges and `values.numeric()` numeric elements.
105    data: UnsafeCell<[Datum<M::Edge>; ENTRY_CAP]>,
106}
107
108struct EntryGuard<'a, M: Manager, O, const ENTRY_CAP: usize>(&'a Entry<M, O, ENTRY_CAP>);
109
110// SAFETY: `Entry` is like a `Mutex`
111unsafe impl<M: Manager, O: Send, const ENTRY_CAP: usize> Send for Entry<M, O, ENTRY_CAP> where
112    M::Edge: Send
113{
114}
115unsafe impl<M: Manager, O: Send, const ENTRY_CAP: usize> Sync for Entry<M, O, ENTRY_CAP> where
116    M::Edge: Send
117{
118}
119
120impl<M: Manager, O: Copy + Eq, const ENTRY_CAP: usize> Entry<M, O, ENTRY_CAP> {
121    // Regarding the lint: the intent here is not to modify the `AtomicBool` in
122    // a const context but to create the `RawMutex` in a const context.
123    #[allow(clippy::declare_interior_mutable_const)]
124    const INIT: Self = Self {
125        mutex: crate::util::RawMutex::INIT,
126        operands: UnsafeCell::new(CountPair::NULL),
127        values: UnsafeCell::new(CountPair::NULL),
128        operator: UnsafeCell::new(MaybeUninit::uninit()),
129        data: UnsafeCell::new([Datum::UNINIT; ENTRY_CAP]),
130    };
131
132    #[inline]
133    fn lock(&self) -> EntryGuard<'_, M, O, ENTRY_CAP> {
134        self.mutex.lock();
135        EntryGuard(self)
136    }
137
138    #[inline]
139    fn try_lock(&self) -> Option<EntryGuard<'_, M, O, ENTRY_CAP>> {
140        if self.mutex.try_lock() {
141            Some(EntryGuard(self))
142        } else {
143            None
144        }
145    }
146}
147
148impl<M: Manager, O, const ENTRY_CAP: usize> Drop for EntryGuard<'_, M, O, ENTRY_CAP> {
149    #[inline]
150    fn drop(&mut self) {
151        // SAFETY: The entry is locked.
152        unsafe { self.0.mutex.unlock() }
153    }
154}
155
156impl<M: Manager, O, const ENTRY_CAP: usize> EntryGuard<'_, M, O, ENTRY_CAP>
157where
158    O: Copy + Eq,
159{
160    /// Is this entry occupied?
161    #[inline]
162    fn is_occupied(&self) -> bool {
163        // SAFETY: The entry is locked.
164        unsafe { *self.0.operands.get() != CountPair::NULL }
165    }
166
167    /// Get the value of this entry if it is occupied and the key (`operator`
168    /// and `operands`) matches
169    ///
170    /// Assumes that
171    /// - there is at least one operand,
172    /// - there are at most `KIND_COUNT` operands and values of each kind, and
173    /// - the count of operands and values is at most `ENTRY_CAP`.
174    #[inline]
175    fn get<const E: usize, const N: usize>(
176        &self,
177        manager: &M,
178        operator: O,
179        operands: (&[Borrowed<M::Edge>], &[u32]),
180    ) -> Option<([M::Edge; E], [u32; N])> {
181        // These conditions are ensured when called by
182        // `DMApplyCache::get_with_numeric()`
183        debug_assert_ne!(operands.0.len() + operands.1.len(), 0);
184        debug_assert!(operands.0.len() <= KIND_COUNT);
185        debug_assert!(operands.1.len() <= KIND_COUNT);
186        debug_assert!(E <= KIND_COUNT);
187        debug_assert!(N <= KIND_COUNT);
188        debug_assert!(operands.0.len() + operands.1.len() + E + N <= ENTRY_CAP);
189
190        #[cfg(feature = "statistics")]
191        STAT_ACCESSES.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
192
193        let num_operands = CountPair::new(operands.0.len(), operands.1.len());
194        // SAFETY: The entry is locked.
195        if unsafe { *self.0.operands.get() } != num_operands {
196            return None;
197        }
198
199        // SAFETY: The entry is locked.
200        let mut data = unsafe { &*self.0.data.get() }.iter();
201        for (o1, o2) in operands.0.iter().zip(data.by_ref()) {
202            // SAFETY: The first `operands.len()` operands are edges
203            if &**o1 != unsafe { o2.assume_edge_ref() } {
204                return None;
205            }
206        }
207        for (&o1, o2) in operands.1.iter().zip(data.by_ref()) {
208            // SAFETY: The next `num_numeric_operands` operands are numeric
209            if o1 != unsafe { o2.assume_numeric() } {
210                return None;
211            }
212        }
213
214        // SAFETY: The entry is (1,2) locked and (2) occupied.
215        if unsafe { (*self.0.operator.get()).assume_init() } != operator
216            || unsafe { *self.0.values.get() } != const { CountPair::new(E, N) }
217        {
218            return None;
219        }
220
221        #[cfg(feature = "statistics")]
222        STAT_HITS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
223
224        let (edge_values, remaining) = data.as_slice().split_at(E);
225        let numeric_values = &remaining[..N];
226        Some((
227            // SAFETY: The next `E` values in `data` are edges
228            std::array::from_fn(|i| unsafe {
229                manager.clone_edge(edge_values[i].assume_edge_ref())
230            }),
231            // SAFETY: The final `N` values in `data` are numeric
232            std::array::from_fn(|i| unsafe { numeric_values[i].assume_numeric() }),
233        ))
234    }
235
236    /// Set the key/value of this entry
237    ///
238    /// If `self` is already occupied and the key matches, the entry is not
239    /// updated (`operands` and `value` are not cloned).
240    ///
241    /// Assumes that
242    /// - there is at least one operand,
243    /// - there are at most `KIND_COUNT` operands and values of each kind, and
244    /// - the count of operands and values is at most `ENTRY_CAP`.
245    #[inline]
246    fn set(
247        &mut self,
248        operator: O,
249        operands: (&[Borrowed<M::Edge>], &[u32]),
250        values: (&[Borrowed<M::Edge>], &[u32]),
251    ) {
252        debug_assert_ne!(operands.0.len() + operands.1.len(), 0);
253        debug_assert!(operands.0.len() <= KIND_COUNT);
254        debug_assert!(operands.1.len() <= KIND_COUNT);
255        debug_assert!(values.0.len() <= KIND_COUNT);
256        debug_assert!(values.1.len() <= KIND_COUNT);
257        debug_assert!(
258            operands.0.len() + operands.1.len() + values.0.len() + values.1.len() <= ENTRY_CAP
259        );
260
261        self.clear();
262
263        #[cfg(feature = "statistics")]
264        STAT_INSERTIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
265
266        // SAFETY (next 2 dereference ops): The entry is locked.
267        unsafe { &mut *self.0.operator.get() }.write(operator);
268        let mut data = unsafe { &mut *self.0.data.get() }.iter_mut();
269        for (src, dst) in operands.0.iter().zip(data.by_ref()) {
270            dst.write_edge(src.borrowed());
271        }
272        for (&src, dst) in operands.1.iter().zip(data.by_ref()) {
273            dst.write_numeric(src);
274        }
275        for (src, dst) in values.0.iter().zip(data.by_ref()) {
276            dst.write_edge(src.borrowed());
277        }
278        for (&src, dst) in values.1.iter().zip(data) {
279            dst.write_numeric(src);
280        }
281
282        // Important: Set the counts last for exception safety (the functions
283        // above might panic).
284        unsafe { *self.0.values.get() = CountPair::new(values.0.len(), values.1.len()) };
285        unsafe { *self.0.operands.get() = CountPair::new(operands.0.len(), operands.1.len()) };
286    }
287
288    /// Clear this entry
289    #[inline(always)]
290    fn clear(&mut self) {
291        // SAFETY: The entry is locked.
292        unsafe { *self.0.operands.get() = CountPair::NULL };
293        // `Edge`s are just borrowed, so nothing else to do.
294    }
295}
296
297impl<M, O, H, const ENTRY_CAP: usize> DMApplyCache<M, O, H, ENTRY_CAP>
298where
299    M: Manager,
300    O: Copy + Eq + Hash,
301    H: Hasher + Default,
302{
303    const CHECK_ENTRY_CAP: () = {
304        assert!(
305            0 < ENTRY_CAP && ENTRY_CAP <= KIND_COUNT * 4,
306            "ENTRY_CAP must be in range [1, 64]"
307        );
308    };
309
310    /// Create a new `ApplyCache` with the given capacity (entries).
311    ///
312    /// # Safety
313    ///
314    /// The apply cache must only be used inside a manager that guarantees all
315    /// node deletions to be wrapped inside an
316    /// [`ManagerEventSubscriber::pre_gc()`] /
317    /// [`ManagerEventSubscriber::post_gc()`] pair.
318    pub unsafe fn with_capacity(capacity: usize) -> Self {
319        let () = Self::CHECK_ENTRY_CAP;
320        let buckets = capacity
321            .checked_next_power_of_two()
322            .expect("capacity is too large");
323        #[cfg(not(feature = "hugealloc"))]
324        let mut vec = Vec::with_capacity(buckets);
325        #[cfg(feature = "hugealloc")]
326        let mut vec = Vec::with_capacity_in(buckets, hugealloc::HugeAlloc);
327
328        vec.resize_with(buckets, || Entry::INIT);
329        DMApplyCache(vec.into_boxed_slice(), PhantomData)
330    }
331
332    /// Get the bucket for the given operator and operands
333    #[inline]
334    fn bucket(
335        &self,
336        operator: O,
337        operands: (&[Borrowed<M::Edge>], &[u32]),
338    ) -> &Entry<M, O, ENTRY_CAP> {
339        let mut hasher = H::default();
340        operator.hash(&mut hasher);
341        for o in operands.0 {
342            o.hash(&mut hasher);
343        }
344        for o in operands.1 {
345            o.hash(&mut hasher);
346        }
347        let mask = (self.0.len() - 1) as u64; // bucket count is a power of two
348        let index = (hasher.finish() & mask) as usize;
349        debug_assert!(index < self.0.len());
350        // SAFETY: access is guaranteed to be in bounds
351        unsafe { self.0.get_unchecked(index) }
352    }
353}
354
355#[cfg(feature = "statistics")]
356static STAT_ACCESSES: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
357
358#[cfg(feature = "statistics")]
359static STAT_HITS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
360
361#[cfg(feature = "statistics")]
362static STAT_INSERTIONS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
363
364impl<M, O, H, const ENTRY_CAP: usize> crate::StatisticsGenerator
365    for DMApplyCache<M, O, H, ENTRY_CAP>
366where
367    M: Manager,
368    O: Copy + Eq,
369{
370    #[cfg(not(feature = "statistics"))]
371    fn print_stats(&self) {}
372
373    #[cfg(feature = "statistics")]
374    fn print_stats(&self) {
375        let count = self.0.len();
376        debug_assert_ne!(count, 0);
377        let occupied = self.0.iter().filter(|e| e.lock().is_occupied()).count();
378
379        let accesses = STAT_ACCESSES.swap(0, std::sync::atomic::Ordering::Relaxed);
380        let hits = STAT_HITS.swap(0, std::sync::atomic::Ordering::Relaxed);
381        let insertions = STAT_INSERTIONS.swap(0, std::sync::atomic::Ordering::Relaxed);
382        println!(
383            "[DMApplyCache] fill level: {:.2} %, accesses: {accesses}, hits: {hits}, insertions: {insertions}, hit ratio ~{:.2} %",
384            100.0 * occupied as f32 / count as f32,
385            100.0 * hits as f32 / accesses as f32,
386        );
387    }
388}
389
390impl<M, O, H, const ENTRY_CAP: usize> ApplyCache<M, O> for DMApplyCache<M, O, H, ENTRY_CAP>
391where
392    M: Manager,
393    O: Copy + Hash + Ord,
394    H: Hasher + Default,
395{
396    #[inline(always)]
397    fn get_extended<const E: usize, const N: usize>(
398        &self,
399        manager: &M,
400        operator: O,
401        operands: (&[Borrowed<M::Edge>], &[u32]),
402    ) -> Option<([M::Edge; E], [u32; N])> {
403        let total_operands = operands.0.len() + operands.1.len();
404        if total_operands == 0
405            || total_operands + (N + E) > ENTRY_CAP
406            || operands.0.len() > KIND_COUNT
407            || operands.1.len() > KIND_COUNT
408            || N > KIND_COUNT
409            || E > KIND_COUNT
410        {
411            return None;
412        }
413        self.bucket(operator, operands)
414            .try_lock()?
415            .get(manager, operator, operands)
416    }
417
418    #[inline(always)]
419    fn add_extended(
420        &self,
421        _manager: &M,
422        operator: O,
423        operands: (&[Borrowed<M::Edge>], &[u32]),
424        values: (&[Borrowed<M::Edge>], &[u32]),
425    ) {
426        let total_operands = operands.0.len() + operands.1.len();
427        if total_operands == 0
428            || total_operands + (values.0.len() + values.1.len()) > ENTRY_CAP
429            || operands.0.len() > KIND_COUNT
430            || operands.1.len() > KIND_COUNT
431            || values.0.len() > KIND_COUNT
432            || values.1.len() > KIND_COUNT
433        {
434            return;
435        }
436        if let Some(mut entry) = self.bucket(operator, operands).try_lock() {
437            entry.set(operator, operands, values);
438        }
439    }
440
441    fn clear(&self, _manager: &M) {
442        for entry in &*self.0 {
443            entry.lock().clear();
444        }
445    }
446}
447
448impl<M, O, H, const ENTRY_CAP: usize> ManagerEventSubscriber<M> for DMApplyCache<M, O, H, ENTRY_CAP>
449where
450    M: Manager,
451    O: Copy + Hash + Ord,
452    H: Hasher + Default,
453{
454    fn pre_gc(&self, _manager: &M) {
455        // FIXME: We should probably do something smarter than clearing the
456        // entire cache.
457        for entry in &*self.0 {
458            let mut entry = entry.lock();
459            entry.clear();
460            // Don't unlock!
461            std::mem::forget(entry);
462        }
463    }
464
465    unsafe fn post_gc(&self, _manager: &M) {
466        for entry in &*self.0 {
467            // SAFETY: `post_gc()` is called at most once after `pre_gc()` and
468            // reordering. Hence, the mutex is locked. The cache is empty, so
469            // we don't risk that a call to `get()` returns an invalid edge.
470            unsafe { entry.mutex.unlock() };
471        }
472    }
473}
474
475impl<M, O, H, const ENTRY_CAP: usize> fmt::Debug for DMApplyCache<M, O, H, ENTRY_CAP>
476where
477    M: Manager,
478    M::Edge: fmt::Debug,
479    O: Copy + Eq + fmt::Debug,
480{
481    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
482        f.debug_map()
483            .entries(
484                self.0
485                    .iter()
486                    .enumerate()
487                    .map(|(i, e)| (i, e.lock()))
488                    .filter(|(_, e)| e.is_occupied()),
489            )
490            .finish()
491    }
492}
493
494impl<M, O, const ENTRY_CAP: usize> fmt::Debug for EntryGuard<'_, M, O, ENTRY_CAP>
495where
496    M: Manager,
497    M::Edge: fmt::Debug,
498    O: Copy + Eq + fmt::Debug,
499{
500    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
501        // SAFETY: The entry is locked.
502        let operands = unsafe { *self.0.operands.get() };
503        if operands == CountPair::NULL {
504            return f.write_str("None");
505        }
506
507        // SAFETY: The entry is (1-3) locked and (1) occupied.
508        let operator = unsafe { (*self.0.operator.get()).assume_init() };
509        let values = unsafe { *self.0.operands.get() };
510        let mut data = unsafe { &*self.0.data.get() }.iter();
511
512        f.write_str("{{ ")?;
513        operator.fmt(f)?;
514
515        let mut tuple = f.debug_tuple("");
516        for operand in data.by_ref().take(operands.edge()) {
517            tuple.field(unsafe { operand.assume_edge_ref() });
518        }
519        for operand in data.by_ref().take(operands.numeric()) {
520            tuple.field(&unsafe { operand.assume_numeric() });
521        }
522        tuple.finish()?;
523
524        f.write_str(" = ")?;
525
526        let mut tuple = f.debug_tuple("");
527        for value in data.by_ref().take(values.edge()) {
528            tuple.field(unsafe { value.assume_edge_ref() });
529        }
530        for value in data.by_ref().take(values.numeric()) {
531            tuple.field(&unsafe { value.assume_numeric() });
532        }
533        tuple.finish()?;
534
535        f.write_str(" }}")
536    }
537}