Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 5926e82

Browse files
committedNov 19, 2024
Auto merge of #124780 - Mark-Simulacrum:lockless-cache, r=lcnr
Improve VecCache under parallel frontend This replaces the single Vec allocation with a series of progressively larger buckets. With the cfg for parallel enabled but with -Zthreads=1, this looks like a slight regression in i-count and cycle counts (~1%). With the parallel frontend at -Zthreads=4, this is an improvement (-5% wall-time from 5.788 to 5.4688 on libcore) than our current Lock-based approach, likely due to reducing the bouncing of the cache line holding the lock. At -Zthreads=32 it's a huge improvement (-46%: 8.829 -> 4.7319 seconds). try-job: i686-gnu-nopt try-job: dist-x86_64-linux
2 parents b71fb5e + da58efb commit 5926e82

File tree

6 files changed

+458
-65
lines changed

6 files changed

+458
-65
lines changed
 

‎compiler/rustc_data_structures/src/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
#![feature(auto_traits)]
2222
#![feature(cfg_match)]
2323
#![feature(core_intrinsics)]
24+
#![feature(dropck_eyepatch)]
2425
#![feature(extend_one)]
2526
#![feature(file_buffered)]
2627
#![feature(hash_raw_entry)]
@@ -78,6 +79,7 @@ pub mod thinvec;
7879
pub mod transitive_relation;
7980
pub mod unhash;
8081
pub mod unord;
82+
pub mod vec_cache;
8183
pub mod work_queue;
8284

8385
mod atomic_ref;
Lines changed: 324 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,324 @@
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.
8+
9+
use std::fmt::Debug;
10+
use std::marker::PhantomData;
11+
use std::sync::atomic::{AtomicPtr, AtomicU32, AtomicUsize, Ordering};
12+
13+
use rustc_index::Idx;
14+
15+
struct Slot<V> {
16+
// We never construct &Slot<V> so it's fine for this to not be in an UnsafeCell.
17+
value: 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.
23+
index_and_lock: AtomicU32,
24+
}
25+
26+
/// 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(Copy, Clone, Debug)]
29+
struct SlotIndex {
30+
// the index of the bucket in VecCache (0 to 20)
31+
bucket_idx: usize,
32+
// number of entries in that bucket
33+
entries: usize,
34+
// the index of the slot within the bucket
35+
index_in_bucket: usize,
36+
}
37+
38+
// 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.
42+
const ENTRIES_BY_BUCKET: [usize; 21] = {
43+
let mut entries = [0; 21];
44+
let mut key = 0;
45+
loop {
46+
let si = SlotIndex::from_index(key);
47+
entries[si.bucket_idx] = si.entries;
48+
if key == 0 {
49+
key = 1;
50+
} else if key == (1 << 31) {
51+
break;
52+
} else {
53+
key <<= 1;
54+
}
55+
}
56+
entries
57+
};
58+
59+
impl 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]
70+
const fn from_index(idx: u32) -> Self {
71+
let mut bucket = match idx.checked_ilog2() {
72+
Some(x) => x as usize,
73+
None => 0,
74+
};
75+
let entries;
76+
let running_sum;
77+
if bucket <= 11 {
78+
entries = 1 << 12;
79+
running_sum = 0;
80+
bucket = 0;
81+
} else {
82+
entries = 1 << bucket;
83+
running_sum = entries;
84+
bucket = bucket - 11;
85+
}
86+
SlotIndex { bucket_idx: bucket, entries, index_in_bucket: idx as usize - running_sum }
87+
}
88+
89+
// 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]
92+
unsafe 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.
95+
let bucket = unsafe { buckets.get_unchecked(self.bucket_idx) };
96+
let ptr = bucket.load(Ordering::Acquire);
97+
// Bucket is not yet initialized: then we obviously won't find this entry in that bucket.
98+
if ptr.is_null() {
99+
return None;
100+
}
101+
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.
104+
let slot = unsafe { ptr.add(self.index_in_bucket) };
105+
106+
// SAFETY: initialized bucket has zeroed all memory within the bucket, so we are valid for
107+
// AtomicU32 access.
108+
let index_and_lock = unsafe { &(*slot).index_and_lock };
109+
let current = index_and_lock.load(Ordering::Acquire);
110+
let index = match current {
111+
0 => 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.
115+
1 => return None,
116+
_ => current - 2,
117+
};
118+
119+
// 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.
123+
let value = unsafe { (*slot).value };
124+
Some((value, index))
125+
}
126+
127+
fn bucket_ptr<V>(&self, bucket: &AtomicPtr<Slot<V>>) -> *mut Slot<V> {
128+
let ptr = bucket.load(Ordering::Acquire);
129+
if ptr.is_null() { self.initialize_bucket(bucket) } else { ptr }
130+
}
131+
132+
#[cold]
133+
fn initialize_bucket<V>(&self, bucket: &AtomicPtr<Slot<V>>) -> *mut Slot<V> {
134+
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
135+
136+
// 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.
140+
let _allocator_guard = LOCK.lock().unwrap_or_else(|e| e.into_inner());
141+
142+
let ptr = bucket.load(Ordering::Acquire);
143+
144+
// OK, now under the allocator lock, if we're still null then it's definitely us that will
145+
// initialize this bucket.
146+
if ptr.is_null() {
147+
let 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.
151+
assert!(bucket_layout.size() > 0);
152+
// SAFETY: Just checked that size is non-zero.
153+
let allocated = unsafe { std::alloc::alloc_zeroed(bucket_layout).cast::<Slot<V>>() };
154+
if allocated.is_null() {
155+
std::alloc::handle_alloc_error(bucket_layout);
156+
}
157+
bucket.store(allocated, Ordering::Release);
158+
allocated
159+
} else {
160+
// Otherwise some other thread initialized this bucket after we took the lock. In that
161+
// case, just return early.
162+
ptr
163+
}
164+
}
165+
166+
/// Returns true if this successfully put into the map.
167+
#[inline]
168+
fn 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.
171+
let bucket = unsafe { buckets.get_unchecked(self.bucket_idx) };
172+
let ptr = self.bucket_ptr(bucket);
173+
174+
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.
177+
let slot = unsafe { ptr.add(self.index_in_bucket) };
178+
179+
// SAFETY: initialized bucket has zeroed all memory within the bucket, so we are valid for
180+
// AtomicU32 access.
181+
let index_and_lock = unsafe { &(*slot).index_and_lock };
182+
match index_and_lock.compare_exchange(0, 1, Ordering::AcqRel, Ordering::Acquire) {
183+
Ok(_) => {
184+
// We have acquired the initialization lock. It is our job to write `value` and
185+
// then set the lock to the real index.
186+
187+
unsafe {
188+
(&raw mut (*slot).value).write(value);
189+
}
190+
191+
index_and_lock.store(extra.checked_add(2).unwrap(), Ordering::Release);
192+
193+
true
194+
}
195+
196+
// 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).
200+
Err(1) => panic!("caller raced calls to put()"),
201+
202+
// This slot was already populated. Also ignore, currently this is the same as
203+
// "initializing".
204+
Err(_) => false,
205+
}
206+
}
207+
}
208+
209+
pub struct VecCache<K: Idx, V, I> {
210+
// Entries per bucket:
211+
// Bucket 0: 4096 2^12
212+
// Bucket 1: 4096 2^12
213+
// Bucket 2: 8192
214+
// Bucket 3: 16384
215+
// ...
216+
// Bucket 19: 1073741824
217+
// Bucket 20: 2147483648
218+
// The total number of entries if all buckets are initialized is u32::MAX-1.
219+
buckets: [AtomicPtr<Slot<V>>; 21],
220+
221+
// In the compiler's current usage these are only *read* during incremental and self-profiling.
222+
// They are an optimization over iterating the full buckets array.
223+
present: [AtomicPtr<Slot<()>>; 21],
224+
len: AtomicUsize,
225+
226+
key: PhantomData<(K, I)>,
227+
}
228+
229+
impl<K: Idx, V, I> Default for VecCache<K, V, I> {
230+
fn default() -> Self {
231+
VecCache {
232+
buckets: Default::default(),
233+
key: PhantomData,
234+
len: Default::default(),
235+
present: Default::default(),
236+
}
237+
}
238+
}
239+
240+
// SAFETY: No access to `V` is made.
241+
unsafe impl<K: Idx, #[may_dangle] V, I> Drop for VecCache<K, V, I> {
242+
fn drop(&mut self) {
243+
// We have unique ownership, so no locks etc. are needed. Since `K` and `V` are both `Copy`,
244+
// we are also guaranteed to just need to deallocate any large arrays (not iterate over
245+
// contents).
246+
//
247+
// Confirm no need to deallocate invidual entries. Note that `V: Copy` is asserted on
248+
// insert/lookup but not necessarily construction, primarily to avoid annoyingly propagating
249+
// the bounds into struct definitions everywhere.
250+
assert!(!std::mem::needs_drop::<K>());
251+
assert!(!std::mem::needs_drop::<V>());
252+
253+
for (idx, bucket) in self.buckets.iter().enumerate() {
254+
let bucket = bucket.load(Ordering::Acquire);
255+
if !bucket.is_null() {
256+
let layout = std::alloc::Layout::array::<Slot<V>>(ENTRIES_BY_BUCKET[idx]).unwrap();
257+
unsafe {
258+
std::alloc::dealloc(bucket.cast(), layout);
259+
}
260+
}
261+
}
262+
263+
for (idx, bucket) in self.present.iter().enumerate() {
264+
let bucket = bucket.load(Ordering::Acquire);
265+
if !bucket.is_null() {
266+
let layout = std::alloc::Layout::array::<Slot<()>>(ENTRIES_BY_BUCKET[idx]).unwrap();
267+
unsafe {
268+
std::alloc::dealloc(bucket.cast(), layout);
269+
}
270+
}
271+
}
272+
}
273+
}
274+
275+
impl<K, V, I> VecCache<K, V, I>
276+
where
277+
K: Eq + Idx + Copy + Debug,
278+
V: Copy,
279+
I: Idx + Copy,
280+
{
281+
#[inline(always)]
282+
pub fn lookup(&self, key: &K) -> Option<(V, I)> {
283+
let key = u32::try_from(key.index()).unwrap();
284+
let slot_idx = SlotIndex::from_index(key);
285+
match unsafe { slot_idx.get(&self.buckets) } {
286+
Some((value, idx)) => Some((value, I::new(idx as usize))),
287+
None => None,
288+
}
289+
}
290+
291+
#[inline]
292+
pub fn complete(&self, key: K, value: V, index: I) {
293+
let key = u32::try_from(key.index()).unwrap();
294+
let slot_idx = SlotIndex::from_index(key);
295+
if slot_idx.put(&self.buckets, value, index.index() as u32) {
296+
let present_idx = self.len.fetch_add(1, Ordering::Relaxed);
297+
let slot = SlotIndex::from_index(present_idx as u32);
298+
// We should always be uniquely putting due to `len` fetch_add returning unique values.
299+
assert!(slot.put(&self.present, (), key));
300+
}
301+
}
302+
303+
pub fn iter(&self, f: &mut dyn FnMut(&K, &V, I)) {
304+
for idx in 0..self.len.load(Ordering::Acquire) {
305+
let key = SlotIndex::from_index(idx as u32);
306+
match unsafe { key.get(&self.present) } {
307+
// This shouldn't happen in our current usage (iter is really only
308+
// used long after queries are done running), but if we hit this in practice it's
309+
// probably fine to just break early.
310+
None => unreachable!(),
311+
Some(((), key)) => {
312+
let key = K::new(key as usize);
313+
// unwrap() is OK: present entries are always written only after we put the real
314+
// entry.
315+
let value = self.lookup(&key).unwrap();
316+
f(&key, &value.0, value.1);
317+
}
318+
}
319+
}
320+
}
321+
}
322+
323+
#[cfg(test)]
324+
mod tests;
Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
use super::*;
2+
3+
#[test]
4+
#[cfg(not(miri))]
5+
fn vec_cache_empty() {
6+
let cache: VecCache<u32, u32, u32> = VecCache::default();
7+
for key in 0..u32::MAX {
8+
assert!(cache.lookup(&key).is_none());
9+
}
10+
}
11+
12+
#[test]
13+
fn vec_cache_insert_and_check() {
14+
let cache: VecCache<u32, u32, u32> = VecCache::default();
15+
cache.complete(0, 1, 2);
16+
assert_eq!(cache.lookup(&0), Some((1, 2)));
17+
}
18+
19+
#[test]
20+
fn sparse_inserts() {
21+
let cache: VecCache<u32, u8, u32> = VecCache::default();
22+
let end = if cfg!(target_pointer_width = "64") && cfg!(target_os = "linux") {
23+
// For paged memory, 64-bit systems we should be able to sparsely allocate all of the pages
24+
// needed for these inserts cheaply (without needing to actually have gigabytes of resident
25+
// memory).
26+
31
27+
} else {
28+
// Otherwise, still run the test but scaled back:
29+
//
30+
// Each slot is 5 bytes, so 2^25 entries (on non-virtual memory systems, like e.g. Windows) will
31+
// mean 160 megabytes of allocated memory. Going beyond that is probably not reasonable for
32+
// tests.
33+
25
34+
};
35+
for shift in 0..end {
36+
let key = 1u32 << shift;
37+
cache.complete(key, shift, key);
38+
assert_eq!(cache.lookup(&key), Some((shift, key)));
39+
}
40+
}
41+
42+
#[test]
43+
fn concurrent_stress_check() {
44+
let cache: VecCache<u32, u32, u32> = VecCache::default();
45+
std::thread::scope(|s| {
46+
for idx in 0..100 {
47+
let cache = &cache;
48+
s.spawn(move || {
49+
cache.complete(idx, idx, idx);
50+
});
51+
}
52+
});
53+
54+
for idx in 0..100 {
55+
assert_eq!(cache.lookup(&idx), Some((idx, idx)));
56+
}
57+
}
58+
59+
#[test]
60+
fn slot_entries_table() {
61+
assert_eq!(ENTRIES_BY_BUCKET, [
62+
4096, 4096, 8192, 16384, 32768, 65536, 131072, 262144, 524288, 1048576, 2097152, 4194304,
63+
8388608, 16777216, 33554432, 67108864, 134217728, 268435456, 536870912, 1073741824,
64+
2147483648
65+
]);
66+
}
67+
68+
#[test]
69+
#[cfg(not(miri))]
70+
fn slot_index_exhaustive() {
71+
let mut buckets = [0u32; 21];
72+
for idx in 0..=u32::MAX {
73+
buckets[SlotIndex::from_index(idx).bucket_idx] += 1;
74+
}
75+
let mut prev = None::<SlotIndex>;
76+
for idx in 0..=u32::MAX {
77+
let slot_idx = SlotIndex::from_index(idx);
78+
if let Some(p) = prev {
79+
if p.bucket_idx == slot_idx.bucket_idx {
80+
assert_eq!(p.index_in_bucket + 1, slot_idx.index_in_bucket);
81+
} else {
82+
assert_eq!(slot_idx.index_in_bucket, 0);
83+
}
84+
} else {
85+
assert_eq!(idx, 0);
86+
assert_eq!(slot_idx.index_in_bucket, 0);
87+
assert_eq!(slot_idx.bucket_idx, 0);
88+
}
89+
90+
assert_eq!(buckets[slot_idx.bucket_idx], slot_idx.entries as u32);
91+
assert_eq!(ENTRIES_BY_BUCKET[slot_idx.bucket_idx], slot_idx.entries, "{}", idx);
92+
93+
prev = Some(slot_idx);
94+
}
95+
}

‎compiler/rustc_middle/src/query/keys.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
33
use rustc_hir::def_id::{CrateNum, DefId, LOCAL_CRATE, LocalDefId, LocalModDefId, ModDefId};
44
use rustc_hir::hir_id::{HirId, OwnerId};
5+
use rustc_query_system::dep_graph::DepNodeIndex;
56
use rustc_query_system::query::{DefIdCache, DefaultCache, SingleCache, VecCache};
67
use rustc_span::symbol::{Ident, Symbol};
78
use rustc_span::{DUMMY_SP, Span};
@@ -111,7 +112,7 @@ impl<'tcx> Key for mir::interpret::LitToConstInput<'tcx> {
111112
}
112113

113114
impl Key for CrateNum {
114-
type Cache<V> = VecCache<Self, V>;
115+
type Cache<V> = VecCache<Self, V, DepNodeIndex>;
115116

116117
fn default_span(&self, _: TyCtxt<'_>) -> Span {
117118
DUMMY_SP
@@ -128,7 +129,7 @@ impl AsLocalKey for CrateNum {
128129
}
129130

130131
impl Key for OwnerId {
131-
type Cache<V> = VecCache<Self, V>;
132+
type Cache<V> = VecCache<Self, V, DepNodeIndex>;
132133

133134
fn default_span(&self, tcx: TyCtxt<'_>) -> Span {
134135
self.to_def_id().default_span(tcx)
@@ -140,7 +141,7 @@ impl Key for OwnerId {
140141
}
141142

142143
impl Key for LocalDefId {
143-
type Cache<V> = VecCache<Self, V>;
144+
type Cache<V> = VecCache<Self, V, DepNodeIndex>;
144145

145146
fn default_span(&self, tcx: TyCtxt<'_>) -> Span {
146147
self.to_def_id().default_span(tcx)

‎compiler/rustc_query_system/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
#![allow(rustc::potential_query_instability, internal_features)]
33
#![feature(assert_matches)]
44
#![feature(core_intrinsics)]
5+
#![feature(dropck_eyepatch)]
56
#![feature(hash_raw_entry)]
67
#![feature(let_chains)]
78
#![feature(min_specialization)]

‎compiler/rustc_query_system/src/query/caches.rs

Lines changed: 32 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@ use std::hash::Hash;
33

44
use rustc_data_structures::fx::FxHashMap;
55
use rustc_data_structures::sharded::{self, Sharded};
6-
use rustc_data_structures::sync::{Lock, OnceLock};
6+
use rustc_data_structures::sync::OnceLock;
7+
pub use rustc_data_structures::vec_cache::VecCache;
78
use rustc_hir::def_id::LOCAL_CRATE;
8-
use rustc_index::{Idx, IndexVec};
9+
use rustc_index::Idx;
910
use rustc_span::def_id::{DefId, DefIndex};
1011

1112
use crate::dep_graph::DepNodeIndex;
@@ -100,52 +101,10 @@ where
100101
}
101102
}
102103

103-
pub struct VecCache<K: Idx, V> {
104-
cache: Lock<IndexVec<K, Option<(V, DepNodeIndex)>>>,
105-
}
106-
107-
impl<K: Idx, V> Default for VecCache<K, V> {
108-
fn default() -> Self {
109-
VecCache { cache: Default::default() }
110-
}
111-
}
112-
113-
impl<K, V> QueryCache for VecCache<K, V>
114-
where
115-
K: Eq + Idx + Copy + Debug,
116-
V: Copy,
117-
{
118-
type Key = K;
119-
type Value = V;
120-
121-
#[inline(always)]
122-
fn lookup(&self, key: &K) -> Option<(V, DepNodeIndex)> {
123-
let lock = self.cache.lock();
124-
if let Some(Some(value)) = lock.get(*key) { Some(*value) } else { None }
125-
}
126-
127-
#[inline]
128-
fn complete(&self, key: K, value: V, index: DepNodeIndex) {
129-
let mut lock = self.cache.lock();
130-
lock.insert(key, (value, index));
131-
}
132-
133-
fn iter(&self, f: &mut dyn FnMut(&Self::Key, &Self::Value, DepNodeIndex)) {
134-
for (k, v) in self.cache.lock().iter_enumerated() {
135-
if let Some(v) = v {
136-
f(&k, &v.0, v.1);
137-
}
138-
}
139-
}
140-
}
141-
142104
pub struct DefIdCache<V> {
143105
/// Stores the local DefIds in a dense map. Local queries are much more often dense, so this is
144106
/// a win over hashing query keys at marginal memory cost (~5% at most) compared to FxHashMap.
145-
///
146-
/// The second element of the tuple is the set of keys actually present in the IndexVec, used
147-
/// for faster iteration in `iter()`.
148-
local: Lock<(IndexVec<DefIndex, Option<(V, DepNodeIndex)>>, Vec<DefIndex>)>,
107+
local: VecCache<DefIndex, V, DepNodeIndex>,
149108
foreign: DefaultCache<DefId, V>,
150109
}
151110

@@ -165,8 +124,7 @@ where
165124
#[inline(always)]
166125
fn lookup(&self, key: &DefId) -> Option<(V, DepNodeIndex)> {
167126
if key.krate == LOCAL_CRATE {
168-
let cache = self.local.lock();
169-
cache.0.get(key.index).and_then(|v| *v)
127+
self.local.lookup(&key.index)
170128
} else {
171129
self.foreign.lookup(key)
172130
}
@@ -175,27 +133,39 @@ where
175133
#[inline]
176134
fn complete(&self, key: DefId, value: V, index: DepNodeIndex) {
177135
if key.krate == LOCAL_CRATE {
178-
let mut cache = self.local.lock();
179-
let (cache, present) = &mut *cache;
180-
let slot = cache.ensure_contains_elem(key.index, Default::default);
181-
if slot.is_none() {
182-
// FIXME: Only store the present set when running in incremental mode. `iter` is not
183-
// used outside of saving caches to disk and self-profile.
184-
present.push(key.index);
185-
}
186-
*slot = Some((value, index));
136+
self.local.complete(key.index, value, index)
187137
} else {
188138
self.foreign.complete(key, value, index)
189139
}
190140
}
191141

192142
fn iter(&self, f: &mut dyn FnMut(&Self::Key, &Self::Value, DepNodeIndex)) {
193-
let guard = self.local.lock();
194-
let (cache, present) = &*guard;
195-
for &idx in present.iter() {
196-
let value = cache[idx].unwrap();
197-
f(&DefId { krate: LOCAL_CRATE, index: idx }, &value.0, value.1);
198-
}
143+
self.local.iter(&mut |key, value, index| {
144+
f(&DefId { krate: LOCAL_CRATE, index: *key }, value, index);
145+
});
199146
self.foreign.iter(f);
200147
}
201148
}
149+
150+
impl<K, V> QueryCache for VecCache<K, V, DepNodeIndex>
151+
where
152+
K: Idx + Eq + Hash + Copy + Debug,
153+
V: Copy,
154+
{
155+
type Key = K;
156+
type Value = V;
157+
158+
#[inline(always)]
159+
fn lookup(&self, key: &K) -> Option<(V, DepNodeIndex)> {
160+
self.lookup(key)
161+
}
162+
163+
#[inline]
164+
fn complete(&self, key: K, value: V, index: DepNodeIndex) {
165+
self.complete(key, value, index)
166+
}
167+
168+
fn iter(&self, f: &mut dyn FnMut(&Self::Key, &Self::Value, DepNodeIndex)) {
169+
self.iter(f)
170+
}
171+
}

0 commit comments

Comments
 (0)
Please sign in to comment.