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 an 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 `AtomicU64`, `AtomicUsize`, etc.
47 /// It has explicit ordering arguments and is only intended for use with
48 /// the native atomic types.
49 /// You should use this type through the `AtomicU64`, `AtomicUsize`, etc, type aliases
50 /// as it's not intended to be used separately.
52 pub struct Atomic<T: Copy>(Cell<T>);
54 impl<T: Copy> Atomic<T> {
56 pub fn new(v: T) -> Self {
61 impl<T: Copy> Atomic<T> {
63 pub fn into_inner(self) -> T {
68 pub fn load(&self, _: Ordering) -> T {
73 pub fn store(&self, val: T, _: Ordering) {
78 pub fn swap(&self, val: T, _: Ordering) -> T {
83 impl<T: Copy + PartialEq> Atomic<T> {
85 pub fn compare_exchange(&self,
91 let read = self.0.get();
101 impl<T: Add<Output=T> + Copy> Atomic<T> {
103 pub fn fetch_add(&self, val: T, _: Ordering) -> T {
104 let old = self.0.get();
105 self.0.set(old + val);
110 pub type AtomicUsize = Atomic<usize>;
111 pub type AtomicBool = Atomic<bool>;
112 pub type AtomicU32 = Atomic<u32>;
113 pub type AtomicU64 = Atomic<u64>;
115 pub fn join<A, B, RA, RB>(oper_a: A, oper_b: B) -> (RA, RB)
116 where A: FnOnce() -> RA,
123 macro_rules! parallel {
124 ($($blocks:tt),*) => {
125 // We catch panics here ensuring that all the blocks execute.
126 // This makes behavior consistent with the parallel compiler.
127 let mut panic = None;
129 if let Err(p) = ::std::panic::catch_unwind(
130 ::std::panic::AssertUnwindSafe(|| $blocks)
137 if let Some(panic) = panic {
138 ::std::panic::resume_unwind(panic);
143 pub use std::iter::Iterator as ParallelIterator;
145 pub fn par_iter<T: IntoIterator>(t: T) -> T::IntoIter {
149 pub fn par_for_each_in<T: IntoIterator>(t: T, for_each: impl Fn(T::Item) + Sync + Send) {
150 // We catch panics here ensuring that all the loop iterations execute.
151 // This makes behavior consistent with the parallel compiler.
152 let mut panic = None;
153 t.into_iter().for_each(|i| {
154 if let Err(p) = catch_unwind(AssertUnwindSafe(|| for_each(i))) {
160 if let Some(panic) = panic {
161 resume_unwind(panic);
165 pub type MetadataRef = OwningRef<Box<dyn Erased>, [u8]>;
167 pub use std::rc::Rc as Lrc;
168 pub use std::rc::Weak as Weak;
169 pub use std::cell::Ref as ReadGuard;
170 pub use std::cell::Ref as MappedReadGuard;
171 pub use std::cell::RefMut as WriteGuard;
172 pub use std::cell::RefMut as MappedWriteGuard;
173 pub use std::cell::RefMut as LockGuard;
174 pub use std::cell::RefMut as MappedLockGuard;
176 pub use std::lazy::OnceCell;
178 use std::cell::RefCell as InnerRwLock;
179 use std::cell::RefCell as InnerLock;
184 pub struct WorkerLocal<T>(OneThread<T>);
186 impl<T> WorkerLocal<T> {
187 /// Creates a new worker local where the `initial` closure computes the
188 /// value this worker local should take for each thread in the thread pool.
190 pub fn new<F: FnMut(usize) -> T>(mut f: F) -> WorkerLocal<T> {
191 WorkerLocal(OneThread::new(f(0)))
194 /// Returns the worker-local value for each thread
196 pub fn into_inner(self) -> Vec<T> {
197 vec![OneThread::into_inner(self.0)]
201 impl<T> Deref for WorkerLocal<T> {
205 fn deref(&self) -> &T {
210 pub type MTRef<'a, T> = &'a mut T;
212 #[derive(Debug, Default)]
213 pub struct MTLock<T>(T);
217 pub fn new(inner: T) -> Self {
222 pub fn into_inner(self) -> T {
227 pub fn get_mut(&mut self) -> &mut T {
232 pub fn lock(&self) -> &T {
237 pub fn lock_mut(&mut self) -> &mut T {
242 // FIXME: Probably a bad idea (in the threaded case)
243 impl<T: Clone> Clone for MTLock<T> {
245 fn clone(&self) -> Self {
246 MTLock(self.0.clone())
250 pub use std::marker::Send as Send;
251 pub use std::marker::Sync as Sync;
253 pub use parking_lot::RwLockReadGuard as ReadGuard;
254 pub use parking_lot::MappedRwLockReadGuard as MappedReadGuard;
255 pub use parking_lot::RwLockWriteGuard as WriteGuard;
256 pub use parking_lot::MappedRwLockWriteGuard as MappedWriteGuard;
258 pub use parking_lot::MutexGuard as LockGuard;
259 pub use parking_lot::MappedMutexGuard as MappedLockGuard;
261 pub use std::lazy::SyncOnceCell as OnceCell;
263 pub use std::sync::atomic::{AtomicBool, AtomicUsize, AtomicU32, AtomicU64};
265 pub use std::sync::Arc as Lrc;
266 pub use std::sync::Weak as Weak;
268 pub type MTRef<'a, T> = &'a T;
270 #[derive(Debug, Default)]
271 pub struct MTLock<T>(Lock<T>);
275 pub fn new(inner: T) -> Self {
276 MTLock(Lock::new(inner))
280 pub fn into_inner(self) -> T {
285 pub fn get_mut(&mut self) -> &mut T {
290 pub fn lock(&self) -> LockGuard<'_, T> {
295 pub fn lock_mut(&self) -> LockGuard<'_, T> {
300 use parking_lot::Mutex as InnerLock;
301 use parking_lot::RwLock as InnerRwLock;
304 pub use rayon::{join, scope};
306 /// Runs a list of blocks in parallel. The first block is executed immediately on
307 /// the current thread. Use that for the longest running block.
309 macro_rules! parallel {
310 (impl $fblock:tt [$($c:tt,)*] [$block:tt $(, $rest:tt)*]) => {
311 parallel!(impl $fblock [$block, $($c,)*] [$($rest),*])
313 (impl $fblock:tt [$($blocks:tt,)*] []) => {
314 ::rustc_data_structures::sync::scope(|s| {
316 s.spawn(|_| $blocks);
321 ($fblock:tt, $($blocks:tt),*) => {
322 // Reverse the order of the later blocks since Rayon executes them in reverse order
323 // when using a single thread. This ensures the execution order matches that
324 // of a single threaded rustc
325 parallel!(impl $fblock [] [$($blocks),*]);
329 pub use rayon_core::WorkerLocal;
331 pub use rayon::iter::ParallelIterator;
332 use rayon::iter::IntoParallelIterator;
334 pub fn par_iter<T: IntoParallelIterator>(t: T) -> T::Iter {
338 pub fn par_for_each_in<T: IntoParallelIterator>(
340 for_each: impl Fn(T::Item) + Sync + Send,
342 t.into_par_iter().for_each(for_each)
345 pub type MetadataRef = OwningRef<Box<dyn Erased + Send + Sync>, [u8]>;
347 /// This makes locks panic if they are already held.
348 /// It is only useful when you are running in a single thread
349 const ERROR_CHECKING: bool = false;
352 macro_rules! rustc_erase_owner {
355 ::rustc_data_structures::sync::assert_send_val(&v);
356 v.erase_send_sync_owner()
362 pub fn assert_sync<T: ?Sized + Sync>() {}
363 pub fn assert_send<T: ?Sized + Send>() {}
364 pub fn assert_send_val<T: ?Sized + Send>(_t: &T) {}
365 pub fn assert_send_sync_val<T: ?Sized + Sync + Send>(_t: &T) {}
367 pub trait HashMapExt<K, V> {
368 /// Same as HashMap::insert, but it may panic if there's already an
369 /// entry for `key` with a value not equal to `value`
370 fn insert_same(&mut self, key: K, value: V);
373 impl<K: Eq + Hash, V: Eq, S: BuildHasher> HashMapExt<K, V> for HashMap<K, V, S> {
374 fn insert_same(&mut self, key: K, value: V) {
375 self.entry(key).and_modify(|old| assert!(*old == value)).or_insert(value);
380 pub struct Lock<T>(InnerLock<T>);
384 pub fn new(inner: T) -> Self {
385 Lock(InnerLock::new(inner))
389 pub fn into_inner(self) -> T {
394 pub fn get_mut(&mut self) -> &mut T {
398 #[cfg(parallel_compiler)]
400 pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
404 #[cfg(not(parallel_compiler))]
406 pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
407 self.0.try_borrow_mut().ok()
410 #[cfg(parallel_compiler)]
412 pub fn lock(&self) -> LockGuard<'_, T> {
414 self.0.try_lock().expect("lock was already held")
420 #[cfg(not(parallel_compiler))]
422 pub fn lock(&self) -> LockGuard<'_, T> {
427 pub fn with_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
432 pub fn borrow(&self) -> LockGuard<'_, T> {
437 pub fn borrow_mut(&self) -> LockGuard<'_, T> {
442 impl<T: Default> Default for Lock<T> {
444 fn default() -> Self {
445 Lock::new(T::default())
449 // FIXME: Probably a bad idea
450 impl<T: Clone> Clone for Lock<T> {
452 fn clone(&self) -> Self {
453 Lock::new(self.borrow().clone())
457 #[derive(Debug, Default)]
458 pub struct RwLock<T>(InnerRwLock<T>);
462 pub fn new(inner: T) -> Self {
463 RwLock(InnerRwLock::new(inner))
467 pub fn into_inner(self) -> T {
472 pub fn get_mut(&mut self) -> &mut T {
476 #[cfg(not(parallel_compiler))]
478 pub fn read(&self) -> ReadGuard<'_, T> {
482 #[cfg(parallel_compiler)]
484 pub fn read(&self) -> ReadGuard<'_, T> {
486 self.0.try_read().expect("lock was already held")
493 pub fn with_read_lock<F: FnOnce(&T) -> R, R>(&self, f: F) -> R {
497 #[cfg(not(parallel_compiler))]
499 pub fn try_write(&self) -> Result<WriteGuard<'_, T>, ()> {
500 self.0.try_borrow_mut().map_err(|_| ())
503 #[cfg(parallel_compiler)]
505 pub fn try_write(&self) -> Result<WriteGuard<'_, T>, ()> {
506 self.0.try_write().ok_or(())
509 #[cfg(not(parallel_compiler))]
511 pub fn write(&self) -> WriteGuard<'_, T> {
515 #[cfg(parallel_compiler)]
517 pub fn write(&self) -> WriteGuard<'_, T> {
519 self.0.try_write().expect("lock was already held")
526 pub fn with_write_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
527 f(&mut *self.write())
531 pub fn borrow(&self) -> ReadGuard<'_, T> {
536 pub fn borrow_mut(&self) -> WriteGuard<'_, T> {
541 // FIXME: Probably a bad idea
542 impl<T: Clone> Clone for RwLock<T> {
544 fn clone(&self) -> Self {
545 RwLock::new(self.borrow().clone())
549 /// A type which only allows its inner value to be used in one thread.
550 /// It will panic if it is used on multiple threads.
552 pub struct OneThread<T> {
553 #[cfg(parallel_compiler)]
554 thread: thread::ThreadId,
558 #[cfg(parallel_compiler)]
559 unsafe impl<T> std::marker::Sync for OneThread<T> {}
560 #[cfg(parallel_compiler)]
561 unsafe impl<T> std::marker::Send for OneThread<T> {}
563 impl<T> OneThread<T> {
566 #[cfg(parallel_compiler)]
567 assert_eq!(thread::current().id(), self.thread);
571 pub fn new(inner: T) -> Self {
573 #[cfg(parallel_compiler)]
574 thread: thread::current().id(),
580 pub fn into_inner(value: Self) -> T {
586 impl<T> Deref for OneThread<T> {
589 fn deref(&self) -> &T {
595 impl<T> DerefMut for OneThread<T> {
596 fn deref_mut(&mut self) -> &mut T {