1//! VecCache maintains a mapping from K -> (V, I) pairing. K and I must be roughly u32-sized, and V
2//! must be Copy.
3//!
4//! VecCache supports efficient concurrent put/get across the key space, with write-once semantics
5//! (i.e., a given key can only be put once). Subsequent puts will panic.
6//!
7//! This is currently used for query caching.
89use std::fmt::Debug;
10use std::marker::PhantomData;
11use std::sync::atomic::{AtomicPtr, AtomicU32, AtomicUsize, Ordering};
1213use rustc_index::Idx;
1415struct Slot<V> {
16// We never construct &Slot<V> so it's fine for this to not be in an UnsafeCell.
17value: V,
18// This is both an index and a once-lock.
19 //
20 // 0: not yet initialized.
21 // 1: lock held, initializing.
22 // 2..u32::MAX - 2: initialized.
23index_and_lock: AtomicU32,
24}
2526/// This uniquely identifies a single `Slot<V>` entry in the buckets map, and provides accessors for
27/// either getting the value or putting a value.
28#[derive(#[automatically_derived]
impl ::core::marker::Copy for SlotIndex { }Copy, #[automatically_derived]
impl ::core::clone::Clone for SlotIndex {
#[inline]
fn clone(&self) -> SlotIndex {
let _: ::core::clone::AssertParamIsClone<usize>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for SlotIndex {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field3_finish(f, "SlotIndex",
"bucket_idx", &self.bucket_idx, "entries", &self.entries,
"index_in_bucket", &&self.index_in_bucket)
}
}Debug)]
29struct SlotIndex {
30// the index of the bucket in VecCache (0 to 20)
31bucket_idx: usize,
32// number of entries in that bucket
33entries: usize,
34// the index of the slot within the bucket
35index_in_bucket: usize,
36}
3738// This makes sure the counts are consistent with what we allocate, precomputing each bucket a
39// compile-time. Visiting all powers of two is enough to hit all the buckets.
40//
41// We confirm counts are accurate in the slot_index_exhaustive test.
42const ENTRIES_BY_BUCKET: [usize; 21] = {
43let mut entries = [0; 21];
44let mut key = 0;
45loop {
46let si = SlotIndex::from_index(key);
47entries[si.bucket_idx] = si.entries;
48if key == 0 {
49key = 1;
50 } else if key == (1 << 31) {
51break;
52 } else {
53key <<= 1;
54 }
55 }
56entries57};
5859impl SlotIndex {
60// This unpacks a flat u32 index into identifying which bucket it belongs to and the offset
61 // within that bucket. As noted in the VecCache docs, buckets double in size with each index.
62 // Typically that would mean 31 buckets (2^0 + 2^1 ... + 2^31 = u32::MAX - 1), but to reduce
63 // the size of the VecCache struct and avoid uselessly small allocations, we instead have the
64 // first bucket have 2**12 entries. To simplify the math, the second bucket also 2**12 entries,
65 // and buckets double from there.
66 //
67 // We assert that [0, 2**32 - 1] uniquely map through this function to individual, consecutive
68 // slots (see `slot_index_exhaustive` in tests).
69#[inline]
70const fn from_index(idx: u32) -> Self {
71const FIRST_BUCKET_SHIFT: usize = 12;
72if idx < (1 << FIRST_BUCKET_SHIFT) {
73return SlotIndex {
74 bucket_idx: 0,
75 entries: 1 << FIRST_BUCKET_SHIFT,
76 index_in_bucket: idxas usize,
77 };
78 }
79// We already ruled out idx 0, so this `ilog2` never panics (and the check optimizes away)
80let bucket = idx.ilog2() as usize;
81let entries = 1 << bucket;
82SlotIndex {
83 bucket_idx: bucket - FIRST_BUCKET_SHIFT + 1,
84entries,
85 index_in_bucket: idxas usize - entries,
86 }
87 }
8889// SAFETY: Buckets must be managed solely by functions here (i.e., get/put on SlotIndex) and
90 // `self` comes from SlotIndex::from_index
91#[inline]
92unsafe fn get<V: Copy>(&self, buckets: &[AtomicPtr<Slot<V>>; 21]) -> Option<(V, u32)> {
93// SAFETY: `bucket_idx` is ilog2(u32).saturating_sub(11), which is at most 21, i.e.,
94 // in-bounds of buckets. See `from_index` for computation.
95let bucket = unsafe { buckets.get_unchecked(self.bucket_idx) };
96let ptr = bucket.load(Ordering::Acquire);
97// Bucket is not yet initialized: then we obviously won't find this entry in that bucket.
98if ptr.is_null() {
99return None;
100 }
101if !(self.index_in_bucket < self.entries) {
::core::panicking::panic("assertion failed: self.index_in_bucket < self.entries")
};assert!(self.index_in_bucket < self.entries);
102// SAFETY: `bucket` was allocated (so <= isize in total bytes) to hold `entries`, so this
103 // must be inbounds.
104let slot = unsafe { ptr.add(self.index_in_bucket) };
105106// SAFETY: initialized bucket has zeroed all memory within the bucket, so we are valid for
107 // AtomicU32 access.
108let index_and_lock = unsafe { &(*slot).index_and_lock };
109let current = index_and_lock.load(Ordering::Acquire);
110let index = match current {
1110 => return None,
112// Treat "initializing" as actually just not initialized at all.
113 // The only reason this is a separate state is that `complete` calls could race and
114 // we can't allow that, but from load perspective there's no difference.
1151 => return None,
116_ => current - 2,
117 };
118119// SAFETY:
120 // * slot is a valid pointer (buckets are always valid for the index we get).
121 // * value is initialized since we saw a >= 2 index above.
122 // * `V: Copy`, so safe to read.
123let value = unsafe { (*slot).value };
124Some((value, index))
125 }
126127fn bucket_ptr<V>(&self, bucket: &AtomicPtr<Slot<V>>) -> *mut Slot<V> {
128let ptr = bucket.load(Ordering::Acquire);
129if ptr.is_null() { self.initialize_bucket(bucket) } else { ptr }
130 }
131132#[cold]
133fn initialize_bucket<V>(&self, bucket: &AtomicPtr<Slot<V>>) -> *mut Slot<V> {
134static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
135136// If we are initializing the bucket, then acquire a global lock.
137 //
138 // This path is quite cold, so it's cheap to use a global lock. This ensures that we never
139 // have multiple allocations for the same bucket.
140let _allocator_guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
141142let ptr = bucket.load(Ordering::Acquire);
143144// OK, now under the allocator lock, if we're still null then it's definitely us that will
145 // initialize this bucket.
146if ptr.is_null() {
147let bucket_layout =
148 std::alloc::Layout::array::<Slot<V>>(self.entries as usize).unwrap();
149// This is more of a sanity check -- this code is very cold, so it's safe to pay a
150 // little extra cost here.
151if !(bucket_layout.size() > 0) {
::core::panicking::panic("assertion failed: bucket_layout.size() > 0")
};assert!(bucket_layout.size() > 0);
152// SAFETY: Just checked that size is non-zero.
153let allocated = unsafe { std::alloc::alloc_zeroed(bucket_layout).cast::<Slot<V>>() };
154if allocated.is_null() {
155 std::alloc::handle_alloc_error(bucket_layout);
156 }
157bucket.store(allocated, Ordering::Release);
158allocated159 } else {
160// Otherwise some other thread initialized this bucket after we took the lock. In that
161 // case, just return early.
162ptr163 }
164 }
165166/// Returns true if this successfully put into the map.
167#[inline]
168fn put<V>(&self, buckets: &[AtomicPtr<Slot<V>>; 21], value: V, extra: u32) -> bool {
169// SAFETY: `bucket_idx` is ilog2(u32).saturating_sub(11), which is at most 21, i.e.,
170 // in-bounds of buckets.
171let bucket = unsafe { buckets.get_unchecked(self.bucket_idx) };
172let ptr = self.bucket_ptr(bucket);
173174if !(self.index_in_bucket < self.entries) {
::core::panicking::panic("assertion failed: self.index_in_bucket < self.entries")
};assert!(self.index_in_bucket < self.entries);
175// SAFETY: `bucket` was allocated (so <= isize in total bytes) to hold `entries`, so this
176 // must be inbounds.
177let slot = unsafe { ptr.add(self.index_in_bucket) };
178179// SAFETY: initialized bucket has zeroed all memory within the bucket, so we are valid for
180 // AtomicU32 access.
181let index_and_lock = unsafe { &(*slot).index_and_lock };
182match index_and_lock.compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire) {
183Ok(_) => {
184// We have acquired the initialization lock. It is our job to write `value` and
185 // then set the lock to the real index.
186187unsafe {
188 (&raw mut (*slot).value).write(value);
189 }
190191index_and_lock.store(extra.checked_add(2).unwrap(), Ordering::Release);
192193true
194}
195196// Treat "initializing" as the caller's fault. Callers are responsible for ensuring that
197 // there are no races on initialization. In the compiler's current usage for query
198 // caches, that's the "active query map" which ensures each query actually runs once
199 // (even if concurrently started).
200Err(1) => { ::core::panicking::panic_fmt(format_args!("caller raced calls to put()")); }panic!("caller raced calls to put()"),
201202// This slot was already populated. Also ignore, currently this is the same as
203 // "initializing".
204Err(_) => false,
205 }
206 }
207}
208209/// In-memory cache for queries whose keys are densely-numbered IDs
210/// (e.g `CrateNum`, `LocalDefId`), and can therefore be used as indices
211/// into a dense vector of cached values.
212///
213/// (As of [#124780] the underlying storage is not an actual `Vec`, but rather
214/// a series of increasingly-large buckets, for improved performance when the
215/// parallel frontend is using multiple threads.)
216///
217/// Each entry in the cache stores the query's return value (`V`), and also
218/// an associated index (`I`), which in practice is a `DepNodeIndex` used for
219/// query dependency tracking.
220///
221/// [#124780]: https://github.com/rust-lang/rust/pull/124780
222pub struct VecCache<K: Idx, V, I> {
223// Entries per bucket:
224 // Bucket 0: 4096 2^12
225 // Bucket 1: 4096 2^12
226 // Bucket 2: 8192
227 // Bucket 3: 16384
228 // ...
229 // Bucket 19: 1073741824
230 // Bucket 20: 2147483648
231 // The total number of entries if all buckets are initialized is u32::MAX-1.
232buckets: [AtomicPtr<Slot<V>>; 21],
233234// In the compiler's current usage these are only *read* during incremental and self-profiling.
235 // They are an optimization over iterating the full buckets array.
236present: [AtomicPtr<Slot<()>>; 21],
237 len: AtomicUsize,
238239 key: PhantomData<(K, I)>,
240}
241242impl<K: Idx, V, I> Defaultfor VecCache<K, V, I> {
243fn default() -> Self {
244VecCache {
245 buckets: Default::default(),
246 key: PhantomData,
247 len: Default::default(),
248 present: Default::default(),
249 }
250 }
251}
252253// SAFETY: No access to `V` is made.
254unsafe impl<K: Idx, #[may_dangle] V, I> Dropfor VecCache<K, V, I> {
255fn drop(&mut self) {
256// We have unique ownership, so no locks etc. are needed. Since `K` and `V` are both `Copy`,
257 // we are also guaranteed to just need to deallocate any large arrays (not iterate over
258 // contents).
259 //
260 // Confirm no need to deallocate individual entries. Note that `V: Copy` is asserted on
261 // insert/lookup but not necessarily construction, primarily to avoid annoyingly propagating
262 // the bounds into struct definitions everywhere.
263if !!std::mem::needs_drop::<K>() {
::core::panicking::panic("assertion failed: !std::mem::needs_drop::<K>()")
};assert!(!std::mem::needs_drop::<K>());
264if !!std::mem::needs_drop::<V>() {
::core::panicking::panic("assertion failed: !std::mem::needs_drop::<V>()")
};assert!(!std::mem::needs_drop::<V>());
265266for (idx, bucket) in self.buckets.iter().enumerate() {
267let bucket = bucket.load(Ordering::Acquire);
268if !bucket.is_null() {
269let layout = std::alloc::Layout::array::<Slot<V>>(ENTRIES_BY_BUCKET[idx]).unwrap();
270unsafe {
271 std::alloc::dealloc(bucket.cast(), layout);
272 }
273 }
274 }
275276for (idx, bucket) in self.present.iter().enumerate() {
277let bucket = bucket.load(Ordering::Acquire);
278if !bucket.is_null() {
279let layout = std::alloc::Layout::array::<Slot<()>>(ENTRIES_BY_BUCKET[idx]).unwrap();
280unsafe {
281 std::alloc::dealloc(bucket.cast(), layout);
282 }
283 }
284 }
285 }
286}
287288impl<K, V, I> VecCache<K, V, I>
289where
290K: Eq + Idx + Copy + Debug,
291 V: Copy,
292 I: Idx + Copy,
293{
294#[inline(always)]
295pub fn lookup(&self, key: &K) -> Option<(V, I)> {
296let key = u32::try_from(key.index()).unwrap();
297let slot_idx = SlotIndex::from_index(key);
298match unsafe { slot_idx.get(&self.buckets) } {
299Some((value, idx)) => Some((value, I::new(idxas usize))),
300None => None,
301 }
302 }
303304#[inline]
305pub fn complete(&self, key: K, value: V, index: I) {
306let key = u32::try_from(key.index()).unwrap();
307let slot_idx = SlotIndex::from_index(key);
308if slot_idx.put(&self.buckets, value, index.index() as u32) {
309let present_idx = self.len.fetch_add(1, Ordering::Relaxed);
310let slot = SlotIndex::from_index(present_idxas u32);
311// We should always be uniquely putting due to `len` fetch_add returning unique values.
312if !slot.put(&self.present, (), key) {
::core::panicking::panic("assertion failed: slot.put(&self.present, (), key)")
};assert!(slot.put(&self.present, (), key));
313 }
314 }
315316pub fn iter(&self, f: &mut dyn FnMut(&K, &V, I)) {
317for idx in 0..self.len.load(Ordering::Acquire) {
318let key = SlotIndex::from_index(idx as u32);
319match unsafe { key.get(&self.present) } {
320// This shouldn't happen in our current usage (iter is really only
321 // used long after queries are done running), but if we hit this in practice it's
322 // probably fine to just break early.
323None => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
324Some(((), key)) => {
325let key = K::new(key as usize);
326// unwrap() is OK: present entries are always written only after we put the real
327 // entry.
328let value = self.lookup(&key).unwrap();
329 f(&key, &value.0, value.1);
330 }
331 }
332 }
333 }
334}
335336#[cfg(test)]
337mod tests;