1 //! This module defines types which are thread safe if cfg!(parallel_compiler) is true.
3 //! `Lrc` is an alias of `Arc` if cfg!(parallel_compiler) is true, `Rc` otherwise.
6 //! It internally uses `parking_lot::Mutex` if cfg!(parallel_compiler) is true,
7 //! `RefCell` otherwise.
9 //! `RwLock` is a read-write lock.
10 //! It internally uses `parking_lot::RwLock` if cfg!(parallel_compiler) is true,
11 //! `RefCell` otherwise.
13 //! `MTLock` is a mutex which disappears if cfg!(parallel_compiler) is false.
15 //! `MTRef` is an immutable reference if cfg!(parallel_compiler), and a mutable reference otherwise.
17 //! `rustc_erase_owner!` erases a OwningRef owner into Erased or Erased + Send + Sync
18 //! depending on the value of cfg!(parallel_compiler).
20 use crate::owning_ref::{Erased, OwningRef};
21 use std::collections::HashMap;
22 use std::hash::{BuildHasher, Hash};
23 use std::ops::{Deref, DerefMut};
25 pub use std::sync::atomic::Ordering;
26 pub use std::sync::atomic::Ordering::SeqCst;
29 if #[cfg(not(parallel_compiler))] {
30 pub auto trait Send {}
31 pub auto trait Sync {}
33 impl<T: ?Sized> Send for T {}
34 impl<T: ?Sized> Sync for T {}
37 macro_rules! rustc_erase_owner {
44 use std::panic::{resume_unwind, catch_unwind, AssertUnwindSafe};
46 /// This is a single threaded variant of AtomicCell provided by crossbeam.
47 /// Unlike `Atomic` this is intended for all `Copy` types,
48 /// but it lacks the explicit ordering arguments.
50 pub struct AtomicCell<T: Copy>(Cell<T>);
52 impl<T: Copy> AtomicCell<T> {
54 pub fn new(v: T) -> Self {
55 AtomicCell(Cell::new(v))
59 pub fn get_mut(&mut self) -> &mut T {
64 impl<T: Copy> AtomicCell<T> {
66 pub fn into_inner(self) -> T {
71 pub fn load(&self) -> T {
76 pub fn store(&self, val: T) {
81 pub fn swap(&self, val: T) -> T {
86 /// This is a single threaded variant of `AtomicU64`, `AtomicUsize`, etc.
87 /// It differs from `AtomicCell` in that it has explicit ordering arguments
88 /// and is only intended for use with the native atomic types.
89 /// You should use this type through the `AtomicU64`, `AtomicUsize`, etc, type aliases
90 /// as it's not intended to be used separately.
92 pub struct Atomic<T: Copy>(Cell<T>);
94 impl<T: Copy> Atomic<T> {
96 pub fn new(v: T) -> Self {
101 impl<T: Copy> Atomic<T> {
103 pub fn into_inner(self) -> T {
108 pub fn load(&self, _: Ordering) -> T {
113 pub fn store(&self, val: T, _: Ordering) {
118 pub fn swap(&self, val: T, _: Ordering) -> T {
123 impl<T: Copy + PartialEq> Atomic<T> {
125 pub fn compare_exchange(&self,
131 let read = self.0.get();
141 impl<T: Add<Output=T> + Copy> Atomic<T> {
143 pub fn fetch_add(&self, val: T, _: Ordering) -> T {
144 let old = self.0.get();
145 self.0.set(old + val);
150 pub type AtomicUsize = Atomic<usize>;
151 pub type AtomicBool = Atomic<bool>;
152 pub type AtomicU32 = Atomic<u32>;
153 pub type AtomicU64 = Atomic<u64>;
155 pub fn join<A, B, RA, RB>(oper_a: A, oper_b: B) -> (RA, RB)
156 where A: FnOnce() -> RA,
162 pub struct SerialScope;
165 pub fn spawn<F>(&self, f: F)
166 where F: FnOnce(&SerialScope)
172 pub fn scope<F, R>(f: F) -> R
173 where F: FnOnce(&SerialScope) -> R
179 macro_rules! parallel {
180 ($($blocks:tt),*) => {
181 // We catch panics here ensuring that all the blocks execute.
182 // This makes behavior consistent with the parallel compiler.
183 let mut panic = None;
185 if let Err(p) = ::std::panic::catch_unwind(
186 ::std::panic::AssertUnwindSafe(|| $blocks)
193 if let Some(panic) = panic {
194 ::std::panic::resume_unwind(panic);
199 pub use std::iter::Iterator as ParallelIterator;
201 pub fn par_iter<T: IntoIterator>(t: T) -> T::IntoIter {
205 pub fn par_for_each_in<T: IntoIterator>(t: T, for_each: impl Fn(T::Item) + Sync + Send) {
206 // We catch panics here ensuring that all the loop iterations execute.
207 // This makes behavior consistent with the parallel compiler.
208 let mut panic = None;
209 t.into_iter().for_each(|i| {
210 if let Err(p) = catch_unwind(AssertUnwindSafe(|| for_each(i))) {
216 if let Some(panic) = panic {
217 resume_unwind(panic);
221 pub type MetadataRef = OwningRef<Box<dyn Erased>, [u8]>;
223 pub use std::rc::Rc as Lrc;
224 pub use std::rc::Weak as Weak;
225 pub use std::cell::Ref as ReadGuard;
226 pub use std::cell::Ref as MappedReadGuard;
227 pub use std::cell::RefMut as WriteGuard;
228 pub use std::cell::RefMut as MappedWriteGuard;
229 pub use std::cell::RefMut as LockGuard;
230 pub use std::cell::RefMut as MappedLockGuard;
232 pub use std::lazy::OnceCell;
234 use std::cell::RefCell as InnerRwLock;
235 use std::cell::RefCell as InnerLock;
240 pub struct WorkerLocal<T>(OneThread<T>);
242 impl<T> WorkerLocal<T> {
243 /// Creates a new worker local where the `initial` closure computes the
244 /// value this worker local should take for each thread in the thread pool.
246 pub fn new<F: FnMut(usize) -> T>(mut f: F) -> WorkerLocal<T> {
247 WorkerLocal(OneThread::new(f(0)))
250 /// Returns the worker-local value for each thread
252 pub fn into_inner(self) -> Vec<T> {
253 vec![OneThread::into_inner(self.0)]
257 impl<T> Deref for WorkerLocal<T> {
261 fn deref(&self) -> &T {
266 pub type MTRef<'a, T> = &'a mut T;
268 #[derive(Debug, Default)]
269 pub struct MTLock<T>(T);
273 pub fn new(inner: T) -> Self {
278 pub fn into_inner(self) -> T {
283 pub fn get_mut(&mut self) -> &mut T {
288 pub fn lock(&self) -> &T {
293 pub fn lock_mut(&mut self) -> &mut T {
298 // FIXME: Probably a bad idea (in the threaded case)
299 impl<T: Clone> Clone for MTLock<T> {
301 fn clone(&self) -> Self {
302 MTLock(self.0.clone())
306 pub use std::marker::Send as Send;
307 pub use std::marker::Sync as Sync;
309 pub use parking_lot::RwLockReadGuard as ReadGuard;
310 pub use parking_lot::MappedRwLockReadGuard as MappedReadGuard;
311 pub use parking_lot::RwLockWriteGuard as WriteGuard;
312 pub use parking_lot::MappedRwLockWriteGuard as MappedWriteGuard;
314 pub use parking_lot::MutexGuard as LockGuard;
315 pub use parking_lot::MappedMutexGuard as MappedLockGuard;
317 pub use std::lazy::SyncOnceCell as OnceCell;
319 pub use std::sync::atomic::{AtomicBool, AtomicUsize, AtomicU32, AtomicU64};
321 pub use crossbeam_utils::atomic::AtomicCell;
323 pub use std::sync::Arc as Lrc;
324 pub use std::sync::Weak as Weak;
326 pub type MTRef<'a, T> = &'a T;
328 #[derive(Debug, Default)]
329 pub struct MTLock<T>(Lock<T>);
333 pub fn new(inner: T) -> Self {
334 MTLock(Lock::new(inner))
338 pub fn into_inner(self) -> T {
343 pub fn get_mut(&mut self) -> &mut T {
348 pub fn lock(&self) -> LockGuard<'_, T> {
353 pub fn lock_mut(&self) -> LockGuard<'_, T> {
358 use parking_lot::Mutex as InnerLock;
359 use parking_lot::RwLock as InnerRwLock;
362 pub use rayon::{join, scope};
364 /// Runs a list of blocks in parallel. The first block is executed immediately on
365 /// the current thread. Use that for the longest running block.
367 macro_rules! parallel {
368 (impl $fblock:tt [$($c:tt,)*] [$block:tt $(, $rest:tt)*]) => {
369 parallel!(impl $fblock [$block, $($c,)*] [$($rest),*])
371 (impl $fblock:tt [$($blocks:tt,)*] []) => {
372 ::rustc_data_structures::sync::scope(|s| {
374 s.spawn(|_| $blocks);
379 ($fblock:tt, $($blocks:tt),*) => {
380 // Reverse the order of the later blocks since Rayon executes them in reverse order
381 // when using a single thread. This ensures the execution order matches that
382 // of a single threaded rustc
383 parallel!(impl $fblock [] [$($blocks),*]);
387 pub use rayon_core::WorkerLocal;
389 pub use rayon::iter::ParallelIterator;
390 use rayon::iter::IntoParallelIterator;
392 pub fn par_iter<T: IntoParallelIterator>(t: T) -> T::Iter {
396 pub fn par_for_each_in<T: IntoParallelIterator>(
398 for_each: impl Fn(T::Item) + Sync + Send,
400 t.into_par_iter().for_each(for_each)
403 pub type MetadataRef = OwningRef<Box<dyn Erased + Send + Sync>, [u8]>;
405 /// This makes locks panic if they are already held.
406 /// It is only useful when you are running in a single thread
407 const ERROR_CHECKING: bool = false;
410 macro_rules! rustc_erase_owner {
413 ::rustc_data_structures::sync::assert_send_val(&v);
414 v.erase_send_sync_owner()
420 pub fn assert_sync<T: ?Sized + Sync>() {}
421 pub fn assert_send<T: ?Sized + Send>() {}
422 pub fn assert_send_val<T: ?Sized + Send>(_t: &T) {}
423 pub fn assert_send_sync_val<T: ?Sized + Sync + Send>(_t: &T) {}
425 pub trait HashMapExt<K, V> {
426 /// Same as HashMap::insert, but it may panic if there's already an
427 /// entry for `key` with a value not equal to `value`
428 fn insert_same(&mut self, key: K, value: V);
431 impl<K: Eq + Hash, V: Eq, S: BuildHasher> HashMapExt<K, V> for HashMap<K, V, S> {
432 fn insert_same(&mut self, key: K, value: V) {
433 self.entry(key).and_modify(|old| assert!(*old == value)).or_insert(value);
438 pub struct Lock<T>(InnerLock<T>);
442 pub fn new(inner: T) -> Self {
443 Lock(InnerLock::new(inner))
447 pub fn into_inner(self) -> T {
452 pub fn get_mut(&mut self) -> &mut T {
456 #[cfg(parallel_compiler)]
458 pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
462 #[cfg(not(parallel_compiler))]
464 pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
465 self.0.try_borrow_mut().ok()
468 #[cfg(parallel_compiler)]
470 pub fn lock(&self) -> LockGuard<'_, T> {
472 self.0.try_lock().expect("lock was already held")
478 #[cfg(not(parallel_compiler))]
480 pub fn lock(&self) -> LockGuard<'_, T> {
485 pub fn with_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
490 pub fn borrow(&self) -> LockGuard<'_, T> {
495 pub fn borrow_mut(&self) -> LockGuard<'_, T> {
500 impl<T: Default> Default for Lock<T> {
502 fn default() -> Self {
503 Lock::new(T::default())
507 // FIXME: Probably a bad idea
508 impl<T: Clone> Clone for Lock<T> {
510 fn clone(&self) -> Self {
511 Lock::new(self.borrow().clone())
515 #[derive(Debug, Default)]
516 pub struct RwLock<T>(InnerRwLock<T>);
520 pub fn new(inner: T) -> Self {
521 RwLock(InnerRwLock::new(inner))
525 pub fn into_inner(self) -> T {
530 pub fn get_mut(&mut self) -> &mut T {
534 #[cfg(not(parallel_compiler))]
536 pub fn read(&self) -> ReadGuard<'_, T> {
540 #[cfg(parallel_compiler)]
542 pub fn read(&self) -> ReadGuard<'_, T> {
544 self.0.try_read().expect("lock was already held")
551 pub fn with_read_lock<F: FnOnce(&T) -> R, R>(&self, f: F) -> R {
555 #[cfg(not(parallel_compiler))]
557 pub fn try_write(&self) -> Result<WriteGuard<'_, T>, ()> {
558 self.0.try_borrow_mut().map_err(|_| ())
561 #[cfg(parallel_compiler)]
563 pub fn try_write(&self) -> Result<WriteGuard<'_, T>, ()> {
564 self.0.try_write().ok_or(())
567 #[cfg(not(parallel_compiler))]
569 pub fn write(&self) -> WriteGuard<'_, T> {
573 #[cfg(parallel_compiler)]
575 pub fn write(&self) -> WriteGuard<'_, T> {
577 self.0.try_write().expect("lock was already held")
584 pub fn with_write_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
585 f(&mut *self.write())
589 pub fn borrow(&self) -> ReadGuard<'_, T> {
594 pub fn borrow_mut(&self) -> WriteGuard<'_, T> {
599 // FIXME: Probably a bad idea
600 impl<T: Clone> Clone for RwLock<T> {
602 fn clone(&self) -> Self {
603 RwLock::new(self.borrow().clone())
607 /// A type which only allows its inner value to be used in one thread.
608 /// It will panic if it is used on multiple threads.
610 pub struct OneThread<T> {
611 #[cfg(parallel_compiler)]
612 thread: thread::ThreadId,
616 #[cfg(parallel_compiler)]
617 unsafe impl<T> std::marker::Sync for OneThread<T> {}
618 #[cfg(parallel_compiler)]
619 unsafe impl<T> std::marker::Send for OneThread<T> {}
621 impl<T> OneThread<T> {
624 #[cfg(parallel_compiler)]
625 assert_eq!(thread::current().id(), self.thread);
629 pub fn new(inner: T) -> Self {
631 #[cfg(parallel_compiler)]
632 thread: thread::current().id(),
638 pub fn into_inner(value: Self) -> T {
644 impl<T> Deref for OneThread<T> {
647 fn deref(&self) -> &T {
653 impl<T> DerefMut for OneThread<T> {
654 fn deref_mut(&mut self) -> &mut T {