]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_data_structures/src/sync.rs
4437c0b1b6964b38c2cd885ac31d428dad9bf486
[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 an 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 use std::panic::{catch_unwind, resume_unwind, AssertUnwindSafe};
25
26 pub use std::sync::atomic::Ordering;
27 pub use std::sync::atomic::Ordering::SeqCst;
28
29 cfg_if! {
30     if #[cfg(not(parallel_compiler))] {
31         pub auto trait Send {}
32         pub auto trait Sync {}
33
34         impl<T: ?Sized> Send for T {}
35         impl<T: ?Sized> Sync for T {}
36
37         #[macro_export]
38         macro_rules! rustc_erase_owner {
39             ($v:expr) => {
40                 $v.erase_owner()
41             }
42         }
43
44         use std::ops::Add;
45
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.
51         #[derive(Debug)]
52         pub struct Atomic<T: Copy>(Cell<T>);
53
54         impl<T: Copy> Atomic<T> {
55             #[inline]
56             pub fn new(v: T) -> Self {
57                 Atomic(Cell::new(v))
58             }
59         }
60
61         impl<T: Copy> Atomic<T> {
62             #[inline]
63             pub fn into_inner(self) -> T {
64                 self.0.into_inner()
65             }
66
67             #[inline]
68             pub fn load(&self, _: Ordering) -> T {
69                 self.0.get()
70             }
71
72             #[inline]
73             pub fn store(&self, val: T, _: Ordering) {
74                 self.0.set(val)
75             }
76
77             #[inline]
78             pub fn swap(&self, val: T, _: Ordering) -> T {
79                 self.0.replace(val)
80             }
81         }
82
83         impl<T: Copy + PartialEq> Atomic<T> {
84             #[inline]
85             pub fn compare_exchange(&self,
86                                     current: T,
87                                     new: T,
88                                     _: Ordering,
89                                     _: Ordering)
90                                     -> Result<T, T> {
91                 let read = self.0.get();
92                 if read == current {
93                     self.0.set(new);
94                     Ok(read)
95                 } else {
96                     Err(read)
97                 }
98             }
99         }
100
101         impl<T: Add<Output=T> + Copy> Atomic<T> {
102             #[inline]
103             pub fn fetch_add(&self, val: T, _: Ordering) -> T {
104                 let old = self.0.get();
105                 self.0.set(old + val);
106                 old
107             }
108         }
109
110         pub type AtomicUsize = Atomic<usize>;
111         pub type AtomicBool = Atomic<bool>;
112         pub type AtomicU32 = Atomic<u32>;
113         pub type AtomicU64 = Atomic<u64>;
114
115         pub fn join<A, B, RA, RB>(oper_a: A, oper_b: B) -> (RA, RB)
116             where A: FnOnce() -> RA,
117                   B: FnOnce() -> RB
118         {
119             (oper_a(), oper_b())
120         }
121
122         #[macro_export]
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;
128                 $(
129                     if let Err(p) = ::std::panic::catch_unwind(
130                         ::std::panic::AssertUnwindSafe(|| $blocks)
131                     ) {
132                         if panic.is_none() {
133                             panic = Some(p);
134                         }
135                     }
136                 )*
137                 if let Some(panic) = panic {
138                     ::std::panic::resume_unwind(panic);
139                 }
140             }
141         }
142
143         pub use std::iter::Iterator as ParallelIterator;
144
145         pub fn par_iter<T: IntoIterator>(t: T) -> T::IntoIter {
146             t.into_iter()
147         }
148
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))) {
155                     if panic.is_none() {
156                         panic = Some(p);
157                     }
158                 }
159             });
160             if let Some(panic) = panic {
161                 resume_unwind(panic);
162             }
163         }
164
165         pub type MetadataRef = OwningRef<Box<dyn Erased>, [u8]>;
166
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;
175
176         pub use std::cell::OnceCell;
177
178         use std::cell::RefCell as InnerRwLock;
179         use std::cell::RefCell as InnerLock;
180
181         use std::cell::Cell;
182
183         #[derive(Debug)]
184         pub struct WorkerLocal<T>(OneThread<T>);
185
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.
189             #[inline]
190             pub fn new<F: FnMut(usize) -> T>(mut f: F) -> WorkerLocal<T> {
191                 WorkerLocal(OneThread::new(f(0)))
192             }
193
194             /// Returns the worker-local value for each thread
195             #[inline]
196             pub fn into_inner(self) -> Vec<T> {
197                 vec![OneThread::into_inner(self.0)]
198             }
199         }
200
201         impl<T> Deref for WorkerLocal<T> {
202             type Target = T;
203
204             #[inline(always)]
205             fn deref(&self) -> &T {
206                 &*self.0
207             }
208         }
209
210         pub type MTRef<'a, T> = &'a mut T;
211
212         #[derive(Debug, Default)]
213         pub struct MTLock<T>(T);
214
215         impl<T> MTLock<T> {
216             #[inline(always)]
217             pub fn new(inner: T) -> Self {
218                 MTLock(inner)
219             }
220
221             #[inline(always)]
222             pub fn into_inner(self) -> T {
223                 self.0
224             }
225
226             #[inline(always)]
227             pub fn get_mut(&mut self) -> &mut T {
228                 &mut self.0
229             }
230
231             #[inline(always)]
232             pub fn lock(&self) -> &T {
233                 &self.0
234             }
235
236             #[inline(always)]
237             pub fn lock_mut(&mut self) -> &mut T {
238                 &mut self.0
239             }
240         }
241
242         // FIXME: Probably a bad idea (in the threaded case)
243         impl<T: Clone> Clone for MTLock<T> {
244             #[inline]
245             fn clone(&self) -> Self {
246                 MTLock(self.0.clone())
247             }
248         }
249     } else {
250         pub use std::marker::Send as Send;
251         pub use std::marker::Sync as Sync;
252
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;
257
258         pub use parking_lot::MutexGuard as LockGuard;
259         pub use parking_lot::MappedMutexGuard as MappedLockGuard;
260
261         pub use std::sync::OnceLock as OnceCell;
262
263         pub use std::sync::atomic::{AtomicBool, AtomicUsize, AtomicU32, AtomicU64};
264
265         pub use std::sync::Arc as Lrc;
266         pub use std::sync::Weak as Weak;
267
268         pub type MTRef<'a, T> = &'a T;
269
270         #[derive(Debug, Default)]
271         pub struct MTLock<T>(Lock<T>);
272
273         impl<T> MTLock<T> {
274             #[inline(always)]
275             pub fn new(inner: T) -> Self {
276                 MTLock(Lock::new(inner))
277             }
278
279             #[inline(always)]
280             pub fn into_inner(self) -> T {
281                 self.0.into_inner()
282             }
283
284             #[inline(always)]
285             pub fn get_mut(&mut self) -> &mut T {
286                 self.0.get_mut()
287             }
288
289             #[inline(always)]
290             pub fn lock(&self) -> LockGuard<'_, T> {
291                 self.0.lock()
292             }
293
294             #[inline(always)]
295             pub fn lock_mut(&self) -> LockGuard<'_, T> {
296                 self.lock()
297             }
298         }
299
300         use parking_lot::Mutex as InnerLock;
301         use parking_lot::RwLock as InnerRwLock;
302
303         use std::thread;
304         pub use rayon::{join, scope};
305
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.
308         #[macro_export]
309         macro_rules! parallel {
310             (impl $fblock:tt [$($c:tt,)*] [$block:tt $(, $rest:tt)*]) => {
311                 parallel!(impl $fblock [$block, $($c,)*] [$($rest),*])
312             };
313             (impl $fblock:tt [$($blocks:tt,)*] []) => {
314                 ::rustc_data_structures::sync::scope(|s| {
315                     $(
316                         s.spawn(|_| $blocks);
317                     )*
318                     $fblock;
319                 })
320             };
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),*]);
326             };
327         }
328
329         pub use rayon_core::WorkerLocal;
330
331         pub use rayon::iter::ParallelIterator;
332         use rayon::iter::IntoParallelIterator;
333
334         pub fn par_iter<T: IntoParallelIterator>(t: T) -> T::Iter {
335             t.into_par_iter()
336         }
337
338         pub fn par_for_each_in<T: IntoParallelIterator>(
339             t: T,
340             for_each: impl Fn(T::Item) + Sync + Send,
341         ) {
342             let ps: Vec<_> = t.into_par_iter().map(|i| catch_unwind(AssertUnwindSafe(|| for_each(i)))).collect();
343             ps.into_iter().for_each(|p| if let Err(panic) = p {
344                 resume_unwind(panic)
345             });
346         }
347
348         pub type MetadataRef = OwningRef<Box<dyn Erased + Send + Sync>, [u8]>;
349
350         /// This makes locks panic if they are already held.
351         /// It is only useful when you are running in a single thread
352         const ERROR_CHECKING: bool = false;
353
354         #[macro_export]
355         macro_rules! rustc_erase_owner {
356             ($v:expr) => {{
357                 let v = $v;
358                 ::rustc_data_structures::sync::assert_send_val(&v);
359                 v.erase_send_sync_owner()
360             }}
361         }
362     }
363 }
364
365 pub fn assert_sync<T: ?Sized + Sync>() {}
366 pub fn assert_send<T: ?Sized + Send>() {}
367 pub fn assert_send_val<T: ?Sized + Send>(_t: &T) {}
368 pub fn assert_send_sync_val<T: ?Sized + Sync + Send>(_t: &T) {}
369
370 pub trait HashMapExt<K, V> {
371     /// Same as HashMap::insert, but it may panic if there's already an
372     /// entry for `key` with a value not equal to `value`
373     fn insert_same(&mut self, key: K, value: V);
374 }
375
376 impl<K: Eq + Hash, V: Eq, S: BuildHasher> HashMapExt<K, V> for HashMap<K, V, S> {
377     fn insert_same(&mut self, key: K, value: V) {
378         self.entry(key).and_modify(|old| assert!(*old == value)).or_insert(value);
379     }
380 }
381
382 #[derive(Debug)]
383 pub struct Lock<T>(InnerLock<T>);
384
385 impl<T> Lock<T> {
386     #[inline(always)]
387     pub fn new(inner: T) -> Self {
388         Lock(InnerLock::new(inner))
389     }
390
391     #[inline(always)]
392     pub fn into_inner(self) -> T {
393         self.0.into_inner()
394     }
395
396     #[inline(always)]
397     pub fn get_mut(&mut self) -> &mut T {
398         self.0.get_mut()
399     }
400
401     #[cfg(parallel_compiler)]
402     #[inline(always)]
403     pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
404         self.0.try_lock()
405     }
406
407     #[cfg(not(parallel_compiler))]
408     #[inline(always)]
409     pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
410         self.0.try_borrow_mut().ok()
411     }
412
413     #[cfg(parallel_compiler)]
414     #[inline(always)]
415     pub fn lock(&self) -> LockGuard<'_, T> {
416         if ERROR_CHECKING {
417             self.0.try_lock().expect("lock was already held")
418         } else {
419             self.0.lock()
420         }
421     }
422
423     #[cfg(not(parallel_compiler))]
424     #[inline(always)]
425     pub fn lock(&self) -> LockGuard<'_, T> {
426         self.0.borrow_mut()
427     }
428
429     #[inline(always)]
430     pub fn with_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
431         f(&mut *self.lock())
432     }
433
434     #[inline(always)]
435     pub fn borrow(&self) -> LockGuard<'_, T> {
436         self.lock()
437     }
438
439     #[inline(always)]
440     pub fn borrow_mut(&self) -> LockGuard<'_, T> {
441         self.lock()
442     }
443 }
444
445 impl<T: Default> Default for Lock<T> {
446     #[inline]
447     fn default() -> Self {
448         Lock::new(T::default())
449     }
450 }
451
452 // FIXME: Probably a bad idea
453 impl<T: Clone> Clone for Lock<T> {
454     #[inline]
455     fn clone(&self) -> Self {
456         Lock::new(self.borrow().clone())
457     }
458 }
459
460 #[derive(Debug, Default)]
461 pub struct RwLock<T>(InnerRwLock<T>);
462
463 impl<T> RwLock<T> {
464     #[inline(always)]
465     pub fn new(inner: T) -> Self {
466         RwLock(InnerRwLock::new(inner))
467     }
468
469     #[inline(always)]
470     pub fn into_inner(self) -> T {
471         self.0.into_inner()
472     }
473
474     #[inline(always)]
475     pub fn get_mut(&mut self) -> &mut T {
476         self.0.get_mut()
477     }
478
479     #[cfg(not(parallel_compiler))]
480     #[inline(always)]
481     pub fn read(&self) -> ReadGuard<'_, T> {
482         self.0.borrow()
483     }
484
485     #[cfg(parallel_compiler)]
486     #[inline(always)]
487     pub fn read(&self) -> ReadGuard<'_, T> {
488         if ERROR_CHECKING {
489             self.0.try_read().expect("lock was already held")
490         } else {
491             self.0.read()
492         }
493     }
494
495     #[inline(always)]
496     pub fn with_read_lock<F: FnOnce(&T) -> R, R>(&self, f: F) -> R {
497         f(&*self.read())
498     }
499
500     #[cfg(not(parallel_compiler))]
501     #[inline(always)]
502     pub fn try_write(&self) -> Result<WriteGuard<'_, T>, ()> {
503         self.0.try_borrow_mut().map_err(|_| ())
504     }
505
506     #[cfg(parallel_compiler)]
507     #[inline(always)]
508     pub fn try_write(&self) -> Result<WriteGuard<'_, T>, ()> {
509         self.0.try_write().ok_or(())
510     }
511
512     #[cfg(not(parallel_compiler))]
513     #[inline(always)]
514     pub fn write(&self) -> WriteGuard<'_, T> {
515         self.0.borrow_mut()
516     }
517
518     #[cfg(parallel_compiler)]
519     #[inline(always)]
520     pub fn write(&self) -> WriteGuard<'_, T> {
521         if ERROR_CHECKING {
522             self.0.try_write().expect("lock was already held")
523         } else {
524             self.0.write()
525         }
526     }
527
528     #[inline(always)]
529     pub fn with_write_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
530         f(&mut *self.write())
531     }
532
533     #[inline(always)]
534     pub fn borrow(&self) -> ReadGuard<'_, T> {
535         self.read()
536     }
537
538     #[inline(always)]
539     pub fn borrow_mut(&self) -> WriteGuard<'_, T> {
540         self.write()
541     }
542 }
543
544 // FIXME: Probably a bad idea
545 impl<T: Clone> Clone for RwLock<T> {
546     #[inline]
547     fn clone(&self) -> Self {
548         RwLock::new(self.borrow().clone())
549     }
550 }
551
552 /// A type which only allows its inner value to be used in one thread.
553 /// It will panic if it is used on multiple threads.
554 #[derive(Debug)]
555 pub struct OneThread<T> {
556     #[cfg(parallel_compiler)]
557     thread: thread::ThreadId,
558     inner: T,
559 }
560
561 #[cfg(parallel_compiler)]
562 unsafe impl<T> std::marker::Sync for OneThread<T> {}
563 #[cfg(parallel_compiler)]
564 unsafe impl<T> std::marker::Send for OneThread<T> {}
565
566 impl<T> OneThread<T> {
567     #[inline(always)]
568     fn check(&self) {
569         #[cfg(parallel_compiler)]
570         assert_eq!(thread::current().id(), self.thread);
571     }
572
573     #[inline(always)]
574     pub fn new(inner: T) -> Self {
575         OneThread {
576             #[cfg(parallel_compiler)]
577             thread: thread::current().id(),
578             inner,
579         }
580     }
581
582     #[inline(always)]
583     pub fn into_inner(value: Self) -> T {
584         value.check();
585         value.inner
586     }
587 }
588
589 impl<T> Deref for OneThread<T> {
590     type Target = T;
591
592     fn deref(&self) -> &T {
593         self.check();
594         &self.inner
595     }
596 }
597
598 impl<T> DerefMut for OneThread<T> {
599     fn deref_mut(&mut self) -> &mut T {
600         self.check();
601         &mut self.inner
602     }
603 }