From 48e3da6d5910d119d4afefd7d06340390db6968d Mon Sep 17 00:00:00 2001 From: tyler Date: Sat, 27 Apr 2019 07:23:31 -0700 Subject: remove dead code: requires_move_before_drop --- src/libstd/sys/redox/fast_thread_local.rs | 4 ---- src/libstd/sys/unix/fast_thread_local.rs | 4 ---- src/libstd/sys/windows/fast_thread_local.rs | 4 ---- 3 files changed, 12 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/redox/fast_thread_local.rs b/src/libstd/sys/redox/fast_thread_local.rs index 1202708a476..fd278bfe39a 100644 --- a/src/libstd/sys/redox/fast_thread_local.rs +++ b/src/libstd/sys/redox/fast_thread_local.rs @@ -105,7 +105,3 @@ pub unsafe extern fn destroy_value(ptr: *mut u8) { ptr::drop_in_place((*ptr).inner.get()); } } - -pub fn requires_move_before_drop() -> bool { - false -} diff --git a/src/libstd/sys/unix/fast_thread_local.rs b/src/libstd/sys/unix/fast_thread_local.rs index 17478dce4fe..c34c2e6e786 100644 --- a/src/libstd/sys/unix/fast_thread_local.rs +++ b/src/libstd/sys/unix/fast_thread_local.rs @@ -82,7 +82,3 @@ pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { } } } - -pub fn requires_move_before_drop() -> bool { - false -} diff --git a/src/libstd/sys/windows/fast_thread_local.rs b/src/libstd/sys/windows/fast_thread_local.rs index 0ccc67e3fd5..31d0bd1e72e 100644 --- a/src/libstd/sys/windows/fast_thread_local.rs +++ b/src/libstd/sys/windows/fast_thread_local.rs @@ -2,7 +2,3 @@ #![cfg(target_thread_local)] pub use crate::sys_common::thread_local::register_dtor_fallback as register_dtor; - -pub fn requires_move_before_drop() -> bool { - false -} -- cgit 1.4.1-3-g733a5 From ae4be16e407061828fe604b1ccbd61181b14a3f1 Mon Sep 17 00:00:00 2001 From: tyler Date: Sat, 27 Apr 2019 07:38:01 -0700 Subject: redox had a copy of fast thread local (oversight?) --- src/libstd/sys/redox/fast_thread_local.rs | 105 +----------------------------- 1 file changed, 1 insertion(+), 104 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/redox/fast_thread_local.rs b/src/libstd/sys/redox/fast_thread_local.rs index fd278bfe39a..67b92d490b2 100644 --- a/src/libstd/sys/redox/fast_thread_local.rs +++ b/src/libstd/sys/redox/fast_thread_local.rs @@ -1,107 +1,4 @@ #![cfg(target_thread_local)] #![unstable(feature = "thread_local_internals", issue = "0")] -use crate::cell::{Cell, UnsafeCell}; -use crate::mem; -use crate::ptr; - - -pub struct Key { - inner: UnsafeCell>, - - // Metadata to keep track of the state of the destructor. Remember that - // these variables are thread-local, not global. - dtor_registered: Cell, - dtor_running: Cell, -} - -unsafe impl Sync for Key { } - -impl Key { - pub const fn new() -> Key { - Key { - inner: UnsafeCell::new(None), - dtor_registered: Cell::new(false), - dtor_running: Cell::new(false) - } - } - - pub fn get(&'static self) -> Option<&'static UnsafeCell>> { - unsafe { - if mem::needs_drop::() && self.dtor_running.get() { - return None - } - self.register_dtor(); - } - Some(&self.inner) - } - - unsafe fn register_dtor(&self) { - if !mem::needs_drop::() || self.dtor_registered.get() { - return - } - - register_dtor(self as *const _ as *mut u8, - destroy_value::); - self.dtor_registered.set(true); - } -} - -pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { - // The fallback implementation uses a vanilla OS-based TLS key to track - // the list of destructors that need to be run for this thread. The key - // then has its own destructor which runs all the other destructors. - // - // The destructor for DTORS is a little special in that it has a `while` - // loop to continuously drain the list of registered destructors. It - // *should* be the case that this loop always terminates because we - // provide the guarantee that a TLS key cannot be set after it is - // flagged for destruction. - use crate::sys_common::thread_local as os; - - static DTORS: os::StaticKey = os::StaticKey::new(Some(run_dtors)); - type List = Vec<(*mut u8, unsafe extern fn(*mut u8))>; - if DTORS.get().is_null() { - let v: Box = box Vec::new(); - DTORS.set(Box::into_raw(v) as *mut u8); - } - let list: &mut List = &mut *(DTORS.get() as *mut List); - list.push((t, dtor)); - - unsafe extern fn run_dtors(mut ptr: *mut u8) { - while !ptr.is_null() { - let list: Box = Box::from_raw(ptr as *mut List); - for (ptr, dtor) in list.into_iter() { - dtor(ptr); - } - ptr = DTORS.get(); - DTORS.set(ptr::null_mut()); - } - } -} - -pub unsafe extern fn destroy_value(ptr: *mut u8) { - let ptr = ptr as *mut Key; - // Right before we run the user destructor be sure to flag the - // destructor as running for this thread so calls to `get` will return - // `None`. - (*ptr).dtor_running.set(true); - - // The macOS implementation of TLS apparently had an odd aspect to it - // where the pointer we have may be overwritten while this destructor - // is running. Specifically if a TLS destructor re-accesses TLS it may - // trigger a re-initialization of all TLS variables, paving over at - // least some destroyed ones with initial values. - // - // This means that if we drop a TLS value in place on macOS that we could - // revert the value to its original state halfway through the - // destructor, which would be bad! - // - // Hence, we use `ptr::read` on macOS (to move to a "safe" location) - // instead of drop_in_place. - if cfg!(target_os = "macos") { - ptr::read((*ptr).inner.get()); - } else { - ptr::drop_in_place((*ptr).inner.get()); - } -} +pub use crate::sys_common::thread_local::register_dtor_fallback as register_dtor; \ No newline at end of file -- cgit 1.4.1-3-g733a5 From 430a091cd80c0e4b6bf44f6a19463a832e566f97 Mon Sep 17 00:00:00 2001 From: tyler Date: Sat, 27 Apr 2019 08:01:32 -0700 Subject: ensure fast thread local lookups occur once per access on macos --- src/libstd/sys/redox/fast_thread_local.rs | 6 +++++- src/libstd/sys/unix/fast_thread_local.rs | 17 +++++++++++++++++ src/libstd/sys/windows/fast_thread_local.rs | 4 ++++ src/libstd/thread/local.rs | 11 ++++++----- 4 files changed, 32 insertions(+), 6 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/redox/fast_thread_local.rs b/src/libstd/sys/redox/fast_thread_local.rs index 67b92d490b2..c34cd575db7 100644 --- a/src/libstd/sys/redox/fast_thread_local.rs +++ b/src/libstd/sys/redox/fast_thread_local.rs @@ -1,4 +1,8 @@ #![cfg(target_thread_local)] #![unstable(feature = "thread_local_internals", issue = "0")] -pub use crate::sys_common::thread_local::register_dtor_fallback as register_dtor; \ No newline at end of file +pub use crate::sys_common::thread_local::register_dtor_fallback as register_dtor; + +pub unsafe fn lookup_once(ptr: *const &T) -> &T { + *ptr +} diff --git a/src/libstd/sys/unix/fast_thread_local.rs b/src/libstd/sys/unix/fast_thread_local.rs index c34c2e6e786..28fb9800541 100644 --- a/src/libstd/sys/unix/fast_thread_local.rs +++ b/src/libstd/sys/unix/fast_thread_local.rs @@ -82,3 +82,20 @@ pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { } } } + +#[cfg(not(target_os = "macos"))] +pub unsafe fn lookup_once(ptr: *const &T) -> &T { + *ptr +} + +#[cfg(target_os = "macos")] +pub unsafe fn lookup_once(ptr: *const &T) -> &T { + // On macos, thread_local lookups can result in terrible code due to + // aggressive rerunning of the macos equivalent of `__tls_get_addr` - four + // lookups per actual reference in user code. + // + // Using a read_volatile on a value holding fast Key's address tricks the + // optimizer into only calling the macos get_addr equivalent once per time + // requested by the user. + crate::ptr::read_volatile(ptr) +} diff --git a/src/libstd/sys/windows/fast_thread_local.rs b/src/libstd/sys/windows/fast_thread_local.rs index 31d0bd1e72e..566d5524fd7 100644 --- a/src/libstd/sys/windows/fast_thread_local.rs +++ b/src/libstd/sys/windows/fast_thread_local.rs @@ -2,3 +2,7 @@ #![cfg(target_thread_local)] pub use crate::sys_common::thread_local::register_dtor_fallback as register_dtor; + +pub unsafe fn lookup_once(ptr: *const &T) -> &T { + *ptr +} diff --git a/src/libstd/thread/local.rs b/src/libstd/thread/local.rs index 0d5e1f2af38..9ce2fcf2352 100644 --- a/src/libstd/thread/local.rs +++ b/src/libstd/thread/local.rs @@ -344,7 +344,7 @@ pub mod fast { use crate::fmt; use crate::mem; use crate::ptr; - use crate::sys::fast_thread_local::register_dtor; + use crate::sys::fast_thread_local::{lookup_once, register_dtor}; pub struct Key { inner: UnsafeCell>, @@ -371,11 +371,12 @@ pub mod fast { } pub unsafe fn get(&self) -> Option<&'static UnsafeCell>> { - if mem::needs_drop::() && self.dtor_running.get() { + let this = lookup_once(&self); + if mem::needs_drop::() && this.dtor_running.get() { return None } - self.register_dtor(); - Some(&*(&self.inner as *const _)) + this.register_dtor(); + Some(&*(&this.inner as *const _)) } unsafe fn register_dtor(&self) { @@ -395,7 +396,7 @@ pub mod fast { // destructor as running for this thread so calls to `get` will return // `None`. (*ptr).dtor_running.set(true); - + ptr::drop_in_place((*ptr).inner.get()); } } -- cgit 1.4.1-3-g733a5 From 7acfb99adc013d4b77c611cfc51bade551205f5a Mon Sep 17 00:00:00 2001 From: tyler Date: Tue, 30 Apr 2019 18:24:38 -0700 Subject: Revert "ensure fast thread local lookups occur once per access on macos" This reverts commit d252f3b77f3b7d4cd59620588f9d026633c05816. --- src/libstd/sys/redox/fast_thread_local.rs | 6 +----- src/libstd/sys/unix/fast_thread_local.rs | 17 ----------------- src/libstd/sys/windows/fast_thread_local.rs | 4 ---- src/libstd/thread/local.rs | 11 +++++------ 4 files changed, 6 insertions(+), 32 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/redox/fast_thread_local.rs b/src/libstd/sys/redox/fast_thread_local.rs index c34cd575db7..67b92d490b2 100644 --- a/src/libstd/sys/redox/fast_thread_local.rs +++ b/src/libstd/sys/redox/fast_thread_local.rs @@ -1,8 +1,4 @@ #![cfg(target_thread_local)] #![unstable(feature = "thread_local_internals", issue = "0")] -pub use crate::sys_common::thread_local::register_dtor_fallback as register_dtor; - -pub unsafe fn lookup_once(ptr: *const &T) -> &T { - *ptr -} +pub use crate::sys_common::thread_local::register_dtor_fallback as register_dtor; \ No newline at end of file diff --git a/src/libstd/sys/unix/fast_thread_local.rs b/src/libstd/sys/unix/fast_thread_local.rs index 28fb9800541..c34c2e6e786 100644 --- a/src/libstd/sys/unix/fast_thread_local.rs +++ b/src/libstd/sys/unix/fast_thread_local.rs @@ -82,20 +82,3 @@ pub unsafe fn register_dtor(t: *mut u8, dtor: unsafe extern fn(*mut u8)) { } } } - -#[cfg(not(target_os = "macos"))] -pub unsafe fn lookup_once(ptr: *const &T) -> &T { - *ptr -} - -#[cfg(target_os = "macos")] -pub unsafe fn lookup_once(ptr: *const &T) -> &T { - // On macos, thread_local lookups can result in terrible code due to - // aggressive rerunning of the macos equivalent of `__tls_get_addr` - four - // lookups per actual reference in user code. - // - // Using a read_volatile on a value holding fast Key's address tricks the - // optimizer into only calling the macos get_addr equivalent once per time - // requested by the user. - crate::ptr::read_volatile(ptr) -} diff --git a/src/libstd/sys/windows/fast_thread_local.rs b/src/libstd/sys/windows/fast_thread_local.rs index 566d5524fd7..31d0bd1e72e 100644 --- a/src/libstd/sys/windows/fast_thread_local.rs +++ b/src/libstd/sys/windows/fast_thread_local.rs @@ -2,7 +2,3 @@ #![cfg(target_thread_local)] pub use crate::sys_common::thread_local::register_dtor_fallback as register_dtor; - -pub unsafe fn lookup_once(ptr: *const &T) -> &T { - *ptr -} diff --git a/src/libstd/thread/local.rs b/src/libstd/thread/local.rs index 9ce2fcf2352..0d5e1f2af38 100644 --- a/src/libstd/thread/local.rs +++ b/src/libstd/thread/local.rs @@ -344,7 +344,7 @@ pub mod fast { use crate::fmt; use crate::mem; use crate::ptr; - use crate::sys::fast_thread_local::{lookup_once, register_dtor}; + use crate::sys::fast_thread_local::register_dtor; pub struct Key { inner: UnsafeCell>, @@ -371,12 +371,11 @@ pub mod fast { } pub unsafe fn get(&self) -> Option<&'static UnsafeCell>> { - let this = lookup_once(&self); - if mem::needs_drop::() && this.dtor_running.get() { + if mem::needs_drop::() && self.dtor_running.get() { return None } - this.register_dtor(); - Some(&*(&this.inner as *const _)) + self.register_dtor(); + Some(&*(&self.inner as *const _)) } unsafe fn register_dtor(&self) { @@ -396,7 +395,7 @@ pub mod fast { // destructor as running for this thread so calls to `get` will return // `None`. (*ptr).dtor_running.set(true); - + ptr::drop_in_place((*ptr).inner.get()); } } -- cgit 1.4.1-3-g733a5 From dfe51a7249e04431526cf3b4779316aabef53cca Mon Sep 17 00:00:00 2001 From: tyler Date: Thu, 2 May 2019 22:40:52 -0700 Subject: restructure thread_local! for better codegen (especially on macos) --- src/libstd/sys/redox/fast_thread_local.rs | 2 +- src/libstd/thread/local.rs | 285 ++++++++++++++++++++---------- src/test/ui/issues/issue-43733.rs | 6 +- src/test/ui/issues/issue-43733.stderr | 8 +- 4 files changed, 195 insertions(+), 106 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/libstd/sys/redox/fast_thread_local.rs b/src/libstd/sys/redox/fast_thread_local.rs index 67b92d490b2..05464787a05 100644 --- a/src/libstd/sys/redox/fast_thread_local.rs +++ b/src/libstd/sys/redox/fast_thread_local.rs @@ -1,4 +1,4 @@ #![cfg(target_thread_local)] #![unstable(feature = "thread_local_internals", issue = "0")] -pub use crate::sys_common::thread_local::register_dtor_fallback as register_dtor; \ No newline at end of file +pub use crate::sys_common::thread_local::register_dtor_fallback as register_dtor; diff --git a/src/libstd/thread/local.rs b/src/libstd/thread/local.rs index 0d5e1f2af38..7ff81bd9a17 100644 --- a/src/libstd/thread/local.rs +++ b/src/libstd/thread/local.rs @@ -2,10 +2,7 @@ #![unstable(feature = "thread_local_internals", issue = "0")] -use crate::cell::UnsafeCell; use crate::fmt; -use crate::hint; -use crate::mem; /// A thread local storage key which owns its contents. /// @@ -92,10 +89,7 @@ pub struct LocalKey { // trivially devirtualizable by LLVM because the value of `inner` never // changes and the constant should be readonly within a crate. This mainly // only runs into problems when TLS statics are exported across crates. - inner: unsafe fn() -> Option<&'static UnsafeCell>>, - - // initialization routine to invoke to create a value - init: fn() -> T, + inner: unsafe fn() -> Option<&'static T>, } #[stable(feature = "std_debug", since = "1.16.0")] @@ -159,10 +153,7 @@ macro_rules! __thread_local_inner { #[inline] fn __init() -> $t { $init } - unsafe fn __getit() -> $crate::option::Option< - &'static $crate::cell::UnsafeCell< - $crate::option::Option<$t>>> - { + unsafe fn __getit() -> $crate::option::Option<&'static $t> { #[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))] static __KEY: $crate::thread::__StaticLocalKeyInner<$t> = $crate::thread::__StaticLocalKeyInner::new(); @@ -182,11 +173,11 @@ macro_rules! __thread_local_inner { static __KEY: $crate::thread::__OsLocalKeyInner<$t> = $crate::thread::__OsLocalKeyInner::new(); - __KEY.get() + __KEY.get(__init) } unsafe { - $crate::thread::LocalKey::new(__getit, __init) + $crate::thread::LocalKey::new(__getit) } } }; @@ -221,11 +212,9 @@ impl LocalKey { #[unstable(feature = "thread_local_internals", reason = "recently added to create a key", issue = "0")] - pub const unsafe fn new(inner: unsafe fn() -> Option<&'static UnsafeCell>>, - init: fn() -> T) -> LocalKey { + pub const unsafe fn new(inner: unsafe fn() -> Option<&'static T>) -> LocalKey { LocalKey { inner, - init, } } @@ -246,37 +235,6 @@ impl LocalKey { after it is destroyed") } - unsafe fn init(&self, slot: &UnsafeCell>) -> &T { - // Execute the initialization up front, *then* move it into our slot, - // just in case initialization fails. - let value = (self.init)(); - let ptr = slot.get(); - - // note that this can in theory just be `*ptr = Some(value)`, but due to - // the compiler will currently codegen that pattern with something like: - // - // ptr::drop_in_place(ptr) - // ptr::write(ptr, Some(value)) - // - // Due to this pattern it's possible for the destructor of the value in - // `ptr` (e.g., if this is being recursively initialized) to re-access - // TLS, in which case there will be a `&` and `&mut` pointer to the same - // value (an aliasing violation). To avoid setting the "I'm running a - // destructor" flag we just use `mem::replace` which should sequence the - // operations a little differently and make this safe to call. - mem::replace(&mut *ptr, Some(value)); - - // After storing `Some` we want to get a reference to the contents of - // what we just stored. While we could use `unwrap` here and it should - // always work it empirically doesn't seem to always get optimized away, - // which means that using something like `try_with` can pull in - // panicking code and cause a large size bloat. - match *ptr { - Some(ref x) => x, - None => hint::unreachable_unchecked(), - } - } - /// Acquires a reference to the value in this TLS key. /// /// This will lazily initialize the value if this thread has not referenced @@ -293,13 +251,68 @@ impl LocalKey { F: FnOnce(&T) -> R, { unsafe { - let slot = (self.inner)().ok_or(AccessError { + let thread_local = (self.inner)().ok_or(AccessError { _private: (), })?; - Ok(f(match *slot.get() { - Some(ref inner) => inner, - None => self.init(slot), - })) + Ok(f(thread_local)) + } + } +} + +mod lazy { + use crate::cell::UnsafeCell; + use crate::mem; + use crate::hint; + + pub struct LazyKeyInner { + inner: UnsafeCell>, + } + + impl LazyKeyInner { + pub const fn new() -> LazyKeyInner { + LazyKeyInner { + inner: UnsafeCell::new(None), + } + } + + #[inline] + pub unsafe fn get(&self) -> Option<&'static T> { + (*self.inner.get()).as_ref() + } + + pub unsafe fn initialize T>(&self, init: F) -> &'static T { + // Execute the initialization up front, *then* move it into our slot, + // just in case initialization fails. + let value = init(); + let ptr = self.inner.get(); + + // note that this can in theory just be `*ptr = Some(value)`, but due to + // the compiler will currently codegen that pattern with something like: + // + // ptr::drop_in_place(ptr) + // ptr::write(ptr, Some(value)) + // + // Due to this pattern it's possible for the destructor of the value in + // `ptr` (e.g., if this is being recursively initialized) to re-access + // TLS, in which case there will be a `&` and `&mut` pointer to the same + // value (an aliasing violation). To avoid setting the "I'm running a + // destructor" flag we just use `mem::replace` which should sequence the + // operations a little differently and make this safe to call. + mem::replace(&mut *ptr, Some(value)); + + // After storing `Some` we want to get a reference to the contents of + // what we just stored. While we could use `unwrap` here and it should + // always work it empirically doesn't seem to always get optimized away, + // which means that using something like `try_with` can pull in + // panicking code and cause a large size bloat. + match *ptr { + Some(ref x) => x, + None => hint::unreachable_unchecked(), + } + } + + pub unsafe fn take(&mut self) -> Option { + (*self.inner.get()).take() } } } @@ -309,11 +322,12 @@ impl LocalKey { #[doc(hidden)] #[cfg(all(target_arch = "wasm32", not(target_feature = "atomics")))] pub mod statik { + use super::lazy::LazyKeyInner; use crate::cell::UnsafeCell; use crate::fmt; pub struct Key { - inner: UnsafeCell>, + inner: LazyKeyInner, } unsafe impl Sync for Key { } @@ -327,12 +341,17 @@ pub mod statik { impl Key { pub const fn new() -> Key { Key { - inner: UnsafeCell::new(None), + inner: LazyKeyInner::new(), } } - pub unsafe fn get(&self) -> Option<&'static UnsafeCell>> { - Some(&*(&self.inner as *const _)) + #[inline] + pub unsafe fn get(&self, init: fn() -> T) -> Option<&'static T> { + let value = match self.inner.get() { + Some(ref value) => value, + None => self.inner.initialize(init), + }; + Some(value) } } } @@ -340,19 +359,33 @@ pub mod statik { #[doc(hidden)] #[cfg(target_thread_local)] pub mod fast { - use crate::cell::{Cell, UnsafeCell}; + use super::lazy::LazyKeyInner; + use crate::cell::Cell; use crate::fmt; use crate::mem; - use crate::ptr; use crate::sys::fast_thread_local::register_dtor; + #[derive(Copy, Clone)] + enum DtorState { + Unregistered, + Registered, + RunningOrHasRun, + } + pub struct Key { - inner: UnsafeCell>, + // If `LazyKeyInner::get` returns `None`, that indicates either: + // * The value has never been initialized + // * The value is being recursively initialized + // * The value has already been destroyed or is being destroyed + // To determine which kind of `None`, check `dtor_state`. + // + // This is very optimizer friendly for the fast path - initialized but + // not yet dropped. + inner: LazyKeyInner, // Metadata to keep track of the state of the destructor. Remember that - // these variables are thread-local, not global. - dtor_registered: Cell, - dtor_running: Cell, + // this variable is thread-local, not global. + dtor_state: Cell, } impl fmt::Debug for Key { @@ -364,45 +397,84 @@ pub mod fast { impl Key { pub const fn new() -> Key { Key { - inner: UnsafeCell::new(None), - dtor_registered: Cell::new(false), - dtor_running: Cell::new(false) + inner: LazyKeyInner::new(), + dtor_state: Cell::new(DtorState::Unregistered), } } - pub unsafe fn get(&self) -> Option<&'static UnsafeCell>> { - if mem::needs_drop::() && self.dtor_running.get() { - return None + #[inline] + pub unsafe fn get T>(&self, init: F) -> Option<&'static T> { + match self.inner.get() { + Some(val) => Some(val), + None => { + if mem::needs_drop::() { + self.try_initialize_drop(init) + } else { + Some(self.try_initialize_nodrop(init)) + } + } } - self.register_dtor(); - Some(&*(&self.inner as *const _)) } - unsafe fn register_dtor(&self) { - if !mem::needs_drop::() || self.dtor_registered.get() { - return + // `try_initialize_nodrop` is only called once per fast thread local + // variable, except in corner cases where it is being recursively + // initialized. + // + // Macos: Inlining this function causes two `tlv_get_addr` calls to be + // performed for every call to `Key::get`. + // LLVM issue: https://bugs.llvm.org/show_bug.cgi?id=41722 + #[inline(never)] + #[cold] + unsafe fn try_initialize_nodrop T>(&self, init: F) -> &'static T { + self.inner.initialize(init) + } + + // `try_initialize_drop` is only called once per fast thread local + // variable, except in corner cases where thread_local dtors reference + // other thread_local's, or it is being recursively initialized. + #[inline(never)] + #[cold] + unsafe fn try_initialize_drop T>(&self, init: F) -> Option<&'static T> { + // We don't put a `needs_drop` check around this and call it a day + // because this function is not inlined. Unwrapping code gets + // generated for callers of `LocalKey::with` even if we always + // return `Some` here. + match self.dtor_state.get() { + DtorState::Unregistered => { + // dtor registration happens before initialization. + register_dtor(self as *const _ as *mut u8, + destroy_value::); + self.dtor_state.set(DtorState::Registered); + } + DtorState::Registered => { + // recursively initialized + } + DtorState::RunningOrHasRun => { + return None + } } - register_dtor(self as *const _ as *mut u8, - destroy_value::); - self.dtor_registered.set(true); + Some(self.inner.initialize(init)) } } unsafe extern fn destroy_value(ptr: *mut u8) { let ptr = ptr as *mut Key; - // Right before we run the user destructor be sure to flag the - // destructor as running for this thread so calls to `get` will return - // `None`. - (*ptr).dtor_running.set(true); - - ptr::drop_in_place((*ptr).inner.get()); + + // Right before we run the user destructor be sure to set the + // `Option` to `None`, and `dtor_state` to `RunningOrHasRun`. This + // causes future calls to `get` to run `try_initialize_drop` again, + // which will now fail, and return `None`. + let value = (*ptr).inner.take(); + (*ptr).dtor_state.set(DtorState::RunningOrHasRun); + drop(value); } } #[doc(hidden)] pub mod os { - use crate::cell::{Cell, UnsafeCell}; + use super::lazy::LazyKeyInner; + use crate::cell::Cell; use crate::fmt; use crate::marker; use crate::ptr; @@ -423,8 +495,8 @@ pub mod os { unsafe impl Sync for Key { } struct Value { + inner: LazyKeyInner, key: &'static Key, - value: UnsafeCell>, } impl Key { @@ -435,24 +507,43 @@ pub mod os { } } - pub unsafe fn get(&'static self) -> Option<&'static UnsafeCell>> { + pub unsafe fn get(&'static self, init: fn() -> T) -> Option<&'static T> { let ptr = self.os.get() as *mut Value; - if !ptr.is_null() { - if ptr as usize == 1 { - return None + if ptr as usize > 1 { + match (*ptr).inner.get() { + Some(ref value) => return Some(value), + None => {}, } - return Some(&(*ptr).value); } + self.try_initialize(init) + } - // If the lookup returned null, we haven't initialized our own - // local copy, so do that now. - let ptr: Box> = box Value { - key: self, - value: UnsafeCell::new(None), + // `try_initialize` is only called once per os thread local variable, + // except in corner cases where thread_local dtors reference other + // thread_local's, or it is being recursively initialized. + unsafe fn try_initialize(&'static self, init: fn() -> T) -> Option<&'static T> { + let ptr = self.os.get() as *mut Value; + if ptr as usize == 1 { + // destructor is running + return None + } + + let ptr = if ptr.is_null() { + // If the lookup returned null, we haven't initialized our own + // local copy, so do that now. + let ptr: Box> = box Value { + inner: LazyKeyInner::new(), + key: self, + }; + let ptr = Box::into_raw(ptr); + self.os.set(ptr as *mut u8); + ptr + } else { + // recursive initialization + ptr }; - let ptr = Box::into_raw(ptr); - self.os.set(ptr as *mut u8); - Some(&(*ptr).value) + + Some((*ptr).inner.initialize(init)) } } diff --git a/src/test/ui/issues/issue-43733.rs b/src/test/ui/issues/issue-43733.rs index 91192e3360c..ba599ff7ce4 100644 --- a/src/test/ui/issues/issue-43733.rs +++ b/src/test/ui/issues/issue-43733.rs @@ -13,11 +13,9 @@ static __KEY: std::thread::__FastLocalKeyInner = static __KEY: std::thread::__OsLocalKeyInner = std::thread::__OsLocalKeyInner::new(); -fn __getit() -> std::option::Option< - &'static std::cell::UnsafeCell< - std::option::Option>> +fn __getit(init: fn() -> Foo) -> std::option::Option<&'static Foo> { - __KEY.get() //~ ERROR call to unsafe function is unsafe + __KEY.get(init) //~ ERROR call to unsafe function is unsafe } static FOO: std::thread::LocalKey = diff --git a/src/test/ui/issues/issue-43733.stderr b/src/test/ui/issues/issue-43733.stderr index c48f9baf271..0ea931d7fb6 100644 --- a/src/test/ui/issues/issue-43733.stderr +++ b/src/test/ui/issues/issue-43733.stderr @@ -1,13 +1,13 @@ error[E0133]: call to unsafe function is unsafe and requires unsafe function or block - --> $DIR/issue-43733.rs:20:5 + --> $DIR/issue-43733.rs:18:5 | -LL | __KEY.get() - | ^^^^^^^^^^^ call to unsafe function +LL | __KEY.get(init) + | ^^^^^^^^^^^^^^^ call to unsafe function | = note: consult the function's documentation for information on how to avoid undefined behavior error[E0133]: call to unsafe function is unsafe and requires unsafe function or block - --> $DIR/issue-43733.rs:24:5 + --> $DIR/issue-43733.rs:22:5 | LL | std::thread::LocalKey::new(__getit, Default::default); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ call to unsafe function -- cgit 1.4.1-3-g733a5 From 7d69d4ced23c446d6af341e3f9dc031a302150fc Mon Sep 17 00:00:00 2001 From: Lzu Tao Date: Mon, 17 Jun 2019 10:52:37 +0000 Subject: Make use of `ptr::null(_mut)` instead of casting zero --- src/bootstrap/job.rs | 9 +++++---- src/bootstrap/util.rs | 2 +- src/libarena/lib.rs | 8 ++++---- src/libpanic_unwind/dummy.rs | 2 +- src/libpanic_unwind/seh.rs | 6 +++--- src/librustc_errors/lock.rs | 2 +- src/librustc_metadata/dynamic_lib.rs | 2 +- src/librustc_typeck/error_codes.rs | 6 +++--- src/libstd/sys/wasi/args.rs | 2 +- src/libstd/sys/wasm/thread_local_atomics.rs | 2 +- src/test/run-make-fulldeps/alloc-extern-crates/fakealloc.rs | 6 ++++-- src/test/run-pass/cast.rs | 2 +- src/test/run-pass/cleanup-shortcircuit.rs | 2 +- src/test/run-pass/consts/const-block.rs | 4 ++-- src/test/run-pass/issues/issue-13259-windows-tcb-trash.rs | 4 ++-- src/test/run-pass/issues/issue-19001.rs | 2 +- src/test/run-pass/issues/issue-39367.rs | 2 +- src/test/run-pass/issues/issue-46069.rs | 2 +- src/test/run-pass/structs-enums/enum-null-pointer-opt.rs | 2 +- src/test/ui/casts-issue-46365.rs | 2 +- src/test/ui/consts/const-eval/ice-generic-assoc-const.rs | 2 +- src/test/ui/consts/min_const_fn/min_const_fn.rs | 4 ++-- src/test/ui/consts/min_const_fn/min_const_fn_unsafe.rs | 4 ++-- src/test/ui/derived-errors/issue-31997.rs | 2 +- src/test/ui/derived-errors/issue-31997.stderr | 2 +- src/test/ui/error-codes/E0605.rs | 2 +- src/test/ui/error-codes/E0607.rs | 2 +- src/test/ui/error-festival.rs | 2 +- src/test/ui/issues/issue-17458.rs | 2 +- src/test/ui/issues/issue-17458.stderr | 4 ++-- src/test/ui/issues/issue-20801.rs | 4 ++-- src/test/ui/issues/issue-22034.rs | 2 +- src/test/ui/mismatched_types/cast-rfc0401.rs | 6 +++--- 33 files changed, 55 insertions(+), 52 deletions(-) (limited to 'src/libstd/sys') diff --git a/src/bootstrap/job.rs b/src/bootstrap/job.rs index df492e0fdfd..6867d62a480 100644 --- a/src/bootstrap/job.rs +++ b/src/bootstrap/job.rs @@ -32,6 +32,7 @@ use std::env; use std::io; use std::mem; +use std::ptr; use crate::Build; type HANDLE = *mut u8; @@ -118,8 +119,8 @@ pub unsafe fn setup(build: &mut Build) { SetErrorMode(mode & !SEM_NOGPFAULTERRORBOX); // Create a new job object for us to use - let job = CreateJobObjectW(0 as *mut _, 0 as *const _); - assert!(job != 0 as *mut _, "{}", io::Error::last_os_error()); + let job = CreateJobObjectW(ptr::null_mut(), ptr::null()); + assert!(!job.is_null(), "{}", io::Error::last_os_error()); // Indicate that when all handles to the job object are gone that all // process in the object should be killed. Note that this includes our @@ -166,8 +167,8 @@ pub unsafe fn setup(build: &mut Build) { }; let parent = OpenProcess(PROCESS_DUP_HANDLE, FALSE, pid.parse().unwrap()); - assert!(parent != 0 as *mut _, "{}", io::Error::last_os_error()); - let mut parent_handle = 0 as *mut _; + assert!(!parent.is_null(), "{}", io::Error::last_os_error()); + let mut parent_handle = ptr::null_mut(); let r = DuplicateHandle(GetCurrentProcess(), job, parent, &mut parent_handle, 0, FALSE, DUPLICATE_SAME_ACCESS); diff --git a/src/bootstrap/util.rs b/src/bootstrap/util.rs index 9f684678bb0..47f5edd1563 100644 --- a/src/bootstrap/util.rs +++ b/src/bootstrap/util.rs @@ -209,7 +209,7 @@ pub fn symlink_dir(config: &Config, src: &Path, dest: &Path) -> io::Result<()> { let h = CreateFileW(path.as_ptr(), GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, - 0 as *mut _, + ptr::null_mut(), OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT | FILE_FLAG_BACKUP_SEMANTICS, ptr::null_mut()); diff --git a/src/libarena/lib.rs b/src/libarena/lib.rs index e2a249c8e61..3d16e335cd8 100644 --- a/src/libarena/lib.rs +++ b/src/libarena/lib.rs @@ -114,8 +114,8 @@ impl Default for TypedArena { TypedArena { // We set both `ptr` and `end` to 0 so that the first call to // alloc() will trigger a grow(). - ptr: Cell::new(0 as *mut T), - end: Cell::new(0 as *mut T), + ptr: Cell::new(ptr::null_mut()), + end: Cell::new(ptr::null_mut()), chunks: RefCell::new(vec![]), _own: PhantomData, } @@ -370,8 +370,8 @@ impl Default for DroplessArena { #[inline] fn default() -> DroplessArena { DroplessArena { - ptr: Cell::new(0 as *mut u8), - end: Cell::new(0 as *mut u8), + ptr: Cell::new(ptr::null_mut()), + end: Cell::new(ptr::null_mut()), chunks: Default::default(), } } diff --git a/src/libpanic_unwind/dummy.rs b/src/libpanic_unwind/dummy.rs index 3a00d637665..86756326387 100644 --- a/src/libpanic_unwind/dummy.rs +++ b/src/libpanic_unwind/dummy.rs @@ -7,7 +7,7 @@ use core::any::Any; use core::intrinsics; pub fn payload() -> *mut u8 { - 0 as *mut u8 + core::ptr::null_mut() } pub unsafe fn cleanup(_ptr: *mut u8) -> Box { diff --git a/src/libpanic_unwind/seh.rs b/src/libpanic_unwind/seh.rs index 996fdb931ef..809e4619812 100644 --- a/src/libpanic_unwind/seh.rs +++ b/src/libpanic_unwind/seh.rs @@ -104,7 +104,7 @@ mod imp { pub const NAME2: [u8; 7] = [b'.', b'P', b'A', b'X', 0, 0, 0]; macro_rules! ptr { - (0) => (0 as *mut u8); + (0) => (core::ptr::null_mut()); ($e:expr) => ($e as *mut u8); } } @@ -223,13 +223,13 @@ extern "C" { #[cfg_attr(not(test), lang = "msvc_try_filter")] static mut TYPE_DESCRIPTOR1: _TypeDescriptor = _TypeDescriptor { pVFTable: unsafe { &TYPE_INFO_VTABLE } as *const _ as *const _, - spare: 0 as *mut _, + spare: core::ptr::null_mut(), name: imp::NAME1, }; static mut TYPE_DESCRIPTOR2: _TypeDescriptor = _TypeDescriptor { pVFTable: unsafe { &TYPE_INFO_VTABLE } as *const _ as *const _, - spare: 0 as *mut _, + spare: core::ptr::null_mut(), name: imp::NAME2, }; diff --git a/src/librustc_errors/lock.rs b/src/librustc_errors/lock.rs index f731791efe6..25a27d2cbd8 100644 --- a/src/librustc_errors/lock.rs +++ b/src/librustc_errors/lock.rs @@ -64,7 +64,7 @@ pub fn acquire_global_lock(name: &str) -> Box { // // This will silently create one if it doesn't already exist, or it'll // open up a handle to one if it already exists. - let mutex = CreateMutexA(0 as *mut _, 0, cname.as_ptr() as *const u8); + let mutex = CreateMutexA(std::ptr::null_mut(), 0, cname.as_ptr() as *const u8); if mutex.is_null() { panic!("failed to create global mutex named `{}`: {}", name, diff --git a/src/librustc_metadata/dynamic_lib.rs b/src/librustc_metadata/dynamic_lib.rs index 76a9a3405bd..4c279361ff5 100644 --- a/src/librustc_metadata/dynamic_lib.rs +++ b/src/librustc_metadata/dynamic_lib.rs @@ -115,7 +115,7 @@ mod dl { { use std::sync::{Mutex, Once}; static INIT: Once = Once::new(); - static mut LOCK: *mut Mutex<()> = 0 as *mut _; + static mut LOCK: *mut Mutex<()> = ptr::null_mut(); unsafe { INIT.call_once(|| { LOCK = Box::into_raw(Box::new(Mutex::new(()))); diff --git a/src/librustc_typeck/error_codes.rs b/src/librustc_typeck/error_codes.rs index 0b618cdf1db..b5b214d4aff 100644 --- a/src/librustc_typeck/error_codes.rs +++ b/src/librustc_typeck/error_codes.rs @@ -3904,7 +3904,7 @@ x as Vec; // error: non-primitive cast: `u8` as `std::vec::Vec` // Another example -let v = 0 as *const u8; // So here, `v` is a `*const u8`. +let v = core::ptr::null::(); // So here, `v` is a `*const u8`. v as &u8; // error: non-primitive cast: `*const u8` as `&u8` ``` @@ -3914,7 +3914,7 @@ Only primitive types can be cast into each other. Examples: let x = 0u8; x as u32; // ok! -let v = 0 as *const u8; +let v = core::ptr::null::(); v as *const i8; // ok! ``` @@ -3954,7 +3954,7 @@ A cast between a thin and a fat pointer was attempted. Erroneous code example: ```compile_fail,E0607 -let v = 0 as *const u8; +let v = core::ptr::null::(); v as *const [u8]; ``` diff --git a/src/libstd/sys/wasi/args.rs b/src/libstd/sys/wasi/args.rs index 9c8e59e4fb5..8b4b354d9fc 100644 --- a/src/libstd/sys/wasi/args.rs +++ b/src/libstd/sys/wasi/args.rs @@ -32,7 +32,7 @@ fn maybe_args() -> io::Result { let (mut argc, mut argv_buf_size) = (0, 0); cvt_wasi(libc::__wasi_args_sizes_get(&mut argc, &mut argv_buf_size))?; - let mut argc = vec![0 as *mut libc::c_char; argc]; + let mut argc = vec![core::ptr::null_mut::(); argc]; let mut argv_buf = vec![0; argv_buf_size]; cvt_wasi(libc::__wasi_args_get(argc.as_mut_ptr(), argv_buf.as_mut_ptr()))?; diff --git a/src/libstd/sys/wasm/thread_local_atomics.rs b/src/libstd/sys/wasm/thread_local_atomics.rs index b408ad0d5c1..3dc0bb24553 100644 --- a/src/libstd/sys/wasm/thread_local_atomics.rs +++ b/src/libstd/sys/wasm/thread_local_atomics.rs @@ -11,7 +11,7 @@ struct ThreadControlBlock { impl ThreadControlBlock { fn new() -> ThreadControlBlock { ThreadControlBlock { - keys: [0 as *mut u8; MAX_KEYS], + keys: [core::ptr::null_mut(); MAX_KEYS], } } diff --git a/src/test/run-make-fulldeps/alloc-extern-crates/fakealloc.rs b/src/test/run-make-fulldeps/alloc-extern-crates/fakealloc.rs index 625c3afab92..d4612c325d5 100644 --- a/src/test/run-make-fulldeps/alloc-extern-crates/fakealloc.rs +++ b/src/test/run-make-fulldeps/alloc-extern-crates/fakealloc.rs @@ -2,14 +2,16 @@ #![no_std] #[inline] -pub unsafe fn allocate(_size: usize, _align: usize) -> *mut u8 { 0 as *mut u8 } +pub unsafe fn allocate(_size: usize, _align: usize) -> *mut u8 { + core::ptr::null_mut() +} #[inline] pub unsafe fn deallocate(_ptr: *mut u8, _old_size: usize, _align: usize) { } #[inline] pub unsafe fn reallocate(_ptr: *mut u8, _old_size: usize, _size: usize, _align: usize) -> *mut u8 { - 0 as *mut u8 + core::ptr::null_mut() } #[inline] diff --git a/src/test/run-pass/cast.rs b/src/test/run-pass/cast.rs index 37add8446f4..c7977f461df 100644 --- a/src/test/run-pass/cast.rs +++ b/src/test/run-pass/cast.rs @@ -15,5 +15,5 @@ pub fn main() { // Test that `_` is correctly inferred. let x = &"hello"; let mut y = x as *const _; - y = 0 as *const _; + y = core::ptr::null_mut(); } diff --git a/src/test/run-pass/cleanup-shortcircuit.rs b/src/test/run-pass/cleanup-shortcircuit.rs index 118fa0083ab..6e67a276d4f 100644 --- a/src/test/run-pass/cleanup-shortcircuit.rs +++ b/src/test/run-pass/cleanup-shortcircuit.rs @@ -16,6 +16,6 @@ pub fn main() { if args.len() >= 2 && args[1] == "signal" { // Raise a segfault. - unsafe { *(0 as *mut isize) = 0; } + unsafe { *std::ptr::null_mut::() = 0; } } } diff --git a/src/test/run-pass/consts/const-block.rs b/src/test/run-pass/consts/const-block.rs index 012523a61ef..7172a34c8cf 100644 --- a/src/test/run-pass/consts/const-block.rs +++ b/src/test/run-pass/consts/const-block.rs @@ -21,7 +21,7 @@ static BLOCK_EXPLICIT_UNIT: () = { () }; static BLOCK_IMPLICIT_UNIT: () = { }; static BLOCK_FLOAT: f64 = { 1.0 }; static BLOCK_ENUM: Option = { Some(100) }; -static BLOCK_STRUCT: Foo = { Foo { a: 12, b: 0 as *const () } }; +static BLOCK_STRUCT: Foo = { Foo { a: 12, b: std::ptr::null::<()>() } }; static BLOCK_UNSAFE: usize = unsafe { 1000 }; static BLOCK_FN_INFERRED: fn(usize) -> usize = { foo }; @@ -36,7 +36,7 @@ pub fn main() { assert_eq!(BLOCK_IMPLICIT_UNIT, ()); assert_eq!(BLOCK_FLOAT, 1.0_f64); assert_eq!(BLOCK_STRUCT.a, 12); - assert_eq!(BLOCK_STRUCT.b, 0 as *const ()); + assert_eq!(BLOCK_STRUCT.b, std::ptr::null::<()>()); assert_eq!(BLOCK_ENUM, Some(100)); assert_eq!(BLOCK_UNSAFE, 1000); assert_eq!(BLOCK_FN_INFERRED(300), 300); diff --git a/src/test/run-pass/issues/issue-13259-windows-tcb-trash.rs b/src/test/run-pass/issues/issue-13259-windows-tcb-trash.rs index d79d34de571..740e7780de6 100644 --- a/src/test/run-pass/issues/issue-13259-windows-tcb-trash.rs +++ b/src/test/run-pass/issues/issue-13259-windows-tcb-trash.rs @@ -23,8 +23,8 @@ mod imp { pub fn test() { let mut buf: [u16; 50] = [0; 50]; let ret = unsafe { - FormatMessageW(0x1000, 0 as *mut _, 1, 0x400, - buf.as_mut_ptr(), buf.len() as u32, 0 as *const _) + FormatMessageW(0x1000, core::ptr::null_mut(), 1, 0x400, + buf.as_mut_ptr(), buf.len() as u32, core::ptr::null()) }; // On some 32-bit Windowses (Win7-8 at least) this will panic with segmented // stacks taking control of pvArbitrary diff --git a/src/test/run-pass/issues/issue-19001.rs b/src/test/run-pass/issues/issue-19001.rs index 85f7a84ac29..76c380c2fc9 100644 --- a/src/test/run-pass/issues/issue-19001.rs +++ b/src/test/run-pass/issues/issue-19001.rs @@ -7,5 +7,5 @@ struct Loopy { } fn main() { - let _t = Loopy { ptr: 0 as *mut _ }; + let _t = Loopy { ptr: core::ptr::null_mut() }; } diff --git a/src/test/run-pass/issues/issue-39367.rs b/src/test/run-pass/issues/issue-39367.rs index 2e2b480e066..8314be3d14c 100644 --- a/src/test/run-pass/issues/issue-39367.rs +++ b/src/test/run-pass/issues/issue-39367.rs @@ -15,7 +15,7 @@ fn arena() -> &'static ArenaSet> { fn require_sync(_: &T) { } unsafe fn __stability() -> &'static ArenaSet> { use std::mem::transmute; - static mut DATA: *const ArenaSet> = 0 as *const ArenaSet>; + static mut DATA: *const ArenaSet> = std::ptr::null_mut(); static mut ONCE: Once = Once::new(); ONCE.call_once(|| { diff --git a/src/test/run-pass/issues/issue-46069.rs b/src/test/run-pass/issues/issue-46069.rs index fba2a2ebe3b..1d4f789828d 100644 --- a/src/test/run-pass/issues/issue-46069.rs +++ b/src/test/run-pass/issues/issue-46069.rs @@ -17,7 +17,7 @@ fn copy_ex() { } fn main() { - let _f = 0 as *mut >> as Iterator>::Item; + let _f: *mut >> as Iterator>::Item = std::ptr::null_mut(); copy_ex(); } diff --git a/src/test/run-pass/structs-enums/enum-null-pointer-opt.rs b/src/test/run-pass/structs-enums/enum-null-pointer-opt.rs index f871c218558..32fdbf620a9 100644 --- a/src/test/run-pass/structs-enums/enum-null-pointer-opt.rs +++ b/src/test/run-pass/structs-enums/enum-null-pointer-opt.rs @@ -38,7 +38,7 @@ fn main() { // The optimization can't apply to raw pointers or unions with a ZST field. assert!(size_of::>() != size_of::<*const isize>()); - assert!(Some(0 as *const isize).is_some()); // Can't collapse None to null + assert!(Some(std::ptr::null::()).is_some()); // Can't collapse None to null assert_ne!(size_of::(), size_of::>>()); assert_ne!(size_of::<&str>(), size_of::>>()); assert_ne!(size_of::>(), size_of::>>>()); diff --git a/src/test/ui/casts-issue-46365.rs b/src/test/ui/casts-issue-46365.rs index 2e7c26b54e4..3d0fea245c0 100644 --- a/src/test/ui/casts-issue-46365.rs +++ b/src/test/ui/casts-issue-46365.rs @@ -3,5 +3,5 @@ struct Lorem { } fn main() { - let _foo: *mut Lorem = 0 as *mut _; // no error here + let _foo: *mut Lorem = core::ptr::null_mut(); // no error here } diff --git a/src/test/ui/consts/const-eval/ice-generic-assoc-const.rs b/src/test/ui/consts/const-eval/ice-generic-assoc-const.rs index e92de84c279..2ad1a633d12 100644 --- a/src/test/ui/consts/const-eval/ice-generic-assoc-const.rs +++ b/src/test/ui/consts/const-eval/ice-generic-assoc-const.rs @@ -7,7 +7,7 @@ pub trait Nullable { } impl Nullable for *const T { - const NULL: Self = 0 as *const T; + const NULL: Self = core::ptr::null::(); fn is_null(&self) -> bool { *self == Self::NULL diff --git a/src/test/ui/consts/min_const_fn/min_const_fn.rs b/src/test/ui/consts/min_const_fn/min_const_fn.rs index 40e7107e4a1..9523fcbfc60 100644 --- a/src/test/ui/consts/min_const_fn/min_const_fn.rs +++ b/src/test/ui/consts/min_const_fn/min_const_fn.rs @@ -69,8 +69,8 @@ const fn i32_ops3(c: i32, d: i32) -> bool { c != d } const fn i32_ops4(c: i32, d: i32) -> i32 { c + d } const fn char_cast(u: u8) -> char { u as char } const unsafe fn ret_i32_no_unsafe() -> i32 { 42 } -const unsafe fn ret_null_ptr_no_unsafe() -> *const T { 0 as *const T } -const unsafe fn ret_null_mut_ptr_no_unsafe() -> *mut T { 0 as *mut T } +const unsafe fn ret_null_ptr_no_unsafe() -> *const T { core::ptr::null() } +const unsafe fn ret_null_mut_ptr_no_unsafe() -> *mut T { core::ptr::null_mut() } // not ok const fn foo11(t: T) -> T { t } diff --git a/src/test/ui/consts/min_const_fn/min_const_fn_unsafe.rs b/src/test/ui/consts/min_const_fn/min_const_fn_unsafe.rs index e25dafa74d7..0152561aefc 100644 --- a/src/test/ui/consts/min_const_fn/min_const_fn_unsafe.rs +++ b/src/test/ui/consts/min_const_fn/min_const_fn_unsafe.rs @@ -3,8 +3,8 @@ //------------------------------------------------------------------------------ const unsafe fn ret_i32_no_unsafe() -> i32 { 42 } -const unsafe fn ret_null_ptr_no_unsafe() -> *const T { 0 as *const T } -const unsafe fn ret_null_mut_ptr_no_unsafe() -> *mut T { 0 as *mut T } +const unsafe fn ret_null_ptr_no_unsafe() -> *const T { std::ptr::null() } +const unsafe fn ret_null_mut_ptr_no_unsafe() -> *mut T { std::ptr::null_mut() } const fn no_unsafe() { unsafe {} } const fn call_unsafe_const_fn() -> i32 { diff --git a/src/test/ui/derived-errors/issue-31997.rs b/src/test/ui/derived-errors/issue-31997.rs index 025e9100e23..cfdee26c559 100644 --- a/src/test/ui/derived-errors/issue-31997.rs +++ b/src/test/ui/derived-errors/issue-31997.rs @@ -10,7 +10,7 @@ fn closure(x: F) -> Result } fn foo() -> Result<(), ()> { - try!(closure(|| bar(0 as *mut _))); //~ ERROR cannot find function `bar` in this scope + try!(closure(|| bar(core::ptr::null_mut()))); //~ ERROR cannot find function `bar` in this scope Ok(()) } diff --git a/src/test/ui/derived-errors/issue-31997.stderr b/src/test/ui/derived-errors/issue-31997.stderr index dbceba046e2..e9fe0d3971e 100644 --- a/src/test/ui/derived-errors/issue-31997.stderr +++ b/src/test/ui/derived-errors/issue-31997.stderr @@ -1,7 +1,7 @@ error[E0425]: cannot find function `bar` in this scope --> $DIR/issue-31997.rs:13:21 | -LL | try!(closure(|| bar(0 as *mut _))); +LL | try!(closure(|| bar(core::ptr::null_mut()))); | ^^^ not found in this scope error: aborting due to previous error diff --git a/src/test/ui/error-codes/E0605.rs b/src/test/ui/error-codes/E0605.rs index 0e86e367e83..cfbf1aa2bd7 100644 --- a/src/test/ui/error-codes/E0605.rs +++ b/src/test/ui/error-codes/E0605.rs @@ -2,6 +2,6 @@ fn main() { let x = 0u8; x as Vec; //~ ERROR E0605 - let v = 0 as *const u8; + let v = std::ptr::null::(); v as &u8; //~ ERROR E0605 } diff --git a/src/test/ui/error-codes/E0607.rs b/src/test/ui/error-codes/E0607.rs index ad9f8709b07..65001c471cb 100644 --- a/src/test/ui/error-codes/E0607.rs +++ b/src/test/ui/error-codes/E0607.rs @@ -1,4 +1,4 @@ fn main() { - let v = 0 as *const u8; + let v = core::ptr::null::(); v as *const [u8]; //~ ERROR E0607 } diff --git a/src/test/ui/error-festival.rs b/src/test/ui/error-festival.rs index e462824cded..356564e5407 100644 --- a/src/test/ui/error-festival.rs +++ b/src/test/ui/error-festival.rs @@ -37,7 +37,7 @@ fn main() { let y: u32 = x as u32; //~^ ERROR E0606 - let v = 0 as *const u8; + let v = core::ptr::null::(); v as *const [u8]; //~^ ERROR E0607 } diff --git a/src/test/ui/issues/issue-17458.rs b/src/test/ui/issues/issue-17458.rs index 444e94d829b..d56ffebad7d 100644 --- a/src/test/ui/issues/issue-17458.rs +++ b/src/test/ui/issues/issue-17458.rs @@ -1,4 +1,4 @@ -static X: usize = unsafe { 0 as *const usize as usize }; +static X: usize = unsafe { core::ptr::null::() as usize }; //~^ ERROR: casting pointers to integers in statics is unstable fn main() { diff --git a/src/test/ui/issues/issue-17458.stderr b/src/test/ui/issues/issue-17458.stderr index 69b6ab71e50..d51d2f50d6f 100644 --- a/src/test/ui/issues/issue-17458.stderr +++ b/src/test/ui/issues/issue-17458.stderr @@ -1,8 +1,8 @@ error[E0658]: casting pointers to integers in statics is unstable --> $DIR/issue-17458.rs:1:28 | -LL | static X: usize = unsafe { 0 as *const usize as usize }; - | ^^^^^^^^^^^^^^^^^^^^^^^^^^ +LL | static X: usize = unsafe { core::ptr::null::() as usize }; + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: for more information, see https://github.com/rust-lang/rust/issues/51910 = help: add #![feature(const_raw_ptr_to_usize_cast)] to the crate attributes to enable diff --git a/src/test/ui/issues/issue-20801.rs b/src/test/ui/issues/issue-20801.rs index 35d6f8c0fae..c3f136f2876 100644 --- a/src/test/ui/issues/issue-20801.rs +++ b/src/test/ui/issues/issue-20801.rs @@ -15,11 +15,11 @@ fn mut_ref() -> &'static mut T { } fn mut_ptr() -> *mut T { - unsafe { 0 as *mut T } + unsafe { core::ptr::null_mut() } } fn const_ptr() -> *const T { - unsafe { 0 as *const T } + unsafe { core::ptr::null() } } pub fn main() { diff --git a/src/test/ui/issues/issue-22034.rs b/src/test/ui/issues/issue-22034.rs index 508c9c91b04..fab1cdadaf5 100644 --- a/src/test/ui/issues/issue-22034.rs +++ b/src/test/ui/issues/issue-22034.rs @@ -3,7 +3,7 @@ extern crate libc; fn main() { - let ptr: *mut () = 0 as *mut _; + let ptr: *mut () = core::ptr::null_mut(); let _: &mut dyn Fn() = unsafe { &mut *(ptr as *mut dyn Fn()) //~^ ERROR expected a `std::ops::Fn<()>` closure, found `()` diff --git a/src/test/ui/mismatched_types/cast-rfc0401.rs b/src/test/ui/mismatched_types/cast-rfc0401.rs index 2f88c6496c4..b8d12fb9809 100644 --- a/src/test/ui/mismatched_types/cast-rfc0401.rs +++ b/src/test/ui/mismatched_types/cast-rfc0401.rs @@ -21,9 +21,9 @@ enum E { fn main() { let f: f32 = 1.2; - let v = 0 as *const u8; - let fat_v : *const [u8] = unsafe { &*(0 as *const [u8; 1])}; - let fat_sv : *const [i8] = unsafe { &*(0 as *const [i8; 1])}; + let v = core::ptr::null::(); + let fat_v : *const [u8] = unsafe { &*core::ptr::null::<[u8; 1]>()}; + let fat_sv : *const [i8] = unsafe { &*core::ptr::null::<[i8; 1]>()}; let foo: &dyn Foo = &f; let _ = v as &u8; //~ ERROR non-primitive cast -- cgit 1.4.1-3-g733a5