]> git.lizzy.rs Git - rust.git/blob - src/librustc_data_structures/sync.rs
Merge remote-tracking branch 'upstream/master'
[rust.git] / src / librustc_data_structures / sync.rs
1 //! This module defines types which are thread safe if cfg!(parallel_compiler) is true.
2 //!
3 //! `Lrc` is an alias of either Rc or Arc.
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 a immutable reference if cfg!(parallel_compiler), and an 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 std::collections::HashMap;
21 use std::hash::{Hash, BuildHasher};
22 use std::marker::PhantomData;
23 use std::ops::{Deref, DerefMut};
24 use crate::owning_ref::{Erased, OwningRef};
25
26 pub fn serial_join<A, B, RA, RB>(oper_a: A, oper_b: B) -> (RA, RB)
27     where A: FnOnce() -> RA,
28           B: FnOnce() -> RB
29 {
30     (oper_a(), oper_b())
31 }
32
33 pub struct SerialScope;
34
35 impl SerialScope {
36     pub fn spawn<F>(&self, f: F)
37         where F: FnOnce(&SerialScope)
38     {
39         f(self)
40     }
41 }
42
43 pub fn serial_scope<F, R>(f: F) -> R
44     where F: FnOnce(&SerialScope) -> R
45 {
46     f(&SerialScope)
47 }
48
49 pub use std::sync::atomic::Ordering::SeqCst;
50 pub use std::sync::atomic::Ordering;
51
52 cfg_if! {
53     if #[cfg(not(parallel_compiler))] {
54         pub auto trait Send {}
55         pub auto trait Sync {}
56
57         impl<T: ?Sized> Send for T {}
58         impl<T: ?Sized> Sync for T {}
59
60         #[macro_export]
61         macro_rules! rustc_erase_owner {
62             ($v:expr) => {
63                 $v.erase_owner()
64             }
65         }
66
67         use std::ops::Add;
68
69         #[derive(Debug)]
70         pub struct Atomic<T: Copy>(Cell<T>);
71
72         impl<T: Copy> Atomic<T> {
73             #[inline]
74             pub fn new(v: T) -> Self {
75                 Atomic(Cell::new(v))
76             }
77         }
78
79         impl<T: Copy + PartialEq> Atomic<T> {
80             pub fn into_inner(self) -> T {
81                 self.0.into_inner()
82             }
83
84             #[inline]
85             pub fn load(&self, _: Ordering) -> T {
86                 self.0.get()
87             }
88
89             #[inline]
90             pub fn store(&self, val: T, _: Ordering) {
91                 self.0.set(val)
92             }
93
94             pub fn swap(&self, val: T, _: Ordering) -> T {
95                 self.0.replace(val)
96             }
97
98             pub fn compare_exchange(&self,
99                                     current: T,
100                                     new: T,
101                                     _: Ordering,
102                                     _: Ordering)
103                                     -> Result<T, T> {
104                 let read = self.0.get();
105                 if read == current {
106                     self.0.set(new);
107                     Ok(read)
108                 } else {
109                     Err(read)
110                 }
111             }
112         }
113
114         impl<T: Add<Output=T> + Copy> Atomic<T> {
115             pub fn fetch_add(&self, val: T, _: Ordering) -> T {
116                 let old = self.0.get();
117                 self.0.set(old + val);
118                 old
119             }
120         }
121
122         pub type AtomicUsize = Atomic<usize>;
123         pub type AtomicBool = Atomic<bool>;
124         pub type AtomicU32 = Atomic<u32>;
125         pub type AtomicU64 = Atomic<u64>;
126
127         pub use self::serial_join as join;
128         pub use self::serial_scope as scope;
129
130         #[macro_export]
131         macro_rules! parallel {
132             ($($blocks:tt),*) => {
133                 $($blocks)*;
134             }
135         }
136
137         pub use std::iter::Iterator as ParallelIterator;
138
139         pub fn par_iter<T: IntoIterator>(t: T) -> T::IntoIter {
140             t.into_iter()
141         }
142
143         pub type MetadataRef = OwningRef<Box<dyn Erased>, [u8]>;
144
145         pub use std::rc::Rc as Lrc;
146         pub use std::rc::Weak as Weak;
147         pub use std::cell::Ref as ReadGuard;
148         pub use std::cell::Ref as MappedReadGuard;
149         pub use std::cell::RefMut as WriteGuard;
150         pub use std::cell::RefMut as MappedWriteGuard;
151         pub use std::cell::RefMut as LockGuard;
152         pub use std::cell::RefMut as MappedLockGuard;
153
154         use std::cell::RefCell as InnerRwLock;
155         use std::cell::RefCell as InnerLock;
156
157         use std::cell::Cell;
158
159         #[derive(Debug)]
160         pub struct WorkerLocal<T>(OneThread<T>);
161
162         impl<T> WorkerLocal<T> {
163             /// Creates a new worker local where the `initial` closure computes the
164             /// value this worker local should take for each thread in the thread pool.
165             #[inline]
166             pub fn new<F: FnMut(usize) -> T>(mut f: F) -> WorkerLocal<T> {
167                 WorkerLocal(OneThread::new(f(0)))
168             }
169
170             /// Returns the worker-local value for each thread
171             #[inline]
172             pub fn into_inner(self) -> Vec<T> {
173                 vec![OneThread::into_inner(self.0)]
174             }
175         }
176
177         impl<T> Deref for WorkerLocal<T> {
178             type Target = T;
179
180             #[inline(always)]
181             fn deref(&self) -> &T {
182                 &*self.0
183             }
184         }
185
186         pub type MTRef<'a, T> = &'a mut T;
187
188         #[derive(Debug, Default)]
189         pub struct MTLock<T>(T);
190
191         impl<T> MTLock<T> {
192             #[inline(always)]
193             pub fn new(inner: T) -> Self {
194                 MTLock(inner)
195             }
196
197             #[inline(always)]
198             pub fn into_inner(self) -> T {
199                 self.0
200             }
201
202             #[inline(always)]
203             pub fn get_mut(&mut self) -> &mut T {
204                 &mut self.0
205             }
206
207             #[inline(always)]
208             pub fn lock(&self) -> &T {
209                 &self.0
210             }
211
212             #[inline(always)]
213             pub fn lock_mut(&mut self) -> &mut T {
214                 &mut self.0
215             }
216         }
217
218         // FIXME: Probably a bad idea (in the threaded case)
219         impl<T: Clone> Clone for MTLock<T> {
220             #[inline]
221             fn clone(&self) -> Self {
222                 MTLock(self.0.clone())
223             }
224         }
225     } else {
226         pub use std::marker::Send as Send;
227         pub use std::marker::Sync as Sync;
228
229         pub use parking_lot::RwLockReadGuard as ReadGuard;
230         pub use parking_lot::MappedRwLockReadGuard as MappedReadGuard;
231         pub use parking_lot::RwLockWriteGuard as WriteGuard;
232         pub use parking_lot::MappedRwLockWriteGuard as MappedWriteGuard;
233
234         pub use parking_lot::MutexGuard as LockGuard;
235         pub use parking_lot::MappedMutexGuard as MappedLockGuard;
236
237         pub use std::sync::atomic::{AtomicBool, AtomicUsize, AtomicU32, AtomicU64};
238
239         pub use std::sync::Arc as Lrc;
240         pub use std::sync::Weak as Weak;
241
242         pub type MTRef<'a, T> = &'a T;
243
244         #[derive(Debug, Default)]
245         pub struct MTLock<T>(Lock<T>);
246
247         impl<T> MTLock<T> {
248             #[inline(always)]
249             pub fn new(inner: T) -> Self {
250                 MTLock(Lock::new(inner))
251             }
252
253             #[inline(always)]
254             pub fn into_inner(self) -> T {
255                 self.0.into_inner()
256             }
257
258             #[inline(always)]
259             pub fn get_mut(&mut self) -> &mut T {
260                 self.0.get_mut()
261             }
262
263             #[inline(always)]
264             pub fn lock(&self) -> LockGuard<'_, T> {
265                 self.0.lock()
266             }
267
268             #[inline(always)]
269             pub fn lock_mut(&self) -> LockGuard<'_, T> {
270                 self.lock()
271             }
272         }
273
274         use parking_lot::Mutex as InnerLock;
275         use parking_lot::RwLock as InnerRwLock;
276
277         use std;
278         use std::thread;
279         pub use rayon::{join, scope};
280
281         #[macro_export]
282         macro_rules! parallel {
283             (impl [$($c:tt,)*] [$block:tt $(, $rest:tt)*]) => {
284                 parallel!(impl [$block, $($c,)*] [$($rest),*])
285             };
286             (impl [$($blocks:tt,)*] []) => {
287                 ::rustc_data_structures::sync::scope(|s| {
288                     $(
289                         s.spawn(|_| $blocks);
290                     )*
291                 })
292             };
293             ($($blocks:tt),*) => {
294                 // Reverse the order of the blocks since Rayon executes them in reverse order
295                 // when using a single thread. This ensures the execution order matches that
296                 // of a single threaded rustc
297                 parallel!(impl [] [$($blocks),*]);
298             };
299         }
300
301         pub use rayon_core::WorkerLocal;
302
303         pub use rayon::iter::ParallelIterator;
304         use rayon::iter::IntoParallelIterator;
305
306         pub fn par_iter<T: IntoParallelIterator>(t: T) -> T::Iter {
307             t.into_par_iter()
308         }
309
310         pub type MetadataRef = OwningRef<Box<dyn Erased + Send + Sync>, [u8]>;
311
312         /// This makes locks panic if they are already held.
313         /// It is only useful when you are running in a single thread
314         const ERROR_CHECKING: bool = false;
315
316         #[macro_export]
317         macro_rules! rustc_erase_owner {
318             ($v:expr) => {{
319                 let v = $v;
320                 ::rustc_data_structures::sync::assert_send_val(&v);
321                 v.erase_send_sync_owner()
322             }}
323         }
324     }
325 }
326
327 pub fn assert_sync<T: ?Sized + Sync>() {}
328 pub fn assert_send<T: ?Sized + Send>() {}
329 pub fn assert_send_val<T: ?Sized + Send>(_t: &T) {}
330 pub fn assert_send_sync_val<T: ?Sized + Sync + Send>(_t: &T) {}
331
332 pub trait HashMapExt<K, V> {
333     /// Same as HashMap::insert, but it may panic if there's already an
334     /// entry for `key` with a value not equal to `value`
335     fn insert_same(&mut self, key: K, value: V);
336 }
337
338 impl<K: Eq + Hash, V: Eq, S: BuildHasher> HashMapExt<K, V> for HashMap<K, V, S> {
339     fn insert_same(&mut self, key: K, value: V) {
340         self.entry(key).and_modify(|old| assert!(*old == value)).or_insert(value);
341     }
342 }
343
344 /// A type whose inner value can be written once and then will stay read-only
345 // This contains a PhantomData<T> since this type conceptually owns a T outside the Mutex once
346 // initialized. This ensures that Once<T> is Sync only if T is. If we did not have PhantomData<T>
347 // we could send a &Once<Cell<bool>> to multiple threads and call `get` on it to get access
348 // to &Cell<bool> on those threads.
349 pub struct Once<T>(Lock<Option<T>>, PhantomData<T>);
350
351 impl<T> Once<T> {
352     /// Creates an Once value which is uninitialized
353     #[inline(always)]
354     pub fn new() -> Self {
355         Once(Lock::new(None), PhantomData)
356     }
357
358     /// Consumes the value and returns Some(T) if it was initialized
359     #[inline(always)]
360     pub fn into_inner(self) -> Option<T> {
361         self.0.into_inner()
362     }
363
364     /// Tries to initialize the inner value to `value`.
365     /// Returns `None` if the inner value was uninitialized and `value` was consumed setting it
366     /// otherwise if the inner value was already set it returns `value` back to the caller
367     #[inline]
368     pub fn try_set(&self, value: T) -> Option<T> {
369         let mut lock = self.0.lock();
370         if lock.is_some() {
371             return Some(value);
372         }
373         *lock = Some(value);
374         None
375     }
376
377     /// Tries to initialize the inner value to `value`.
378     /// Returns `None` if the inner value was uninitialized and `value` was consumed setting it
379     /// otherwise if the inner value was already set it asserts that `value` is equal to the inner
380     /// value and then returns `value` back to the caller
381     #[inline]
382     pub fn try_set_same(&self, value: T) -> Option<T> where T: Eq {
383         let mut lock = self.0.lock();
384         if let Some(ref inner) = *lock {
385             assert!(*inner == value);
386             return Some(value);
387         }
388         *lock = Some(value);
389         None
390     }
391
392     /// Tries to initialize the inner value to `value` and panics if it was already initialized
393     #[inline]
394     pub fn set(&self, value: T) {
395         assert!(self.try_set(value).is_none());
396     }
397
398     /// Tries to initialize the inner value by calling the closure while ensuring that no-one else
399     /// can access the value in the mean time by holding a lock for the duration of the closure.
400     /// If the value was already initialized the closure is not called and `false` is returned,
401     /// otherwise if the value from the closure initializes the inner value, `true` is returned
402     #[inline]
403     pub fn init_locking<F: FnOnce() -> T>(&self, f: F) -> bool {
404         let mut lock = self.0.lock();
405         if lock.is_some() {
406             return false;
407         }
408         *lock = Some(f());
409         true
410     }
411
412     /// Tries to initialize the inner value by calling the closure without ensuring that no-one
413     /// else can access it. This mean when this is called from multiple threads, multiple
414     /// closures may concurrently be computing a value which the inner value should take.
415     /// Only one of these closures are used to actually initialize the value.
416     /// If some other closure already set the value,
417     /// we return the value our closure computed wrapped in a `Option`.
418     /// If our closure set the value, `None` is returned.
419     /// If the value is already initialized, the closure is not called and `None` is returned.
420     #[inline]
421     pub fn init_nonlocking<F: FnOnce() -> T>(&self, f: F) -> Option<T> {
422         if self.0.lock().is_some() {
423             None
424         } else {
425             self.try_set(f())
426         }
427     }
428
429     /// Tries to initialize the inner value by calling the closure without ensuring that no-one
430     /// else can access it. This mean when this is called from multiple threads, multiple
431     /// closures may concurrently be computing a value which the inner value should take.
432     /// Only one of these closures are used to actually initialize the value.
433     /// If some other closure already set the value, we assert that it our closure computed
434     /// a value equal to the value already set and then
435     /// we return the value our closure computed wrapped in a `Option`.
436     /// If our closure set the value, `None` is returned.
437     /// If the value is already initialized, the closure is not called and `None` is returned.
438     #[inline]
439     pub fn init_nonlocking_same<F: FnOnce() -> T>(&self, f: F) -> Option<T> where T: Eq {
440         if self.0.lock().is_some() {
441             None
442         } else {
443             self.try_set_same(f())
444         }
445     }
446
447     /// Tries to get a reference to the inner value, returns `None` if it is not yet initialized
448     #[inline(always)]
449     pub fn try_get(&self) -> Option<&T> {
450         let lock = &*self.0.lock();
451         if let Some(ref inner) = *lock {
452             // This is safe since we won't mutate the inner value
453             unsafe { Some(&*(inner as *const T)) }
454         } else {
455             None
456         }
457     }
458
459     /// Gets reference to the inner value, panics if it is not yet initialized
460     #[inline(always)]
461     pub fn get(&self) -> &T {
462         self.try_get().expect("value was not set")
463     }
464
465     /// Gets reference to the inner value, panics if it is not yet initialized
466     #[inline(always)]
467     pub fn borrow(&self) -> &T {
468         self.get()
469     }
470 }
471
472 #[derive(Debug)]
473 pub struct Lock<T>(InnerLock<T>);
474
475 impl<T> Lock<T> {
476     #[inline(always)]
477     pub fn new(inner: T) -> Self {
478         Lock(InnerLock::new(inner))
479     }
480
481     #[inline(always)]
482     pub fn into_inner(self) -> T {
483         self.0.into_inner()
484     }
485
486     #[inline(always)]
487     pub fn get_mut(&mut self) -> &mut T {
488         self.0.get_mut()
489     }
490
491     #[cfg(parallel_compiler)]
492     #[inline(always)]
493     pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
494         self.0.try_lock()
495     }
496
497     #[cfg(not(parallel_compiler))]
498     #[inline(always)]
499     pub fn try_lock(&self) -> Option<LockGuard<'_, T>> {
500         self.0.try_borrow_mut().ok()
501     }
502
503     #[cfg(parallel_compiler)]
504     #[inline(always)]
505     pub fn lock(&self) -> LockGuard<'_, T> {
506         if ERROR_CHECKING {
507             self.0.try_lock().expect("lock was already held")
508         } else {
509             self.0.lock()
510         }
511     }
512
513     #[cfg(not(parallel_compiler))]
514     #[inline(always)]
515     pub fn lock(&self) -> LockGuard<'_, T> {
516         self.0.borrow_mut()
517     }
518
519     #[inline(always)]
520     pub fn with_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
521         f(&mut *self.lock())
522     }
523
524     #[inline(always)]
525     pub fn borrow(&self) -> LockGuard<'_, T> {
526         self.lock()
527     }
528
529     #[inline(always)]
530     pub fn borrow_mut(&self) -> LockGuard<'_, T> {
531         self.lock()
532     }
533 }
534
535 impl<T: Default> Default for Lock<T> {
536     #[inline]
537     fn default() -> Self {
538         Lock::new(T::default())
539     }
540 }
541
542 // FIXME: Probably a bad idea
543 impl<T: Clone> Clone for Lock<T> {
544     #[inline]
545     fn clone(&self) -> Self {
546         Lock::new(self.borrow().clone())
547     }
548 }
549
550 #[derive(Debug)]
551 pub struct RwLock<T>(InnerRwLock<T>);
552
553 impl<T> RwLock<T> {
554     #[inline(always)]
555     pub fn new(inner: T) -> Self {
556         RwLock(InnerRwLock::new(inner))
557     }
558
559     #[inline(always)]
560     pub fn into_inner(self) -> T {
561         self.0.into_inner()
562     }
563
564     #[inline(always)]
565     pub fn get_mut(&mut self) -> &mut T {
566         self.0.get_mut()
567     }
568
569     #[cfg(not(parallel_compiler))]
570     #[inline(always)]
571     pub fn read(&self) -> ReadGuard<'_, T> {
572         self.0.borrow()
573     }
574
575     #[cfg(parallel_compiler)]
576     #[inline(always)]
577     pub fn read(&self) -> ReadGuard<'_, T> {
578         if ERROR_CHECKING {
579             self.0.try_read().expect("lock was already held")
580         } else {
581             self.0.read()
582         }
583     }
584
585     #[inline(always)]
586     pub fn with_read_lock<F: FnOnce(&T) -> R, R>(&self, f: F) -> R {
587         f(&*self.read())
588     }
589
590     #[cfg(not(parallel_compiler))]
591     #[inline(always)]
592     pub fn try_write(&self) -> Result<WriteGuard<'_, T>, ()> {
593         self.0.try_borrow_mut().map_err(|_| ())
594     }
595
596     #[cfg(parallel_compiler)]
597     #[inline(always)]
598     pub fn try_write(&self) -> Result<WriteGuard<'_, T>, ()> {
599         self.0.try_write().ok_or(())
600     }
601
602     #[cfg(not(parallel_compiler))]
603     #[inline(always)]
604     pub fn write(&self) -> WriteGuard<'_, T> {
605         self.0.borrow_mut()
606     }
607
608     #[cfg(parallel_compiler)]
609     #[inline(always)]
610     pub fn write(&self) -> WriteGuard<'_, T> {
611         if ERROR_CHECKING {
612             self.0.try_write().expect("lock was already held")
613         } else {
614             self.0.write()
615         }
616     }
617
618     #[inline(always)]
619     pub fn with_write_lock<F: FnOnce(&mut T) -> R, R>(&self, f: F) -> R {
620         f(&mut *self.write())
621     }
622
623     #[inline(always)]
624     pub fn borrow(&self) -> ReadGuard<'_, T> {
625         self.read()
626     }
627
628     #[inline(always)]
629     pub fn borrow_mut(&self) -> WriteGuard<'_, T> {
630         self.write()
631     }
632 }
633
634 // FIXME: Probably a bad idea
635 impl<T: Clone> Clone for RwLock<T> {
636     #[inline]
637     fn clone(&self) -> Self {
638         RwLock::new(self.borrow().clone())
639     }
640 }
641
642 /// A type which only allows its inner value to be used in one thread.
643 /// It will panic if it is used on multiple threads.
644 #[derive(Copy, Clone, Hash, Debug, Eq, PartialEq)]
645 pub struct OneThread<T> {
646     #[cfg(parallel_compiler)]
647     thread: thread::ThreadId,
648     inner: T,
649 }
650
651 #[cfg(parallel_compiler)]
652 unsafe impl<T> std::marker::Sync for OneThread<T> {}
653 #[cfg(parallel_compiler)]
654 unsafe impl<T> std::marker::Send for OneThread<T> {}
655
656 impl<T> OneThread<T> {
657     #[inline(always)]
658     fn check(&self) {
659         #[cfg(parallel_compiler)]
660         assert_eq!(thread::current().id(), self.thread);
661     }
662
663     #[inline(always)]
664     pub fn new(inner: T) -> Self {
665         OneThread {
666             #[cfg(parallel_compiler)]
667             thread: thread::current().id(),
668             inner,
669         }
670     }
671
672     #[inline(always)]
673     pub fn into_inner(value: Self) -> T {
674         value.check();
675         value.inner
676     }
677 }
678
679 impl<T> Deref for OneThread<T> {
680     type Target = T;
681
682     fn deref(&self) -> &T {
683         self.check();
684         &self.inner
685     }
686 }
687
688 impl<T> DerefMut for OneThread<T> {
689     fn deref_mut(&mut self) -> &mut T {
690         self.check();
691         &mut self.inner
692     }
693 }