]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_data_structures/src/sync.rs
Auto merge of #85053 - camsteffen:duplicate-lint, r=davidtwco
[rust.git] / compiler / rustc_data_structures / src / sync.rs
1 //! This module defines types which are thread safe if cfg!(parallel_compiler) is true.
2 //!
3 //! `Lrc` is an alias of `Arc` if cfg!(parallel_compiler) is true, `Rc` otherwise.
4 //!
5 //! `Lock` is a mutex.
6 //! It internally uses `parking_lot::Mutex` if cfg!(parallel_compiler) is true,
7 //! `RefCell` otherwise.
8 //!
9 //! `RwLock` is a read-write lock.
10 //! It internally uses `parking_lot::RwLock` if cfg!(parallel_compiler) is true,
11 //! `RefCell` otherwise.
12 //!
13 //! `MTLock` is a mutex which disappears if cfg!(parallel_compiler) is false.
14 //!
15 //! `MTRef` is an immutable reference if cfg!(parallel_compiler), and a mutable reference otherwise.
16 //!
17 //! `rustc_erase_owner!` erases a OwningRef owner into Erased or Erased + Send + Sync
18 //! depending on the value of cfg!(parallel_compiler).
19
20 use crate::owning_ref::{Erased, OwningRef};
21 use std::collections::HashMap;
22 use std::hash::{BuildHasher, Hash};
23 use std::ops::{Deref, DerefMut};
24
25 pub use std::sync::atomic::Ordering;
26 pub use std::sync::atomic::Ordering::SeqCst;
27
28 cfg_if! {
29     if #[cfg(not(parallel_compiler))] {
30         pub auto trait Send {}
31         pub auto trait Sync {}
32
33         impl<T: ?Sized> Send for T {}
34         impl<T: ?Sized> Sync for T {}
35
36         #[macro_export]
37         macro_rules! rustc_erase_owner {
38             ($v:expr) => {
39                 $v.erase_owner()
40             }
41         }
42
43         use std::ops::Add;
44         use std::panic::{resume_unwind, catch_unwind, AssertUnwindSafe};
45
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.
49         #[derive(Debug)]
50         pub struct AtomicCell<T: Copy>(Cell<T>);
51
52         impl<T: Copy> AtomicCell<T> {
53             #[inline]
54             pub fn new(v: T) -> Self {
55                 AtomicCell(Cell::new(v))
56             }
57
58             #[inline]
59             pub fn get_mut(&mut self) -> &mut T {
60                 self.0.get_mut()
61             }
62         }
63
64         impl<T: Copy> AtomicCell<T> {
65             #[inline]
66             pub fn into_inner(self) -> T {
67                 self.0.into_inner()
68             }
69
70             #[inline]
71             pub fn load(&self) -> T {
72                 self.0.get()
73             }
74
75             #[inline]
76             pub fn store(&self, val: T) {
77                 self.0.set(val)
78             }
79
80             #[inline]
81             pub fn swap(&self, val: T) -> T {
82                 self.0.replace(val)
83             }
84         }
85
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.
91         #[derive(Debug)]
92         pub struct Atomic<T: Copy>(Cell<T>);
93
94         impl<T: Copy> Atomic<T> {
95             #[inline]
96             pub fn new(v: T) -> Self {
97                 Atomic(Cell::new(v))
98             }
99         }
100
101         impl<T: Copy> Atomic<T> {
102             #[inline]
103             pub fn into_inner(self) -> T {
104                 self.0.into_inner()
105             }
106
107             #[inline]
108             pub fn load(&self, _: Ordering) -> T {
109                 self.0.get()
110             }
111
112             #[inline]
113             pub fn store(&self, val: T, _: Ordering) {
114                 self.0.set(val)
115             }
116
117             #[inline]
118             pub fn swap(&self, val: T, _: Ordering) -> T {
119                 self.0.replace(val)
120             }
121         }
122
123         impl<T: Copy + PartialEq> Atomic<T> {
124             #[inline]
125             pub fn compare_exchange(&self,
126                                     current: T,
127                                     new: T,
128                                     _: Ordering,
129                                     _: Ordering)
130                                     -> Result<T, T> {
131                 let read = self.0.get();
132                 if read == current {
133                     self.0.set(new);
134                     Ok(read)
135                 } else {
136                     Err(read)
137                 }
138             }
139         }
140
141         impl<T: Add<Output=T> + Copy> Atomic<T> {
142             #[inline]
143             pub fn fetch_add(&self, val: T, _: Ordering) -> T {
144                 let old = self.0.get();
145                 self.0.set(old + val);
146                 old
147             }
148         }
149
150         pub type AtomicUsize = Atomic<usize>;
151         pub type AtomicBool = Atomic<bool>;
152         pub type AtomicU32 = Atomic<u32>;
153         pub type AtomicU64 = Atomic<u64>;
154
155         pub fn join<A, B, RA, RB>(oper_a: A, oper_b: B) -> (RA, RB)
156             where A: FnOnce() -> RA,
157                   B: FnOnce() -> RB
158         {
159             (oper_a(), oper_b())
160         }
161
162         pub struct SerialScope;
163
164         impl SerialScope {
165             pub fn spawn<F>(&self, f: F)
166                 where F: FnOnce(&SerialScope)
167             {
168                 f(self)
169             }
170         }
171
172         pub fn scope<F, R>(f: F) -> R
173             where F: FnOnce(&SerialScope) -> R
174         {
175             f(&SerialScope)
176         }
177
178         #[macro_export]
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;
184                 $(
185                     if let Err(p) = ::std::panic::catch_unwind(
186                         ::std::panic::AssertUnwindSafe(|| $blocks)
187                     ) {
188                         if panic.is_none() {
189                             panic = Some(p);
190                         }
191                     }
192                 )*
193                 if let Some(panic) = panic {
194                     ::std::panic::resume_unwind(panic);
195                 }
196             }
197         }
198
199         pub use std::iter::Iterator as ParallelIterator;
200
201         pub fn par_iter<T: IntoIterator>(t: T) -> T::IntoIter {
202             t.into_iter()
203         }
204
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))) {
211                     if panic.is_none() {
212                         panic = Some(p);
213                     }
214                 }
215             });
216             if let Some(panic) = panic {
217                 resume_unwind(panic);
218             }
219         }
220
221         pub type MetadataRef = OwningRef<Box<dyn Erased>, [u8]>;
222
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;
231
232         pub use std::lazy::OnceCell;
233
234         use std::cell::RefCell as InnerRwLock;
235         use std::cell::RefCell as InnerLock;
236
237         use std::cell::Cell;
238
239         #[derive(Debug)]
240         pub struct WorkerLocal<T>(OneThread<T>);
241
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.
245             #[inline]
246             pub fn new<F: FnMut(usize) -> T>(mut f: F) -> WorkerLocal<T> {
247                 WorkerLocal(OneThread::new(f(0)))
248             }
249
250             /// Returns the worker-local value for each thread
251             #[inline]
252             pub fn into_inner(self) -> Vec<T> {
253                 vec![OneThread::into_inner(self.0)]
254             }
255         }
256
257         impl<T> Deref for WorkerLocal<T> {
258             type Target = T;
259
260             #[inline(always)]
261             fn deref(&self) -> &T {
262                 &*self.0
263             }
264         }
265
266         pub type MTRef<'a, T> = &'a mut T;
267
268         #[derive(Debug, Default)]
269         pub struct MTLock<T>(T);
270
271         impl<T> MTLock<T> {
272             #[inline(always)]
273             pub fn new(inner: T) -> Self {
274                 MTLock(inner)
275             }
276
277             #[inline(always)]
278             pub fn into_inner(self) -> T {
279                 self.0
280             }
281
282             #[inline(always)]
283             pub fn get_mut(&mut self) -> &mut T {
284                 &mut self.0
285             }
286
287             #[inline(always)]
288             pub fn lock(&self) -> &T {
289                 &self.0
290             }
291
292             #[inline(always)]
293             pub fn lock_mut(&mut self) -> &mut T {
294                 &mut self.0
295             }
296         }
297
298         // FIXME: Probably a bad idea (in the threaded case)
299         impl<T: Clone> Clone for MTLock<T> {
300             #[inline]
301             fn clone(&self) -> Self {
302                 MTLock(self.0.clone())
303             }
304         }
305     } else {
306         pub use std::marker::Send as Send;
307         pub use std::marker::Sync as Sync;
308
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;
313
314         pub use parking_lot::MutexGuard as LockGuard;
315         pub use parking_lot::MappedMutexGuard as MappedLockGuard;
316
317         pub use std::lazy::SyncOnceCell as OnceCell;
318
319         pub use std::sync::atomic::{AtomicBool, AtomicUsize, AtomicU32, AtomicU64};
320
321         pub use crossbeam_utils::atomic::AtomicCell;
322
323         pub use std::sync::Arc as Lrc;
324         pub use std::sync::Weak as Weak;
325
326         pub type MTRef<'a, T> = &'a T;
327
328         #[derive(Debug, Default)]
329         pub struct MTLock<T>(Lock<T>);
330
331         impl<T> MTLock<T> {
332             #[inline(always)]
333             pub fn new(inner: T) -> Self {
334                 MTLock(Lock::new(inner))
335             }
336
337             #[inline(always)]
338             pub fn into_inner(self) -> T {
339                 self.0.into_inner()
340             }
341
342             #[inline(always)]
343             pub fn get_mut(&mut self) -> &mut T {
344                 self.0.get_mut()
345             }
346
347             #[inline(always)]
348             pub fn lock(&self) -> LockGuard<'_, T> {
349                 self.0.lock()
350             }
351
352             #[inline(always)]
353             pub fn lock_mut(&self) -> LockGuard<'_, T> {
354                 self.lock()
355             }
356         }
357
358         use parking_lot::Mutex as InnerLock;
359         use parking_lot::RwLock as InnerRwLock;
360
361         use std::thread;
362         pub use rayon::{join, scope};
363
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.
366         #[macro_export]
367         macro_rules! parallel {
368             (impl $fblock:tt [$($c:tt,)*] [$block:tt $(, $rest:tt)*]) => {
369                 parallel!(impl $fblock [$block, $($c,)*] [$($rest),*])
370             };
371             (impl $fblock:tt [$($blocks:tt,)*] []) => {
372                 ::rustc_data_structures::sync::scope(|s| {
373                     $(
374                         s.spawn(|_| $blocks);
375                     )*
376                     $fblock;
377                 })
378             };
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),*]);
384             };
385         }
386
387         pub use rayon_core::WorkerLocal;
388
389         pub use rayon::iter::ParallelIterator;
390         use rayon::iter::IntoParallelIterator;
391
392         pub fn par_iter<T: IntoParallelIterator>(t: T) -> T::Iter {
393             t.into_par_iter()
394         }
395
396         pub fn par_for_each_in<T: IntoParallelIterator>(
397             t: T,
398             for_each: impl Fn(T::Item) + Sync + Send,
399         ) {
400             t.into_par_iter().for_each(for_each)
401         }
402
403         pub type MetadataRef = OwningRef<Box<dyn Erased + Send + Sync>, [u8]>;
404
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;
408
409         #[macro_export]
410         macro_rules! rustc_erase_owner {
411             ($v:expr) => {{
412                 let v = $v;
413                 ::rustc_data_structures::sync::assert_send_val(&v);
414                 v.erase_send_sync_owner()
415             }}
416         }
417     }
418 }
419
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) {}
424
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);
429 }
430
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);
434     }
435 }
436
437 #[derive(Debug)]
438 pub struct Lock<T>(InnerLock<T>);
439
440 impl<T> Lock<T> {
441     #[inline(always)]
442     pub fn new(inner: T) -> Self {
443         Lock(InnerLock::new(inner))
444     }
445
446     #[inline(always)]
447     pub fn into_inner(self) -> T {
448         self.0.into_inner()
449     }
450
451     #[inline(always)]
452     pub fn get_mut(&mut self) -> &mut T {
453         self.0.get_mut()
454     }
455
456     #[cfg(parallel_compiler)]
457     #[inline(always)]
458     pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
459         self.0.try_lock()
460     }
461
462     #[cfg(not(parallel_compiler))]
463     #[inline(always)]
464     pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
465         self.0.try_borrow_mut().ok()
466     }
467
468     #[cfg(parallel_compiler)]
469     #[inline(always)]
470     pub fn lock(&self) -> LockGuard<'_, T> {
471         if ERROR_CHECKING {
472             self.0.try_lock().expect("lock was already held")
473         } else {
474             self.0.lock()
475         }
476     }
477
478     #[cfg(not(parallel_compiler))]
479     #[inline(always)]
480     pub fn lock(&self) -> LockGuard<'_, T> {
481         self.0.borrow_mut()
482     }
483
484     #[inline(always)]
485     pub fn with_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
486         f(&mut *self.lock())
487     }
488
489     #[inline(always)]
490     pub fn borrow(&self) -> LockGuard<'_, T> {
491         self.lock()
492     }
493
494     #[inline(always)]
495     pub fn borrow_mut(&self) -> LockGuard<'_, T> {
496         self.lock()
497     }
498 }
499
500 impl<T: Default> Default for Lock<T> {
501     #[inline]
502     fn default() -> Self {
503         Lock::new(T::default())
504     }
505 }
506
507 // FIXME: Probably a bad idea
508 impl<T: Clone> Clone for Lock<T> {
509     #[inline]
510     fn clone(&self) -> Self {
511         Lock::new(self.borrow().clone())
512     }
513 }
514
515 #[derive(Debug, Default)]
516 pub struct RwLock<T>(InnerRwLock<T>);
517
518 impl<T> RwLock<T> {
519     #[inline(always)]
520     pub fn new(inner: T) -> Self {
521         RwLock(InnerRwLock::new(inner))
522     }
523
524     #[inline(always)]
525     pub fn into_inner(self) -> T {
526         self.0.into_inner()
527     }
528
529     #[inline(always)]
530     pub fn get_mut(&mut self) -> &mut T {
531         self.0.get_mut()
532     }
533
534     #[cfg(not(parallel_compiler))]
535     #[inline(always)]
536     pub fn read(&self) -> ReadGuard<'_, T> {
537         self.0.borrow()
538     }
539
540     #[cfg(parallel_compiler)]
541     #[inline(always)]
542     pub fn read(&self) -> ReadGuard<'_, T> {
543         if ERROR_CHECKING {
544             self.0.try_read().expect("lock was already held")
545         } else {
546             self.0.read()
547         }
548     }
549
550     #[inline(always)]
551     pub fn with_read_lock<F: FnOnce(&T) -> R, R>(&self, f: F) -> R {
552         f(&*self.read())
553     }
554
555     #[cfg(not(parallel_compiler))]
556     #[inline(always)]
557     pub fn try_write(&self) -> Result<WriteGuard<'_, T>, ()> {
558         self.0.try_borrow_mut().map_err(|_| ())
559     }
560
561     #[cfg(parallel_compiler)]
562     #[inline(always)]
563     pub fn try_write(&self) -> Result<WriteGuard<'_, T>, ()> {
564         self.0.try_write().ok_or(())
565     }
566
567     #[cfg(not(parallel_compiler))]
568     #[inline(always)]
569     pub fn write(&self) -> WriteGuard<'_, T> {
570         self.0.borrow_mut()
571     }
572
573     #[cfg(parallel_compiler)]
574     #[inline(always)]
575     pub fn write(&self) -> WriteGuard<'_, T> {
576         if ERROR_CHECKING {
577             self.0.try_write().expect("lock was already held")
578         } else {
579             self.0.write()
580         }
581     }
582
583     #[inline(always)]
584     pub fn with_write_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
585         f(&mut *self.write())
586     }
587
588     #[inline(always)]
589     pub fn borrow(&self) -> ReadGuard<'_, T> {
590         self.read()
591     }
592
593     #[inline(always)]
594     pub fn borrow_mut(&self) -> WriteGuard<'_, T> {
595         self.write()
596     }
597 }
598
599 // FIXME: Probably a bad idea
600 impl<T: Clone> Clone for RwLock<T> {
601     #[inline]
602     fn clone(&self) -> Self {
603         RwLock::new(self.borrow().clone())
604     }
605 }
606
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.
609 #[derive(Debug)]
610 pub struct OneThread<T> {
611     #[cfg(parallel_compiler)]
612     thread: thread::ThreadId,
613     inner: T,
614 }
615
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> {}
620
621 impl<T> OneThread<T> {
622     #[inline(always)]
623     fn check(&self) {
624         #[cfg(parallel_compiler)]
625         assert_eq!(thread::current().id(), self.thread);
626     }
627
628     #[inline(always)]
629     pub fn new(inner: T) -> Self {
630         OneThread {
631             #[cfg(parallel_compiler)]
632             thread: thread::current().id(),
633             inner,
634         }
635     }
636
637     #[inline(always)]
638     pub fn into_inner(value: Self) -> T {
639         value.check();
640         value.inner
641     }
642 }
643
644 impl<T> Deref for OneThread<T> {
645     type Target = T;
646
647     fn deref(&self) -> &T {
648         self.check();
649         &self.inner
650     }
651 }
652
653 impl<T> DerefMut for OneThread<T> {
654     fn deref_mut(&mut self) -> &mut T {
655         self.check();
656         &mut self.inner
657     }
658 }