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 ad08842

Browse files
committedFeb 2, 2025
Auto merge of #136401 - Mark-Simulacrum:lockfree-as-str, r=<try>
Lazy-page Symbol interner This is a simple and only semi-correct impl that works well only on 64-bit platforms where we can lazily allocate zeroed pages (i.e., not actually use up memory for zeroed pages), meaning that we can grab a 4GB chunk of memory for all interned strings and then just offset allocate into that. This already fixes unsoundness in the Symbol::as_str by leaking that 4gb memory chunk, but could also be faster (TBD). A rewrite supporting ~any platform should be pretty straightforward by sharding the allocation and manually lazily allocating it in chunks. r? `@ghost` -- this impl can't land due to being non-workable on Windows, opening for initial perf run
2 parents e1f0920 + 79a6cff commit ad08842

File tree

7 files changed

+137
-51
lines changed

7 files changed

+137
-51
lines changed
 

‎Cargo.lock

+4
Original file line numberDiff line numberDiff line change
@@ -1533,6 +1533,8 @@ version = "0.15.2"
15331533
source = "registry+https://github.com/rust-lang/crates.io-index"
15341534
checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289"
15351535
dependencies = [
1536+
"allocator-api2",
1537+
"equivalent",
15361538
"foldhash",
15371539
"serde",
15381540
]
@@ -3614,6 +3616,7 @@ dependencies = [
36143616
"either",
36153617
"elsa",
36163618
"ena",
3619+
"hashbrown 0.15.2",
36173620
"indexmap",
36183621
"jobserver",
36193622
"libc",
@@ -4510,6 +4513,7 @@ version = "0.0.0"
45104513
dependencies = [
45114514
"blake3",
45124515
"derive-where",
4516+
"hashbrown 0.15.2",
45134517
"indexmap",
45144518
"itoa",
45154519
"md-5",

‎compiler/rustc_data_structures/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ bitflags = "2.4.1"
1010
either = "1.0"
1111
elsa = "=1.7.1"
1212
ena = "0.14.3"
13+
hashbrown = "0.15.2"
1314
indexmap = "2.4.0"
1415
jobserver_crate = { version = "0.1.28", package = "jobserver" }
1516
measureme = "11"

‎compiler/rustc_data_structures/src/marker.rs

+2
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ impl_dyn_send!(
6868
[std::sync::LazyLock<T, F> where T: DynSend, F: DynSend]
6969
[std::collections::HashSet<K, S> where K: DynSend, S: DynSend]
7070
[std::collections::HashMap<K, V, S> where K: DynSend, V: DynSend, S: DynSend]
71+
[hashbrown::HashTable<T> where T: DynSend]
7172
[std::collections::BTreeMap<K, V, A> where K: DynSend, V: DynSend, A: std::alloc::Allocator + Clone + DynSend]
7273
[Vec<T, A> where T: DynSend, A: std::alloc::Allocator + DynSend]
7374
[Box<T, A> where T: ?Sized + DynSend, A: std::alloc::Allocator + DynSend]
@@ -142,6 +143,7 @@ impl_dyn_sync!(
142143
[std::sync::LazyLock<T, F> where T: DynSend + DynSync, F: DynSend]
143144
[std::collections::HashSet<K, S> where K: DynSync, S: DynSync]
144145
[std::collections::HashMap<K, V, S> where K: DynSync, V: DynSync, S: DynSync]
146+
[hashbrown::HashTable<T> where T: DynSync]
145147
[std::collections::BTreeMap<K, V, A> where K: DynSync, V: DynSync, A: std::alloc::Allocator + Clone + DynSync]
146148
[Vec<T, A> where T: DynSync, A: std::alloc::Allocator + DynSync]
147149
[Box<T, A> where T: ?Sized + DynSync, A: std::alloc::Allocator + DynSync]

‎compiler/rustc_span/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ edition = "2021"
77
# tidy-alphabetical-start
88
blake3 = "1.5.2"
99
derive-where = "1.2.7"
10+
hashbrown = "0.15.2"
1011
indexmap = { version = "2.0.0" }
1112
itoa = "1.0"
1213
md5 = { package = "md-5", version = "0.10.0" }

‎compiler/rustc_span/src/lib.rs

+2
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@
3131
#![feature(round_char_boundary)]
3232
#![feature(rustc_attrs)]
3333
#![feature(rustdoc_internals)]
34+
#![feature(str_from_raw_parts)]
35+
#![feature(strict_provenance_atomic_ptr)]
3436
#![warn(unreachable_pub)]
3537
// tidy-alphabetical-end
3638

‎compiler/rustc_span/src/symbol.rs

+120-46
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,13 @@
22
//! allows bidirectional lookup; i.e., given a value, one can easily find the
33
//! type, and vice versa.
44
5-
use std::hash::{Hash, Hasher};
5+
use std::alloc::Layout;
6+
use std::hash::{BuildHasher, BuildHasherDefault, Hash, Hasher};
7+
use std::sync::Mutex;
8+
use std::sync::atomic::{AtomicPtr, Ordering};
69
use std::{fmt, str};
710

8-
use rustc_arena::DroplessArena;
9-
use rustc_data_structures::fx::FxIndexSet;
11+
use rustc_data_structures::fx::FxHasher;
1012
use rustc_data_structures::stable_hasher::{
1113
HashStable, StableCompare, StableHasher, ToStableHashKey,
1214
};
@@ -2460,18 +2462,9 @@ impl Symbol {
24602462
with_session_globals(|session_globals| session_globals.symbol_interner.intern(string))
24612463
}
24622464

2463-
/// Access the underlying string. This is a slowish operation because it
2464-
/// requires locking the symbol interner.
2465-
///
2466-
/// Note that the lifetime of the return value is a lie. It's not the same
2467-
/// as `&self`, but actually tied to the lifetime of the underlying
2468-
/// interner. Interners are long-lived, and there are very few of them, and
2469-
/// this function is typically used for short-lived things, so in practice
2470-
/// it works out ok.
2465+
/// Access the underlying string.
24712466
pub fn as_str(&self) -> &str {
2472-
with_session_globals(|session_globals| unsafe {
2473-
std::mem::transmute::<&str, &str>(session_globals.symbol_interner.get(*self))
2474-
})
2467+
with_session_globals(|session_globals| session_globals.symbol_interner.get(*self))
24752468
}
24762469

24772470
pub fn as_u32(self) -> u32 {
@@ -2526,53 +2519,134 @@ impl StableCompare for Symbol {
25262519
}
25272520
}
25282521

2529-
pub(crate) struct Interner(Lock<InternerInner>);
2522+
// This is never de-initialized and stores interned &str in static storage.
2523+
// Each str is stored length-prefixed (u32), and we allow for random-access indexing with a u32
2524+
// index by direct lookup in the arena. Indices <2^16 are stored in a separate structure (they are
2525+
// pre-allocated at dense addresses so we can't use the same lockless O(1) hack for them).
2526+
static GLOBAL_ARENA: std::sync::LazyLock<StringArena> =
2527+
std::sync::LazyLock::new(|| StringArena::new());
2528+
2529+
struct StringArena {
2530+
base: *mut u8,
2531+
end: *mut u8,
2532+
write_at: AtomicPtr<u8>,
2533+
// this guards writes to `write_at`, but not reads, which proceed lock-free. write_at is only moved
2534+
// forward so this ends up being safe.
2535+
writer: std::sync::Mutex<()>,
2536+
}
2537+
2538+
unsafe impl Sync for StringArena {}
2539+
unsafe impl Send for StringArena {}
2540+
2541+
impl StringArena {
2542+
fn new() -> Self {
2543+
unsafe {
2544+
let layout =
2545+
Layout::from_size_align(u32::MAX as usize, std::mem::align_of::<u32>()).unwrap();
2546+
let allocation = std::alloc::alloc_zeroed(layout);
2547+
if allocation.is_null() {
2548+
std::alloc::handle_alloc_error(layout)
2549+
}
2550+
StringArena {
2551+
base: allocation,
2552+
end: allocation.add(layout.size()),
2553+
// Reserve 2^16 u32 indices -- these will be used for pre-filled interning where we
2554+
// have a dense SymbolIndex space. We could make this exact but it doesn't really
2555+
// matter for this initial test anyway.
2556+
write_at: AtomicPtr::new(allocation.add(u16::MAX as usize)),
2557+
writer: Mutex::new(()),
2558+
}
2559+
}
2560+
}
2561+
2562+
fn alloc(&self, s: &str) -> u32 {
2563+
unsafe {
2564+
let _guard = self.writer.lock().unwrap();
2565+
// Allocate a chunk of the region, and fill it with the &str's length and bytes.
2566+
let dst = self.write_at.load(Ordering::Acquire);
2567+
// Assert we're in-bounds.
2568+
assert!(
2569+
dst.addr().checked_add(4).unwrap().checked_add(s.len()).unwrap() < self.end.addr()
2570+
);
2571+
dst.cast::<u32>().write_unaligned(s.len().try_into().unwrap());
2572+
dst.add(4).copy_from_nonoverlapping(s.as_ptr(), s.len());
2573+
2574+
// Semantically this releases the memory for readers.
2575+
self.write_at.store(dst.add(4 + s.len()), Ordering::Release);
2576+
2577+
dst.byte_offset_from(self.base).try_into().unwrap()
2578+
}
2579+
}
2580+
2581+
fn get(&self, idx: u32) -> &str {
2582+
// SAFETY: `write_at` is only updated after writing to a given region, so we never have
2583+
// concurrent writes to this memory. It's initialized at allocation (alloc_zeroed) and we
2584+
// only write initialized bytes to it, so there's also never any uninit bytes in the region.
2585+
let region = unsafe {
2586+
let end = self.write_at.load(Ordering::Acquire);
2587+
std::slice::from_raw_parts(self.base, end.offset_from(self.base) as usize)
2588+
};
2589+
2590+
let len = u32::from_ne_bytes(region[idx as usize..idx as usize + 4].try_into().unwrap());
2591+
let data = &region[idx as usize + 4..][..len as usize];
2592+
2593+
// FIXME: hopefully we got passed an accurate index.
2594+
unsafe { std::str::from_utf8_unchecked(data) }
2595+
}
2596+
}
2597+
2598+
pub(crate) struct Interner(&'static [&'static str], Lock<InternerInner>);
25302599

2531-
// The `&'static str`s in this type actually point into the arena.
2532-
//
2533-
// This type is private to prevent accidentally constructing more than one
2534-
// `Interner` on the same thread, which makes it easy to mix up `Symbol`s
2535-
// between `Interner`s.
25362600
struct InternerInner {
2537-
arena: DroplessArena,
2538-
strings: FxIndexSet<&'static str>,
2601+
strings: hashbrown::HashTable<Symbol>,
25392602
}
25402603

25412604
impl Interner {
2542-
fn prefill(init: &[&'static str]) -> Self {
2543-
Interner(Lock::new(InternerInner {
2544-
arena: Default::default(),
2545-
strings: init.iter().copied().collect(),
2546-
}))
2605+
fn prefill(init: &'static [&'static str]) -> Self {
2606+
assert!(init.len() < u16::MAX as usize);
2607+
let mut strings = hashbrown::HashTable::new();
2608+
2609+
for (idx, s) in init.iter().copied().enumerate() {
2610+
let mut hasher = FxHasher::default();
2611+
s.hash(&mut hasher);
2612+
let hash = hasher.finish();
2613+
strings.insert_unique(hash, Symbol::new(idx as u32), |val| {
2614+
// has to be from `init` because we haven't yet inserted anything except those.
2615+
BuildHasherDefault::<FxHasher>::default().hash_one(init[val.0.index()])
2616+
});
2617+
}
2618+
2619+
Interner(init, Lock::new(InternerInner { strings }))
25472620
}
25482621

25492622
#[inline]
25502623
fn intern(&self, string: &str) -> Symbol {
2551-
let mut inner = self.0.lock();
2552-
if let Some(idx) = inner.strings.get_index_of(string) {
2553-
return Symbol::new(idx as u32);
2624+
let hash = BuildHasherDefault::<FxHasher>::default().hash_one(string);
2625+
let mut inner = self.1.lock();
2626+
match inner.strings.find_entry(hash, |v| self.get(*v) == string) {
2627+
Ok(e) => return *e.get(),
2628+
Err(e) => {
2629+
let idx = GLOBAL_ARENA.alloc(string);
2630+
let res = Symbol::new(idx as u32);
2631+
2632+
e.into_table().insert_unique(hash, res, |val| {
2633+
BuildHasherDefault::<FxHasher>::default().hash_one(self.get(*val))
2634+
});
2635+
2636+
res
2637+
}
25542638
}
2555-
2556-
let string: &str = inner.arena.alloc_str(string);
2557-
2558-
// SAFETY: we can extend the arena allocation to `'static` because we
2559-
// only access these while the arena is still alive.
2560-
let string: &'static str = unsafe { &*(string as *const str) };
2561-
2562-
// This second hash table lookup can be avoided by using `RawEntryMut`,
2563-
// but this code path isn't hot enough for it to be worth it. See
2564-
// #91445 for details.
2565-
let (idx, is_new) = inner.strings.insert_full(string);
2566-
debug_assert!(is_new); // due to the get_index_of check above
2567-
2568-
Symbol::new(idx as u32)
25692639
}
25702640

25712641
/// Get the symbol as a string.
25722642
///
25732643
/// [`Symbol::as_str()`] should be used in preference to this function.
2574-
fn get(&self, symbol: Symbol) -> &str {
2575-
self.0.lock().strings.get_index(symbol.0.as_usize()).unwrap()
2644+
fn get(&self, symbol: Symbol) -> &'static str {
2645+
if symbol.0.index() < u16::MAX as usize {
2646+
self.0[symbol.0.index()]
2647+
} else {
2648+
GLOBAL_ARENA.get(symbol.0.as_u32())
2649+
}
25762650
}
25772651
}
25782652

‎compiler/rustc_span/src/symbol/tests.rs

+7-5
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,17 @@ use crate::create_default_session_globals_then;
44
#[test]
55
fn interner_tests() {
66
let i = Interner::prefill(&[]);
7+
let dog = i.intern("dog");
78
// first one is zero:
8-
assert_eq!(i.intern("dog"), Symbol::new(0));
9+
assert_eq!(i.intern("dog"), dog);
910
// re-use gets the same entry:
10-
assert_eq!(i.intern("dog"), Symbol::new(0));
11+
assert_eq!(i.intern("dog"), dog);
1112
// different string gets a different #:
12-
assert_eq!(i.intern("cat"), Symbol::new(1));
13-
assert_eq!(i.intern("cat"), Symbol::new(1));
13+
let cat = i.intern("cat");
14+
assert_eq!(i.intern("cat"), cat);
15+
assert_eq!(i.intern("cat"), cat);
1416
// dog is still at zero
15-
assert_eq!(i.intern("dog"), Symbol::new(0));
17+
assert_eq!(i.intern("dog"), dog);
1618
}
1719

1820
#[test]

0 commit comments

Comments
 (0)
Failed to load comments.