Skip to content

[naga]: Switch off of LazyLock to once_cell::racy::OnceBox #7587

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Apr 30, 2025
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions naga/src/back/glsl/keywords.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::sync::LazyLock;
use crate::racy_lock::RacyLock;

use hashbrown::HashSet;

Expand Down Expand Up @@ -499,7 +499,7 @@ pub const RESERVED_KEYWORDS: &[&str] = &[
/// significant time during [`Namer::reset`](crate::proc::Namer::reset).
///
/// See <https://github.com/gfx-rs/wgpu/pull/7338> for benchmarks.
pub static RESERVED_KEYWORD_SET: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
pub static RESERVED_KEYWORD_SET: RacyLock<HashSet<&'static str>> = RacyLock::new(|| {
let mut set = HashSet::default();
set.reserve(RESERVED_KEYWORDS.len());
for &word in RESERVED_KEYWORDS {
Expand Down
4 changes: 2 additions & 2 deletions naga/src/back/hlsl/keywords.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::sync::LazyLock;
use crate::racy_lock::RacyLock;

use hashbrown::HashSet;

Expand Down Expand Up @@ -924,7 +924,7 @@ pub const TYPES: &[&str] = &{
/// significant time during [`Namer::reset`](crate::proc::Namer::reset).
///
/// See <https://github.com/gfx-rs/wgpu/pull/7338> for benchmarks.
pub static RESERVED_SET: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
pub static RESERVED_SET: RacyLock<HashSet<&'static str>> = RacyLock::new(|| {
let mut set = HashSet::default();
set.reserve(RESERVED.len() + TYPES.len());
for &word in RESERVED {
Expand Down
4 changes: 2 additions & 2 deletions naga/src/back/msl/keywords.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::sync::LazyLock;
use crate::racy_lock::RacyLock;

use hashbrown::HashSet;

Expand Down Expand Up @@ -360,7 +360,7 @@ pub const RESERVED: &[&str] = &[
/// significant time during [`Namer::reset`](crate::proc::Namer::reset).
///
/// See <https://github.com/gfx-rs/wgpu/pull/7338> for benchmarks.
pub static RESERVED_SET: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
pub static RESERVED_SET: RacyLock<HashSet<&'static str>> = RacyLock::new(|| {
let mut set = HashSet::default();
set.reserve(RESERVED.len());
for &word in RESERVED {
Expand Down
4 changes: 2 additions & 2 deletions naga/src/back/pipeline_constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -905,7 +905,7 @@ fn map_value_to_literal(value: f64, scalar: Scalar) -> Result<Literal, PipelineC
return Err(PipelineConstantError::SrcNeedsToBeFinite);
}

let value = value.trunc();
let value = <f64 as num_traits::float::FloatCore>::trunc(value);
if value < f64::from(i32::MIN) || value > f64::from(i32::MAX) {
return Err(PipelineConstantError::DstRangeTooSmall);
}
Expand All @@ -919,7 +919,7 @@ fn map_value_to_literal(value: f64, scalar: Scalar) -> Result<Literal, PipelineC
return Err(PipelineConstantError::SrcNeedsToBeFinite);
}

let value = value.trunc();
let value = <f64 as num_traits::float::FloatCore>::trunc(value);
if value < f64::from(u32::MIN) || value > f64::from(u32::MAX) {
return Err(PipelineConstantError::DstRangeTooSmall);
}
Expand Down
4 changes: 2 additions & 2 deletions naga/src/common/wgsl/to_wgsl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ use alloc::string::{String, ToString};
///
/// - If a type's WGSL form requires dynamic formatting, so that
/// returning a `&'static str` isn't feasible, consider implementing
/// [`std::fmt::Display`] on some wrapper type instead.
/// [`core::fmt::Display`] on some wrapper type instead.
pub trait ToWgsl: Sized {
/// Return WGSL source code representation of `self`.
fn to_wgsl(self) -> &'static str;
Expand All @@ -32,7 +32,7 @@ pub trait ToWgsl: Sized {
///
/// - If a type's WGSL form requires dynamic formatting, so that
/// returning a `&'static str` isn't feasible, consider implementing
/// [`std::fmt::Display`] on some wrapper type instead.
/// [`core::fmt::Display`] on some wrapper type instead.
pub trait TryToWgsl: Sized {
/// Return the WGSL form of `self` as a `'static` string.
///
Expand Down
4 changes: 2 additions & 2 deletions naga/src/keywords/wgsl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Keywords for [WGSL][wgsl] (WebGPU Shading Language).
[wgsl]: https://gpuweb.github.io/gpuweb/wgsl.html
*/

use std::sync::LazyLock;
use crate::racy_lock::RacyLock;

use hashbrown::HashSet;

Expand Down Expand Up @@ -238,7 +238,7 @@ pub const RESERVED: &[&str] = &[
/// significant time during [`Namer::reset`](crate::proc::Namer::reset).
///
/// See <https://github.com/gfx-rs/wgpu/pull/7338> for benchmarks.
pub static RESERVED_SET: LazyLock<HashSet<&'static str>> = LazyLock::new(|| {
pub static RESERVED_SET: RacyLock<HashSet<&'static str>> = RacyLock::new(|| {
let mut set = HashSet::default();
set.reserve(RESERVED.len());
for &word in RESERVED {
Expand Down
8 changes: 1 addition & 7 deletions naga/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,15 +103,8 @@ void main() {
#[cfg(any(
test,
spv_out,

// Need OnceLock
hlsl_out,
msl_out,
wgsl_out,

feature = "spv-in",
feature = "wgsl-in",

feature = "stderr",
))]
extern crate std;
Expand All @@ -130,6 +123,7 @@ pub mod ir;
pub mod keywords;
mod non_max_u32;
pub mod proc;
mod racy_lock;
mod span;
pub mod valid;

Expand Down
76 changes: 76 additions & 0 deletions naga/src/racy_lock.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
#![cfg_attr(
not(any(hlsl_out, msl_out, wgsl_out, glsl_out)),
allow(
dead_code,
reason = "RacyLock is only required for the above configurations"
)
)]

use alloc::boxed::Box;
use core::sync::atomic::{AtomicPtr, Ordering};

/// An alternative to [`LazyLock`] which will race to initialize rather than blocking.
/// This makes it suitable for `no_std` environments, at the expense of possibly leaking
/// memory during initialization.
///
/// [`LazyLock`]: https://doc.rust-lang.org/stable/std/sync/struct.LazyLock.html
pub struct RacyLock<T: 'static> {
inner: AtomicPtr<T>,
init: fn() -> T,
}

impl<T: 'static> RacyLock<T> {
/// Creates a new [`RacyLock`], which will initialize using the provided `init` function.
pub const fn new(init: fn() -> T) -> Self {
Self {
inner: AtomicPtr::new(core::ptr::null_mut()),
init,
}
}

/// Attempts to load the internal value, returning [`None`] if it is not yet initialized.
pub fn try_get(&self) -> Option<&T> {
let ptr = self.inner.load(Ordering::Acquire);

if ptr.is_null() {
None
} else {
// SAFETY: ptr can only ever be null, or a static-valid value from Box::leak,
// as it is private.
// The above check ensures ptr is not null, so it must be a valid pointer.
unsafe { Some(&*ptr) }
}
}

/// Loads the internal value, initializing it if required.
pub fn get(&self) -> &T {
self.try_get().unwrap_or_else(|| {
let value = (self.init)();

// Refresh the static value just before leaking to minimize leaked memory.
let ptr = self.inner.load(Ordering::Acquire);

if ptr.is_null() {
// Explicit type used to assert the returned reference is 'static.
let ptr: &'static mut T = Box::leak(Box::new(value));

self.inner.store(ptr, Ordering::Release);

ptr
} else {
// SAFETY: ptr can only ever be null, or a static-valid value from Box::leak,
// as it is private.
// The above check ensures ptr is not null, so it must be a valid pointer.
unsafe { &*ptr }
}
})
}
}

impl<T: 'static> core::ops::Deref for RacyLock<T> {
type Target = T;

fn deref(&self) -> &Self::Target {
self.get()
}
}
Loading