oxidd_cache/
direct.rs

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