Skip to content

Commit 0c96a92

Browse files
committed
Add Freeze type and use it to store Definitions
1 parent 9dc11a1 commit 0c96a92

File tree

6 files changed

+122
-15
lines changed

6 files changed

+122
-15
lines changed

compiler/rustc_data_structures/src/sync.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,9 @@ pub use vec::{AppendOnlyIndexVec, AppendOnlyVec};
6161

6262
mod vec;
6363

64+
mod freeze;
65+
pub use freeze::{Freeze, FreezeReadGuard, FreezeWriteGuard};
66+
6467
mod mode {
6568
use super::Ordering;
6669
use std::sync::atomic::AtomicU8;
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
use crate::sync::{AtomicBool, Lock, LockGuard};
2+
#[cfg(parallel_compiler)]
3+
use crate::sync::{DynSend, DynSync};
4+
use std::{
5+
cell::UnsafeCell,
6+
ops::{Deref, DerefMut},
7+
sync::atomic::Ordering,
8+
};
9+
10+
/// A type which allows mutation using a lock until
11+
/// the value is frozen and can be accessed lock-free.
12+
#[derive(Default)]
13+
pub struct Freeze<T> {
14+
data: UnsafeCell<T>,
15+
frozen: AtomicBool,
16+
lock: Lock<()>,
17+
}
18+
19+
#[cfg(parallel_compiler)]
20+
unsafe impl<T: DynSync + DynSend> DynSync for Freeze<T> {}
21+
22+
impl<T> Freeze<T> {
23+
#[inline]
24+
pub fn new(value: T) -> Self {
25+
Self { data: UnsafeCell::new(value), frozen: AtomicBool::new(false), lock: Lock::new(()) }
26+
}
27+
28+
#[inline]
29+
pub fn read(&self) -> FreezeReadGuard<'_, T> {
30+
FreezeReadGuard {
31+
_lock_guard: if self.frozen.load(Ordering::Acquire) {
32+
None
33+
} else {
34+
Some(self.lock.lock())
35+
},
36+
// SAFETY: If this is not frozen, `_lock_guard` holds the lock to the `UnsafeCell` so
37+
// this has shared access until the `FreezeReadGuard` is dropped. If this is frozen,
38+
// the data cannot be modified and shared access is sound.
39+
data: unsafe { &*self.data.get() },
40+
}
41+
}
42+
43+
#[inline]
44+
#[track_caller]
45+
pub fn write(&self) -> FreezeWriteGuard<'_, T> {
46+
let _lock_guard = self.lock.lock();
47+
assert!(!self.frozen.load(Ordering::Relaxed), "still mutable");
48+
FreezeWriteGuard {
49+
_lock_guard,
50+
// SAFETY: `_lock_guard` holds the lock to the `UnsafeCell` so this has mutable access
51+
// until the `FreezeWriteGuard` is dropped.
52+
data: unsafe { &mut *self.data.get() },
53+
}
54+
}
55+
56+
#[inline]
57+
pub fn freeze(&self) -> &T {
58+
if !self.frozen.load(Ordering::Acquire) {
59+
// Get the lock to ensure no concurrent writes.
60+
let _lock = self.lock.lock();
61+
self.frozen.store(true, Ordering::Release);
62+
}
63+
64+
// SAFETY: This is frozen so the data cannot be modified and shared access is sound.
65+
unsafe { &*self.data.get() }
66+
}
67+
}
68+
69+
/// A guard holding shared access to a `Freeze` which is in a locked state or frozen.
70+
#[must_use = "if unused the Freeze may immediately unlock"]
71+
pub struct FreezeReadGuard<'a, T> {
72+
_lock_guard: Option<LockGuard<'a, ()>>,
73+
data: &'a T,
74+
}
75+
76+
impl<'a, T: 'a> Deref for FreezeReadGuard<'a, T> {
77+
type Target = T;
78+
#[inline]
79+
fn deref(&self) -> &T {
80+
self.data
81+
}
82+
}
83+
84+
/// A guard holding mutable access to a `Freeze` which is in a locked state or frozen.
85+
#[must_use = "if unused the Freeze may immediately unlock"]
86+
pub struct FreezeWriteGuard<'a, T> {
87+
_lock_guard: LockGuard<'a, ()>,
88+
data: &'a mut T,
89+
}
90+
91+
impl<'a, T: 'a> Deref for FreezeWriteGuard<'a, T> {
92+
type Target = T;
93+
#[inline]
94+
fn deref(&self) -> &T {
95+
self.data
96+
}
97+
}
98+
99+
impl<'a, T: 'a> DerefMut for FreezeWriteGuard<'a, T> {
100+
#[inline]
101+
fn deref_mut(&mut self) -> &mut T {
102+
self.data
103+
}
104+
}

compiler/rustc_interface/src/queries.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use rustc_codegen_ssa::traits::CodegenBackend;
77
use rustc_codegen_ssa::CodegenResults;
88
use rustc_data_structures::steal::Steal;
99
use rustc_data_structures::svh::Svh;
10-
use rustc_data_structures::sync::{AppendOnlyIndexVec, Lrc, OnceLock, RwLock, WorkerLocal};
10+
use rustc_data_structures::sync::{AppendOnlyIndexVec, Freeze, Lrc, OnceLock, RwLock, WorkerLocal};
1111
use rustc_hir::def_id::{StableCrateId, CRATE_DEF_ID, LOCAL_CRATE};
1212
use rustc_hir::definitions::Definitions;
1313
use rustc_incremental::DepGraphFuture;
@@ -197,7 +197,7 @@ impl<'tcx> Queries<'tcx> {
197197
self.codegen_backend().metadata_loader(),
198198
stable_crate_id,
199199
)) as _);
200-
let definitions = RwLock::new(Definitions::new(stable_crate_id));
200+
let definitions = Freeze::new(Definitions::new(stable_crate_id));
201201
let source_span = AppendOnlyIndexVec::new();
202202
let _id = source_span.push(krate.spans.inner_span);
203203
debug_assert_eq!(_id, CRATE_DEF_ID);

compiler/rustc_middle/src/hir/map/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1207,7 +1207,7 @@ pub(super) fn crate_hash(tcx: TyCtxt<'_>, _: LocalCrate) -> Svh {
12071207
source_file_names.hash_stable(&mut hcx, &mut stable_hasher);
12081208
debugger_visualizers.hash_stable(&mut hcx, &mut stable_hasher);
12091209
if tcx.sess.opts.incremental_relative_spans() {
1210-
let definitions = tcx.definitions_untracked();
1210+
let definitions = tcx.untracked().definitions.freeze();
12111211
let mut owner_spans: Vec<_> = krate
12121212
.owners
12131213
.iter_enumerated()

compiler/rustc_middle/src/ty/context.rs

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,9 @@ use rustc_data_structures::profiling::SelfProfilerRef;
3939
use rustc_data_structures::sharded::{IntoPointer, ShardedHashMap};
4040
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
4141
use rustc_data_structures::steal::Steal;
42-
use rustc_data_structures::sync::{self, Lock, Lrc, MappedReadGuard, ReadGuard, WorkerLocal};
42+
use rustc_data_structures::sync::{
43+
self, FreezeReadGuard, Lock, Lrc, MappedReadGuard, ReadGuard, WorkerLocal,
44+
};
4345
use rustc_data_structures::unord::UnordSet;
4446
use rustc_errors::{
4547
DecorateLint, DiagnosticBuilder, DiagnosticMessage, ErrorGuaranteed, MultiSpan,
@@ -964,8 +966,8 @@ impl<'tcx> TyCtxt<'tcx> {
964966
i += 1;
965967
}
966968

967-
// Leak a read lock once we finish iterating on definitions, to prevent adding new ones.
968-
definitions.leak();
969+
// Freeze definitions once we finish iterating on them, to prevent adding new ones.
970+
definitions.freeze();
969971
})
970972
}
971973

@@ -974,10 +976,9 @@ impl<'tcx> TyCtxt<'tcx> {
974976
// definitions change.
975977
self.dep_graph.read_index(DepNodeIndex::FOREVER_RED_NODE);
976978

977-
// Leak a read lock once we start iterating on definitions, to prevent adding new ones
979+
// Freeze definitions once we start iterating on them, to prevent adding new ones
978980
// while iterating. If some query needs to add definitions, it should be `ensure`d above.
979-
let definitions = self.untracked.definitions.leak();
980-
definitions.def_path_table()
981+
self.untracked.definitions.freeze().def_path_table()
981982
}
982983

983984
pub fn def_path_hash_to_def_index_map(
@@ -986,10 +987,9 @@ impl<'tcx> TyCtxt<'tcx> {
986987
// Create a dependency to the crate to be sure we re-execute this when the amount of
987988
// definitions change.
988989
self.ensure().hir_crate(());
989-
// Leak a read lock once we start iterating on definitions, to prevent adding new ones
990+
// Freeze definitions once we start iterating on them, to prevent adding new ones
990991
// while iterating. If some query needs to add definitions, it should be `ensure`d above.
991-
let definitions = self.untracked.definitions.leak();
992-
definitions.def_path_hash_to_def_index_map()
992+
self.untracked.definitions.freeze().def_path_hash_to_def_index_map()
993993
}
994994

995995
/// Note that this is *untracked* and should only be used within the query
@@ -1006,7 +1006,7 @@ impl<'tcx> TyCtxt<'tcx> {
10061006
/// Note that this is *untracked* and should only be used within the query
10071007
/// system if the result is otherwise tracked through queries
10081008
#[inline]
1009-
pub fn definitions_untracked(self) -> ReadGuard<'tcx, Definitions> {
1009+
pub fn definitions_untracked(self) -> FreezeReadGuard<'tcx, Definitions> {
10101010
self.untracked.definitions.read()
10111011
}
10121012

compiler/rustc_session/src/cstore.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use crate::utils::NativeLibKind;
77
use crate::Session;
88
use rustc_ast as ast;
99
use rustc_data_structures::owned_slice::OwnedSlice;
10-
use rustc_data_structures::sync::{self, AppendOnlyIndexVec, RwLock};
10+
use rustc_data_structures::sync::{self, AppendOnlyIndexVec, Freeze, RwLock};
1111
use rustc_hir::def_id::{CrateNum, DefId, LocalDefId, StableCrateId, LOCAL_CRATE};
1212
use rustc_hir::definitions::{DefKey, DefPath, DefPathHash, Definitions};
1313
use rustc_span::hygiene::{ExpnHash, ExpnId};
@@ -261,5 +261,5 @@ pub struct Untracked {
261261
pub cstore: RwLock<Box<CrateStoreDyn>>,
262262
/// Reference span for definitions.
263263
pub source_span: AppendOnlyIndexVec<LocalDefId, Span>,
264-
pub definitions: RwLock<Definitions>,
264+
pub definitions: Freeze<Definitions>,
265265
}

0 commit comments

Comments
 (0)