Validate pipeline layout immediate_size and fix its calculation when there are multiple immediate variables (#9711)

This commit is contained in:
Luo Zhihao authored and GitHub committed 2026-07-14 09:47:17 -07:00
1 parent 6bbaf27426
commit d056b0e025
21 files changed
+631 -145

No files matched your search

+2
View File
@@ -57,6 +57,8 @@ Bottom level categories:
#### General
- Allow `set_immediates` before `set_pipeline` by deferring actual setting of immediates to draw/dispatch call time. By @beicause in [#9597](https://github.com/gfx-rs/wgpu/pull/9597).
- Validate pipeline layout `immediate_size` and fix its calculation when there are multiple immediate variables. Now it must be >= required size of the shader entry point. By @beicause in [#9711](https://github.com/gfx-rs/wgpu/pull/9711).
- [`immediate_address_space`](https://www.w3.org/TR/WGSL/#language_extension-immediate_address_space) WGSL language extension is implemented. By @beicause in [#9711](https://github.com/gfx-rs/wgpu/pull/9711).
#### naga
-1
View File
@@ -45,7 +45,6 @@ webgpu:api,validation,encoding,render_bundle:* // 81%, readonly flag normalizati
webgpu:api,validation,image_copy,buffer_texture_copies:* // https://github.com/gfx-rs/wgpu/issues/7946
webgpu:api,validation,layout_shader_compat:pipeline_layout_shader_exact_match:* // dx12, https://bugzilla.mozilla.org/show_bug.cgi?id=2017725
webgpu:api,validation,non_filterable_texture:non_filterable_texture_with_filtering_sampler:* // 80%, depth textures with filtering samplers
webgpu:api,validation,pipeline,immediates:* // 0%, https://github.com/gfx-rs/wgpu/issues/8556
webgpu:api,validation,query_set,create:count:* // 0%, wgpu incorrectly rejects zero-count query sets
webgpu:api,validation,queue,destroyed,* // 71%, writeBuffer/writeTexture return value, destroyed query set
webgpu:api,validation,queue,writeBuffer:ranges:* // 0%, missing OperationError for invalid ranges
+9
View File
@@ -243,6 +243,7 @@ webgpu:api,validation,image_copy,layout_related:required_bytes_in_copy:*
webgpu:api,validation,image_copy,layout_related:rows_per_image_alignment:*
webgpu:api,validation,image_copy,texture_related:*
fails-if(dx12) webgpu:api,validation,layout_shader_compat:pipeline_layout_shader_exact_match:*
webgpu:api,validation,pipeline,immediates:*
webgpu:api,validation,query_set,destroy:*
webgpu:api,validation,queue,buffer_mapped:*
webgpu:api,validation,queue,destroyed,query_set:*
@@ -380,6 +381,14 @@ webgpu:shader,validation,decl,assignment_statement:*
webgpu:shader,validation,decl,compound_statement:*
webgpu:shader,validation,decl,const:*
webgpu:shader,validation,decl,context_dependent_resolution:*
webgpu:shader,validation,decl,immediate:access_mode:*
webgpu:shader,validation,decl,immediate:binding_attributes:*
webgpu:shader,validation,decl,immediate:entry_point_interface:*
webgpu:shader,validation,decl,immediate:pointers:*
webgpu:shader,validation,decl,immediate:scope:*
//FAIL: Fixed array should be disallowed in immediates
// webgpu:shader,validation,decl,immediate:store_type,invalid:*
webgpu:shader,validation,decl,immediate:store_type,valid:*
webgpu:shader,validation,expression,access,array:early_eval_errors:case="override_array_cnt_size_neg"
webgpu:shader,validation,expression,access,array:early_eval_errors:case="override_array_cnt_size_one"
webgpu:shader,validation,expression,access,array:early_eval_errors:case="override_array_cnt_size_zero_signed"
+2 -2
View File
@@ -94,7 +94,7 @@ impl crate::framework::Example for Example {
fn required_limits() -> wgpu::Limits {
wgpu::Limits {
max_immediate_size: 12,
max_immediate_size: 16,
..wgpu::Limits::default()
}
.using_minimum_supported_acceleration_structure_values()
@@ -186,7 +186,7 @@ impl crate::framework::Example for Example {
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 12,
immediate_size: 16,
});
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
@@ -17,6 +17,7 @@ impl LanguageExtension {
const PACKED4X8_INTEGER_DOT_PRODUCT: &'static str = "packed_4x8_integer_dot_product";
const UNRESTRICTED_POINTER_PARAMETERS: &'static str = "unrestricted_pointer_parameters";
const POINTER_COMPOSITE_ACCESS: &'static str = "pointer_composite_access";
const IMMEDIATE_ADDRESS_SPACE: &'static str = "immediate_address_space";
/// Convert from a sentinel word in WGSL into its associated [`LanguageExtension`], if possible.
pub fn from_ident(s: &str) -> Option<Self> {
@@ -33,6 +34,9 @@ impl LanguageExtension {
Self::POINTER_COMPOSITE_ACCESS => {
Self::Implemented(ImplementedLanguageExtension::PointerCompositeAccess)
}
Self::IMMEDIATE_ADDRESS_SPACE => {
Self::Implemented(ImplementedLanguageExtension::ImmediateAddressSpace)
}
_ => return None,
})
}
@@ -57,6 +61,7 @@ pub enum ImplementedLanguageExtension {
ReadOnlyAndReadWriteStorageTextures,
Packed4x8IntegerDotProduct,
PointerCompositeAccess,
ImmediateAddressSpace,
}
impl ImplementedLanguageExtension {
@@ -65,6 +70,7 @@ impl ImplementedLanguageExtension {
Self::ReadOnlyAndReadWriteStorageTextures,
Self::Packed4x8IntegerDotProduct,
Self::PointerCompositeAccess,
Self::ImmediateAddressSpace,
];
/// Returns slice of all variants of [`ImplementedLanguageExtension`].
@@ -84,6 +90,9 @@ impl ImplementedLanguageExtension {
ImplementedLanguageExtension::PointerCompositeAccess => {
LanguageExtension::POINTER_COMPOSITE_ACCESS
}
ImplementedLanguageExtension::ImmediateAddressSpace => {
LanguageExtension::IMMEDIATE_ADDRESS_SPACE
}
}
}
}
+23 -11
View File
@@ -30,7 +30,20 @@ impl ImmediateSlots {
types: &crate::UniqueArena<crate::Type>,
gctx: crate::proc::GlobalCtx,
) -> Self {
// <https://www.w3.org/TR/WGSL/#accessible-bytes>
match *ty {
crate::TypeInner::Matrix {
columns,
rows,
scalar,
} => {
let mut slots = Self::default();
let stride = crate::proc::Alignment::from(rows) * scalar.width as u32;
for col in 0..u32::from(columns) {
slots |= Self::from_range(col * stride, u32::from(rows) * scalar.width as u32);
}
slots
}
crate::TypeInner::Struct { ref members, .. } => {
let mut slots = Self::default();
for member in members {
@@ -53,17 +66,6 @@ impl ImmediateSlots {
Self(self.0 & !other.0)
}
/// Returns the byte size of the `var<immediate>` type in a module.
/// Zero if the module has no `var<immediate>`.
pub fn size_for_module(module: &crate::Module) -> u32 {
module
.global_variables
.iter()
.find(|&(_, var)| var.space == crate::AddressSpace::Immediate)
.map(|(_, var)| module.types[var.ty].inner.size(module.to_ctx()))
.unwrap_or(0)
}
/// Compute the immediate slot bitmask for a pointer expression that
/// refers to (part of) an immediate global variable.
///
@@ -195,6 +197,16 @@ mod tests {
assert_eq!(slots, ImmediateSlots::from_raw(0b1111_0001));
}
#[test]
fn from_type_excludes_matrix_padding() {
let module = crate::front::wgsl::parse_str("struct S { mat: mat3x3<f32> }").unwrap();
let struct_ty = (module.types.iter().map(|ty| ty.1))
.find(|ty| ty.name.as_deref() == Some("S"))
.unwrap();
let slots = ImmediateSlots::from_type(&struct_ty.inner, 0, &module.types, module.to_ctx());
assert_eq!(slots, ImmediateSlots::from_raw(0b0111_0111_0111));
}
#[test]
fn range_unaligned() {
assert_eq!(
+3 -1
View File
@@ -896,7 +896,9 @@ impl Validator {
}
match self.validate_entry_point(ep, module, &mod_info) {
Ok(info) => mod_info.entry_points.push(info),
Ok(info) => {
mod_info.entry_points.push(info);
}
Err(error) => {
return Err(Box::new(error.and_then(|source| {
ValidationError::EntryPoint {
-2
View File
@@ -309,8 +309,6 @@ impl super::Validator {
});
}
immediates_compatibility = Err(ImmediateError::InvalidScalar(scalar));
true
}
_ => scalar.width == 4,
+1 -1
View File
@@ -1,5 +1,5 @@
capabilities = "IMMEDIATES"
targets = "GLSL | HLSL"
targets = "GLSL | HLSL | ANALYSIS"
[hlsl]
fake_missing_bindings = true
+12 -5
View File
@@ -1,7 +1,14 @@
struct ImmediateData {
multiplier: f32
struct ImmediateDataVert {
position_clip: f32,
matrix: mat3x3<f32>,
}
var<immediate> im: ImmediateData;
var<immediate> im_vert: ImmediateDataVert;
struct ImmediateDataFrag {
multiplier: f32,
tint: vec4f,
}
var<immediate> im_frag: ImmediateDataFrag;
struct FragmentIn {
@location(0) color: vec4<f32>
@@ -13,10 +20,10 @@ fn vert_main(
@builtin(instance_index) ii: u32,
@builtin(vertex_index) vi: u32,
) -> @builtin(position) vec4<f32> {
return vec4<f32>(f32(ii) * f32(vi) * im.multiplier * pos, 0.0, 1.0);
return vec4<f32>(f32(ii) * f32(vi) * pos, 0.0, im_vert.position_clip);
}
@fragment
fn main(in: FragmentIn) -> @location(0) vec4<f32> {
return in.color * im.multiplier;
return in.color * im_frag.tint;
}
-20
View File
@@ -1565,26 +1565,6 @@ fn int16_in_immediate() {
}
}
#[test]
fn float16_in_immediate() {
check_validation! {
"enable f16; var<immediate> input: f16;",
"enable f16; var<immediate> input: vec2<f16>;",
"enable f16; var<immediate> input: mat4x4<f16>;",
"enable f16; struct S { a: f16 }; var<immediate> input: S;",
"enable f16; struct S1 { a: f16 }; struct S2 { a : S1 } var<immediate> input: S2;":
Err(naga::valid::ValidationError::GlobalVariable {
source: naga::valid::GlobalVariableError::InvalidImmediateType(
naga::valid::ImmediateError::InvalidScalar(
naga::Scalar::F16
)
),
..
}),
naga::valid::Capabilities::SHADER_FLOAT16 | naga::valid::Capabilities::IMMEDIATES
}
}
#[test]
fn float16_in_atomic() {
check_validation! {
@@ -0,0 +1,242 @@
(
type_flags: [
("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | CREATION_RESOLVED | ARGUMENT | CONSTRUCTIBLE"),
("DATA | SIZED | COPY | HOST_SHAREABLE | CREATION_RESOLVED | ARGUMENT | CONSTRUCTIBLE"),
("DATA | SIZED | COPY | HOST_SHAREABLE | CREATION_RESOLVED | ARGUMENT | CONSTRUCTIBLE"),
("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | CREATION_RESOLVED | ARGUMENT | CONSTRUCTIBLE"),
("DATA | SIZED | COPY | HOST_SHAREABLE | CREATION_RESOLVED | ARGUMENT | CONSTRUCTIBLE"),
("DATA | SIZED | COPY | HOST_SHAREABLE | CREATION_RESOLVED | ARGUMENT | CONSTRUCTIBLE"),
("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | CREATION_RESOLVED | ARGUMENT | CONSTRUCTIBLE"),
("DATA | SIZED | COPY | IO_SHAREABLE | HOST_SHAREABLE | CREATION_RESOLVED | ARGUMENT | CONSTRUCTIBLE"),
],
functions: [],
entry_points: [
(
flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"),
available_stages: ("VERTEX | FRAGMENT | COMPUTE | MESH | TASK | RAY_GENERATION | ANY_HIT | CLOSEST_HIT | MISS"),
uniformity: (
non_uniform_result: Some(1),
requirements: (""),
),
may_kill: false,
sampling_set: [],
global_uses: [
("READ"),
(""),
],
expressions: [
(
uniformity: (
non_uniform_result: Some(0),
requirements: (""),
),
ref_count: 1,
assignable_global: None,
ty: Handle(6),
),
(
uniformity: (
non_uniform_result: Some(1),
requirements: (""),
),
ref_count: 1,
assignable_global: None,
ty: Handle(7),
),
(
uniformity: (
non_uniform_result: Some(2),
requirements: (""),
),
ref_count: 1,
assignable_global: None,
ty: Handle(7),
),
(
uniformity: (
non_uniform_result: Some(1),
requirements: (""),
),
ref_count: 1,
assignable_global: None,
ty: Value(Scalar((
kind: Float,
width: 4,
))),
),
(
uniformity: (
non_uniform_result: Some(2),
requirements: (""),
),
ref_count: 1,
assignable_global: None,
ty: Value(Scalar((
kind: Float,
width: 4,
))),
),
(
uniformity: (
non_uniform_result: Some(1),
requirements: (""),
),
ref_count: 1,
assignable_global: None,
ty: Value(Scalar((
kind: Float,
width: 4,
))),
),
(
uniformity: (
non_uniform_result: Some(1),
requirements: (""),
),
ref_count: 1,
assignable_global: None,
ty: Handle(6),
),
(
uniformity: (
non_uniform_result: None,
requirements: (""),
),
ref_count: 1,
assignable_global: Some(0),
ty: Value(Pointer(
base: 2,
space: Immediate,
)),
),
(
uniformity: (
non_uniform_result: None,
requirements: (""),
),
ref_count: 1,
assignable_global: Some(0),
ty: Value(Pointer(
base: 0,
space: Immediate,
)),
),
(
uniformity: (
non_uniform_result: None,
requirements: (""),
),
ref_count: 1,
assignable_global: None,
ty: Handle(0),
),
(
uniformity: (
non_uniform_result: None,
requirements: (""),
),
ref_count: 1,
assignable_global: None,
ty: Value(Scalar((
kind: Float,
width: 4,
))),
),
(
uniformity: (
non_uniform_result: Some(1),
requirements: (""),
),
ref_count: 1,
assignable_global: None,
ty: Handle(3),
),
],
sampling: [],
dual_source_blending: false,
diagnostic_filter_leaf: None,
immediate_slots_used: (1),
),
(
flags: ("EXPRESSIONS | BLOCKS | CONTROL_FLOW_UNIFORMITY | STRUCT_LAYOUTS | CONSTANTS | BINDINGS"),
available_stages: ("VERTEX | FRAGMENT | COMPUTE | MESH | TASK | RAY_GENERATION | ANY_HIT | CLOSEST_HIT | MISS"),
uniformity: (
non_uniform_result: Some(0),
requirements: (""),
),
may_kill: false,
sampling_set: [],
global_uses: [
(""),
("READ"),
],
expressions: [
(
uniformity: (
non_uniform_result: Some(0),
requirements: (""),
),
ref_count: 1,
assignable_global: None,
ty: Handle(5),
),
(
uniformity: (
non_uniform_result: Some(0),
requirements: (""),
),
ref_count: 1,
assignable_global: None,
ty: Handle(3),
),
(
uniformity: (
non_uniform_result: None,
requirements: (""),
),
ref_count: 1,
assignable_global: Some(1),
ty: Value(Pointer(
base: 4,
space: Immediate,
)),
),
(
uniformity: (
non_uniform_result: None,
requirements: (""),
),
ref_count: 1,
assignable_global: Some(1),
ty: Value(Pointer(
base: 3,
space: Immediate,
)),
),
(
uniformity: (
non_uniform_result: None,
requirements: (""),
),
ref_count: 1,
assignable_global: None,
ty: Handle(3),
),
(
uniformity: (
non_uniform_result: Some(0),
requirements: (""),
),
ref_count: 1,
assignable_global: None,
ty: Handle(3),
),
],
sampling: [],
dual_source_blending: false,
diagnostic_filter_leaf: None,
immediate_slots_used: (240),
),
],
const_expression_types: [],
)
@@ -3,20 +3,25 @@
precision highp float;
precision highp int;
struct ImmediateData {
struct ImmediateDataVert {
float position_clip;
mat3x3 matrix;
};
struct ImmediateDataFrag {
float multiplier;
vec4 tint;
};
struct FragmentIn {
vec4 color;
};
uniform ImmediateData _immediates_binding_fs;
uniform ImmediateDataFrag _immediates_binding_fs;
layout(location = 0) smooth in vec4 _vs2fs_location0;
layout(location = 0) out vec4 _fs2p_location0;
void main() {
FragmentIn in_ = FragmentIn(_vs2fs_location0);
float _e4 = _immediates_binding_fs.multiplier;
vec4 _e4 = _immediates_binding_fs.tint;
_fs2p_location0 = (in_.color * _e4);
return;
}
@@ -5,13 +5,18 @@ precision highp int;
uniform uint naga_vs_first_instance;
struct ImmediateData {
struct ImmediateDataVert {
float position_clip;
mat3x3 matrix;
};
struct ImmediateDataFrag {
float multiplier;
vec4 tint;
};
struct FragmentIn {
vec4 color;
};
uniform ImmediateData _immediates_binding_vs;
uniform ImmediateDataVert _immediates_binding_vs;
layout(location = 0) in vec2 _p2vs_location0;
@@ -19,8 +24,8 @@ void main() {
vec2 pos = _p2vs_location0;
uint ii = (uint(gl_InstanceID) + naga_vs_first_instance);
uint vi = uint(gl_VertexID);
float _e8 = _immediates_binding_vs.multiplier;
gl_Position = vec4((((float(ii) * float(vi)) * _e8) * pos), 0.0, 1.0);
float _e9 = _immediates_binding_vs.position_clip;
gl_Position = vec4(((float(ii) * float(vi)) * pos), 0.0, _e9);
return;
}
+19 -5
View File
@@ -5,15 +5,29 @@ struct NagaConstants {
};
ConstantBuffer<NagaConstants> _NagaConstants: register(b0, space1);
struct ImmediateData {
struct ImmediateDataVert {
float position_clip;
int _pad1_0;
int _pad1_1;
int _pad1_2;
row_major float3x3 matrix_;
int _end_pad_0;
};
struct ImmediateDataFrag {
float multiplier;
int _pad1_0;
int _pad1_1;
int _pad1_2;
float4 tint;
};
struct FragmentIn {
float4 color : LOC0;
};
ConstantBuffer<ImmediateData> im: register(b0);
ConstantBuffer<ImmediateDataVert> im_vert: register(b0);
ConstantBuffer<ImmediateDataFrag> im_frag: register(b0);
struct FragmentInput_main {
float4 color : LOC0;
@@ -21,13 +35,13 @@ struct FragmentInput_main {
float4 vert_main(float2 pos : LOC0, uint ii : SV_InstanceID, uint vi : SV_VertexID) : SV_Position
{
float _e8 = im.multiplier;
return float4((((float((_NagaConstants.first_instance + ii)) * float((_NagaConstants.first_vertex + vi))) * _e8) * pos), 0.0, 1.0);
float _e9 = im_vert.position_clip;
return float4(((float((_NagaConstants.first_instance + ii)) * float((_NagaConstants.first_vertex + vi))) * pos), 0.0, _e9);
}
float4 main(FragmentInput_main fragmentinput_main) : SV_Target0
{
FragmentIn in_ = { fragmentinput_main.color };
float _e4 = im.multiplier;
float4 _e4 = im_frag.tint;
return (in_.color * _e4);
}
+196 -2
View File
@@ -93,7 +93,7 @@ fn dispatch_without_setting_immediates_fails() {
pass.set_bind_group(0, &bind_group, &[]);
pass.dispatch_workgroups(1, 1, 1);
}
fail(&device, || encoder.finish(), Some("immediate data"));
fail(&device, || encoder.finish(), Some("not all immediate data required by the pipeline has been set via set_immediates (missing byte ranges: 0..16)"));
}
#[test]
@@ -108,7 +108,7 @@ fn dispatch_with_partial_immediates_fails() {
pass.set_immediates(0, &[0u8; 8]);
pass.dispatch_workgroups(1, 1, 1);
}
fail(&device, || encoder.finish(), Some("immediate data"));
fail(&device, || encoder.finish(), Some("not all immediate data required by the pipeline has been set via set_immediates (missing byte ranges: 8..16)"));
}
#[test]
@@ -358,3 +358,197 @@ fn auto_layout_infers_immediate_size() {
}
wgpu_test::valid(&device, || encoder.finish());
}
const RENDER_SHADER_MULTI_IMMEDIATES: &str = "
enable f16;
struct ImmediateA {
@size(34)
a1: f16,
}
var<immediate> im_a: ImmediateA;
struct ImmediateB {
b1: u32,
b2: vec4<f32>,
}
var<immediate> im_b: ImmediateB;
struct VertexOutput {
@builtin(position) position: vec4f,
@location(0) @interpolate(flat) index: u32,
}
@vertex fn vertex() -> VertexOutput {
return VertexOutput(vec4f(1.0, 0.0, 0.0, 1.0), u32(im_a.a1));
}
@fragment fn fragment(
@location(0) @interpolate(flat) ix: u32,
) -> @location(0) vec4f {
return im_b.b2;
}
";
fn begin_render_pass<'b, 'a: 'b>(
output_texture_view: &'a wgpu::TextureView,
encoder: &'a mut wgpu::CommandEncoder,
f: impl Fn(&mut wgpu::RenderPass<'b>),
) {
let mut render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("Render Pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: output_texture_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color::default()),
store: wgpu::StoreOp::Store,
},
})],
..Default::default()
});
f(&mut render_pass);
}
fn setup_render() -> (wgpu::Device, wgpu::Queue, wgpu::TextureView) {
let (device, queue) = wgpu::Device::noop(&wgpu::DeviceDescriptor {
required_features: wgpu::Features::IMMEDIATES | wgpu::Features::SHADER_F16,
required_limits: wgpu::Limits {
max_immediate_size: 64,
..Default::default()
},
..Default::default()
});
let output_texture = device.create_texture(&wgpu::TextureDescriptor {
size: wgpu::Extent3d {
width: 2,
height: 2,
depth_or_array_layers: 1,
},
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8UnormSrgb,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
label: Some("Output Texture"),
view_formats: &[],
});
let output_texture_view = output_texture.create_view(&Default::default());
(device, queue, output_texture_view)
}
#[test]
fn render_multi_immediates_with_smaller_layout_immediate_size_fails() {
let (device, _queue, output_texture_view) = setup_render();
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Shader"),
source: wgpu::ShaderSource::Wgsl(RENDER_SHADER_MULTI_IMMEDIATES.into()),
});
let create_pipeline = |immediate_size| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render Pipeline"),
layout: Some(
&device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: None,
bind_group_layouts: &[],
immediate_size,
}),
),
vertex: wgpu::VertexState {
module: &shader,
entry_point: None,
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: None,
targets: &[Some(output_texture_view.texture().format().into())],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::PointList,
..Default::default()
},
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
})
};
fail(&device, || create_pipeline(32), Some("Pipeline layout immediate size (32) must be >= the required immediate size (34) of the shader entry point"));
fail(&device, || create_pipeline(34), Some("Immediate data has range bound 34 which is not aligned to IMMEDIATE_DATA_ALIGNMENT (4)"));
wgpu_test::valid(&device, || create_pipeline(36));
}
#[test]
fn render_multi_immediates_auto_layout_with_all_immediates_set_succeeds() {
let (device, _queue, output_texture_view) = setup_render();
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("Shader"),
source: wgpu::ShaderSource::Wgsl(RENDER_SHADER_MULTI_IMMEDIATES.into()),
});
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("Render Pipeline"),
layout: None,
vertex: wgpu::VertexState {
module: &shader,
entry_point: None,
buffers: &[],
compilation_options: Default::default(),
},
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: None,
targets: &[Some(output_texture_view.texture().format().into())],
compilation_options: Default::default(),
}),
primitive: wgpu::PrimitiveState {
topology: wgpu::PrimitiveTopology::PointList,
..Default::default()
},
depth_stencil: None,
multisample: wgpu::MultisampleState::default(),
multiview_mask: None,
cache: None,
});
fn do_encoding<'a>(
encoder: &mut dyn wgpu::util::RenderEncoder<'a>,
pipeline: &'a wgpu::RenderPipeline,
) {
encoder.set_pipeline(pipeline);
encoder.set_immediates(0, &[0u8; 4]);
encoder.set_immediates(16, &[0u8; 16]);
encoder.draw(0..4, 0..1);
}
let mut encoder = device.create_command_encoder(&Default::default());
begin_render_pass(&output_texture_view, &mut encoder, |pass| {
do_encoding(pass, &pipeline);
});
wgpu_test::valid(&device, || encoder.finish());
let mut encoder = device.create_command_encoder(&Default::default());
let mut bundle_encoder =
device.create_render_bundle_encoder(&wgpu::RenderBundleEncoderDescriptor {
color_formats: &[Some(output_texture_view.texture().format())],
sample_count: 1,
..wgpu::RenderBundleEncoderDescriptor::default()
});
do_encoding(&mut bundle_encoder, &pipeline);
let bundle = bundle_encoder.finish(&wgpu::RenderBundleDescriptor::default());
begin_render_pass(&output_texture_view, &mut encoder, |pass| {
pass.execute_bundles([&bundle]);
});
wgpu_test::valid(&device, || encoder.finish());
}
+10 -53
View File
@@ -4466,6 +4466,10 @@ impl Device {
mut derived_group_layouts: Box<ArrayVec<bgl::EntryMap, { hal::MAX_BIND_GROUPS }>>,
immediate_size: u32,
) -> Result<Arc<binding_model::PipelineLayout>, pipeline::ImplicitLayoutError> {
// <https://gpuweb.github.io/gpuweb/#abstract-opdef-default-pipeline-layout>
// Round up the immediate size for pipeline layout as it is required to be a multiple of 4
let immediate_size = align_to(immediate_size, wgt::IMMEDIATE_DATA_ALIGNMENT);
while derived_group_layouts
.last()
.is_some_and(|map| map.is_empty())
@@ -4579,7 +4583,7 @@ impl Device {
None => validation::BindingLayoutSource::new_derived(&self.limits),
};
let mut shader_binding_sizes = FastHashMap::default();
let io = validation::StageIo::default();
let mut io = validation::StageIo::default();
let final_entry_point_name;
@@ -4592,7 +4596,7 @@ impl Device {
)?;
if let Some(interface) = shader_module_state.interface.interface() {
let _ = interface.check_stage(
io = interface.check_stage(
&mut binding_layout_source,
&mut shader_binding_sizes,
&final_entry_point_name,
@@ -4606,11 +4610,7 @@ impl Device {
let pipeline_layout = match binding_layout_source {
validation::BindingLayoutSource::Provided(pipeline_layout) => pipeline_layout,
validation::BindingLayoutSource::Derived(entries) => {
let immediate_size = shader_module_state
.interface
.interface()
.map_or(0, |i| i.immediate_size);
self.create_derived_pipeline_layout(entries, immediate_size)?
self.create_derived_pipeline_layout(entries, io.immediate_size_required)?
}
};
@@ -4658,17 +4658,6 @@ impl Device {
},
)?;
let immediate_slots_required =
shader_module_state
.interface
.interface()
.map_or(Default::default(), |iface| {
iface.immediate_slots_required(
naga::ShaderStage::Compute,
&final_entry_point_name,
)
});
let pipeline = pipeline::ComputePipeline {
state: ResourceState::Valid(pipeline::ComputePipelineState {
raw: ManuallyDrop::new(raw),
@@ -4677,7 +4666,7 @@ impl Device {
}),
device: self.clone(),
late_sized_buffer_groups,
immediate_slots_required,
immediate_slots_required: io.immediate_slots_required,
label: desc.label.to_string(),
tracking_data: TrackingData::new(self.tracker_indices.compute_pipelines.clone()),
};
@@ -5155,7 +5144,6 @@ impl Device {
let mut _vertex_entry_point_name = String::new();
let mut _task_entry_point_name = String::new();
let mut _mesh_entry_point_name = String::new();
let mut immediate_slots_required = naga::valid::ImmediateSlots::default();
let mut passthrough_stages = wgt::ShaderStages::empty();
match desc.vertex {
pipeline::RenderPipelineVertexProcessor::Vertex(ref vertex) => {
@@ -5190,8 +5178,6 @@ impl Device {
.map_err(stage_err)?;
if let Some(interface) = vertex_shader_module_state.interface.interface() {
immediate_slots_required |= interface
.immediate_slots_required(stage.to_naga(), &_vertex_entry_point_name);
io = interface
.check_stage(
&mut binding_layout_source,
@@ -5244,8 +5230,6 @@ impl Device {
.map_err(stage_err)?;
if let Some(interface) = task_shader_module_state.interface.interface() {
immediate_slots_required |= interface
.immediate_slots_required(stage.to_naga(), &_task_entry_point_name);
io = interface
.check_stage(
&mut binding_layout_source,
@@ -5296,8 +5280,6 @@ impl Device {
.map_err(stage_err)?;
if let Some(interface) = mesh_shader_module_state.interface.interface() {
immediate_slots_required |= interface
.immediate_slots_required(stage.to_naga(), &_mesh_entry_point_name);
io = interface
.check_stage(
&mut binding_layout_source,
@@ -5357,8 +5339,6 @@ impl Device {
.map_err(stage_err)?;
if let Some(interface) = shader_module_state.interface.interface() {
immediate_slots_required |= interface
.immediate_slots_required(stage.to_naga(), &fragment_entry_point_name);
io = interface
.check_stage(
&mut binding_layout_source,
@@ -5429,30 +5409,7 @@ impl Device {
let pipeline_layout = match binding_layout_source {
validation::BindingLayoutSource::Provided(pipeline_layout) => pipeline_layout,
validation::BindingLayoutSource::Derived(entries) => {
let immediate_size = {
let immediate_size_of = |sm: &pipeline::ShaderModule| {
sm.state()
.expect("Should be validated above")
.interface
.interface()
.map(|i| i.immediate_size)
};
let vertex = match desc.vertex {
pipeline::RenderPipelineVertexProcessor::Vertex(ref v) => {
immediate_size_of(&v.stage.module)
}
pipeline::RenderPipelineVertexProcessor::Mesh(ref task, ref mesh) => task
.as_ref()
.and_then(|t| immediate_size_of(&t.stage.module))
.max(immediate_size_of(&mesh.stage.module)),
};
let fragment = desc
.fragment
.as_ref()
.and_then(|f| immediate_size_of(&f.stage.module));
vertex.max(fragment).unwrap_or(0)
};
self.create_derived_pipeline_layout(entries, immediate_size)?
self.create_derived_pipeline_layout(entries, io.immediate_size_required)?
}
};
@@ -5633,7 +5590,7 @@ impl Device {
strip_index_format: desc.primitive.strip_index_format,
vertex_steps,
late_sized_buffer_groups,
immediate_slots_required,
immediate_slots_required: io.immediate_slots_required,
label: desc.label.to_string(),
tracking_data: TrackingData::new(self.tracker_indices.render_pipelines.clone()),
is_mesh,
+78 -35
View File
@@ -293,15 +293,27 @@ struct EntryPoint {
dual_source_blending: bool,
task_payload_size: Option<u32>,
mesh_info: Option<EntryPointMeshInfo>,
immediate_slots_required: naga::valid::ImmediateSlots,
immediate_slots: naga::valid::ImmediateSlots,
immediate_size: u32,
}
#[derive(Debug, Hash, PartialEq, Eq)]
struct EntryPointKey(naga::ShaderStage, String);
#[derive(Debug, Hash, PartialEq, Eq)]
struct EntryPointKeyRef<'a>(naga::ShaderStage, &'a str);
impl hashbrown::Equivalent<EntryPointKey> for EntryPointKeyRef<'_> {
fn equivalent(&self, key: &EntryPointKey) -> bool {
self.0 == key.0 && self.1 == key.1
}
}
#[derive(Debug)]
pub struct Interface {
limits: wgt::Limits,
resources: naga::Arena<Resource>,
entry_points: FastHashMap<(naga::ShaderStage, String), EntryPoint>,
pub(crate) immediate_size: u32,
entry_points: FastHashMap<EntryPointKey, EntryPoint>,
}
#[derive(Debug)]
@@ -532,6 +544,8 @@ pub enum StageError {
PerVertexNotTriangles,
#[error("Mesh shader pipelines must have primitive topology of TriangleList, LineList or PointList, and this must match with what the mesh shader declares.")]
MeshTopologyMismatch,
#[error("Pipeline layout immediate size ({layout}) must be >= the required immediate size ({required}) of the shader entry point")]
LayoutImmediateSize { layout: u32, required: u32 },
}
impl WebGpuError for StageError {
@@ -568,7 +582,8 @@ impl WebGpuError for StageError {
| Self::InvalidDualSourceBlending
| Self::MissingFragDepthAttachment
| Self::PerVertexNotTriangles
| Self::MeshTopologyMismatch => ErrorType::Validation,
| Self::MeshTopologyMismatch
| Self::LayoutImmediateSize { .. } => ErrorType::Validation,
}
}
}
@@ -1066,6 +1081,8 @@ pub struct StageIo {
///
/// This is Some if it was a mesh shader.
pub primitive_index: Option<bool>,
pub immediate_slots_required: naga::valid::ImmediateSlots,
pub immediate_size_required: u32,
}
impl Interface {
@@ -1256,12 +1273,10 @@ impl Interface {
resource_mapping.insert(var_handle, handle);
}
let immediate_size = naga::valid::ImmediateSlots::size_for_module(module);
let mut entry_points = FastHashMap::default();
entry_points.reserve(module.entry_points.len());
for (index, entry_point) in module.entry_points.iter().enumerate() {
let info = info.get_entry_point(index);
let func_info = info.get_entry_point(index);
let mut ep = EntryPoint::default();
for arg in entry_point.function.arguments.iter() {
Self::populate(&mut ep.inputs, arg.binding.as_ref(), arg.ty, &module.types);
@@ -1276,19 +1291,35 @@ impl Interface {
}
for (var_handle, var) in module.global_variables.iter() {
let usage = info[var_handle];
let usage = func_info[var_handle];
if !usage.is_empty() && var.binding.is_some() {
ep.resources.push(resource_mapping[&var_handle]);
}
}
for key in info.sampling_set.iter() {
for key in func_info.sampling_set.iter() {
ep.sampling_pairs
.insert((resource_mapping[&key.image], resource_mapping[&key.sampler]));
}
ep.dual_source_blending = info.dual_source_blending;
ep.dual_source_blending = func_info.dual_source_blending;
ep.workgroup_size = entry_point.workgroup_size;
ep.immediate_slots_required = info.immediate_slots_used;
ep.immediate_slots = func_info.immediate_slots_used;
// Find the used immediates. Naga should have validated that
// at most one immediate is used by the entry point.
let mut used_immediates = module
.global_variables
.iter()
.filter(|&(_, var)| var.space == naga::AddressSpace::Immediate)
.map(|(handle, _)| handle)
.filter(|&handle| !func_info[handle].is_empty());
ep.immediate_size = if let Some(immediate) = used_immediates.next() {
let ty = &module.types[module.global_variables[immediate].ty];
ty.inner.size(module.to_ctx())
} else {
0
};
assert!(used_immediates.next().is_none());
if let Some(task_payload) = entry_point.task_payload {
ep.task_payload_size = Some(
@@ -1321,25 +1352,29 @@ impl Interface {
);
}
entry_points.insert((entry_point.stage, entry_point.name.clone()), ep);
entry_points.insert(
EntryPointKey(entry_point.stage, entry_point.name.clone()),
ep,
);
}
Self {
limits,
resources,
entry_points,
immediate_size,
}
}
pub fn immediate_slots_required(
fn immediate_size_and_slots_required(
&self,
stage: naga::ShaderStage,
entry_point_name: &str,
) -> naga::valid::ImmediateSlots {
) -> (u32, naga::valid::ImmediateSlots) {
self.entry_points
.get(&(stage, entry_point_name.to_string()))
.map_or(Default::default(), |ep| ep.immediate_slots_required)
.get(&EntryPointKeyRef(stage, entry_point_name))
.map_or(Default::default(), |ep| {
(ep.immediate_size, ep.immediate_slots)
})
}
pub fn finalize_entry_point_name(
@@ -1351,10 +1386,12 @@ impl Interface {
.map(|ep| ep.to_string())
.map(Ok)
.unwrap_or_else(|| {
let mut entry_points = self
.entry_points
.keys()
.filter_map(|(ep_stage, name)| (ep_stage == &stage).then_some(name));
let mut entry_points =
self.entry_points
.keys()
.filter_map(|EntryPointKey(ep_stage, name)| {
(ep_stage == &stage).then_some(name)
});
let first = entry_points.next().ok_or(StageError::NoEntryPointFound)?;
if entry_points.next().is_some() {
return Err(StageError::MultipleEntryPointsFound);
@@ -1376,12 +1413,12 @@ impl Interface {
) -> Result<StageIo, StageError> {
// Since a shader module can have multiple entry points with the same name,
// we need to look for one with the right execution model.
let pair = (shader_stage.to_naga(), entry_point_name.to_string());
let pair = EntryPointKeyRef(shader_stage.to_naga(), entry_point_name);
let entry_point = match self.entry_points.get(&pair) {
Some(some) => some,
None => return Err(StageError::MissingEntryPoint(pair.1)),
None => return Err(StageError::MissingEntryPoint(pair.1.to_string())),
};
let (_, entry_point_name) = pair;
let EntryPointKeyRef(_, entry_point_name) = pair;
let stage_bit = shader_stage.to_wgt_bit();
@@ -1879,6 +1916,21 @@ impl Interface {
})
.collect();
let (immediate_size_required, immediate_slots_required) =
self.immediate_size_and_slots_required(shader_stage.to_naga(), entry_point_name);
let immediate_slots_required = immediate_slots_required | inputs.immediate_slots_required;
let immediate_size_required = immediate_size_required.max(inputs.immediate_size_required);
// Check pipeline layout immediate size
if let BindingLayoutSource::Provided(pipeline_layout) = layouts {
if pipeline_layout.immediate_size < immediate_size_required {
return Err(StageError::LayoutImmediateSize {
layout: pipeline_layout.immediate_size,
required: immediate_size_required,
});
}
}
Ok(StageIo {
task_payload_size: entry_point.task_payload_size,
varyings: outputs,
@@ -1887,19 +1939,10 @@ impl Interface {
} else {
None
},
immediate_slots_required,
immediate_size_required,
})
}
pub fn fragment_uses_dual_source_blending(
&self,
entry_point_name: &str,
) -> Result<bool, StageError> {
let pair = (naga::ShaderStage::Fragment, entry_point_name.to_string());
self.entry_points
.get(&pair)
.ok_or(StageError::MissingEntryPoint(pair.1))
.map(|ep| ep.dual_source_blending)
}
}
pub fn check_color_attachment_count(
+2
View File
@@ -17,6 +17,8 @@ bitflags::bitflags! {
const UnrestrictedPointerParameters = 1 << 2;
/// <https://www.w3.org/TR/WGSL/#language_extension-pointer_composite_access>
const PointerCompositeAccess = 1 << 3;
/// <https://www.w3.org/TR/WGSL/#language_extension-immediate_address_space>
const ImmediateAddressSpace = 1 << 4;
}
}
+3
View File
@@ -1752,6 +1752,9 @@ impl dispatch::InstanceInterface for ContextWebGpu {
"pointer_composite_access" => {
Some(crate::WgslLanguageFeatures::PointerCompositeAccess)
}
"immediate_address_space" => {
Some(crate::WgslLanguageFeatures::ImmediateAddressSpace)
}
_ => None,
})
.for_each(|wlf| {
+3
View File
@@ -906,6 +906,9 @@ impl dispatch::InstanceInterface for ContextWgpuCore {
ImplementedLanguageExtension::PointerCompositeAccess => {
crate::WgslLanguageFeatures::PointerCompositeAccess
}
ImplementedLanguageExtension::ImmediateAddressSpace => {
crate::WgslLanguageFeatures::ImmediateAddressSpace
}
}
},
)