From 103a70e581e2ed14ea1fb4edbe377fd8acba7b52 Mon Sep 17 00:00:00 2001 From: MinerSheep <46878556+MinerSheep@users.noreply.github.com> Date: Tue, 22 Sep 2026 13:17:45 -0700 Subject: [PATCH] [naga] const_evaluator: insertBits, extractBits, faceForward, reflect, and refract (#10258) Co-authored-by: Teodor Tanasoaia <28601907+teoxoy@users.noreply.github.com> --- CHANGELOG.md | 1 + cts_runner/fail.lst | 10 +- cts_runner/test.lst | 13 + naga/src/front/wgsl/lower/mod.rs | 44 +++ naga/src/proc/constant_evaluator.rs | 471 ++++++++++++++++++++++++++-- naga/src/proc/mod.rs | 3 +- naga/tests/naga/wgsl_errors.rs | 181 +++++++++++ 7 files changed, 695 insertions(+), 28 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e1f360de5..3d394fd03 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -200,6 +200,7 @@ By @sagudev in [#10109](https://github.com/gfx-rs/wgpu/pull/10109). - Fix a panic in the SPIR-V frontend when a subgroup collective operation (e.g. `OpGroupNonUniformUMin`) or `OpGroupNonUniformBallot` used an argument whose value needed to be spilled to a temporary variable, such as when the argument was computed inside a loop. By @nazar-pc in [#9957](https://github.com/gfx-rs/wgpu/issues/9957). - Lower `@builtin(instance_index)` in `@any_hit` and `@closest_hit` entry points to SPIR-V's `InstanceId` rather than `InstanceIndex`, which Vulkan only permits in the vertex stage. By @JMS55 in [10154](https://github.com/gfx-rs/wgpu/pull/10154). - Report WGSL type mismatches in `return` statements, function call arguments and composite constructors as WGSL errors naming both types, instead of IR validation errors that could only name the operands by handle index (such as "The \`return\` expression Some([1]) does not match the declared return type Some([1])"). By @emilk in [#9973](https://github.com/gfx-rs/wgpu/pull/9973). +- Implement constant evaluation of the `extractBits`, `insertBits`, `faceForward`, `reflect`, and `refract` built-in functions. Evaluates expression at compile time to report issues early like `offset` and `count` selecting bits beyond the width of the data. By @MinerSheep in [#10258](https://github.com/gfx-rs/wgpu/pull/10258). #### Validation diff --git a/cts_runner/fail.lst b/cts_runner/fail.lst index 568d86484..0f8734efd 100644 --- a/cts_runner/fail.lst +++ b/cts_runner/fail.lst @@ -79,11 +79,11 @@ webgpu:shader,validation,expression,call,builtin,determinant:* // 71%, abstract webgpu:shader,validation,expression,call,builtin,distance:* // 66%, scalar distance uses wrong formula (sqrt instead of abs) webgpu:shader,validation,expression,call,builtin,dot4I8Packed:* // 91%, missing const eval (#4507) webgpu:shader,validation,expression,call,builtin,dot4U8Packed:* // 91%, missing const eval (#4507) -webgpu:shader,validation,expression,call,builtin,extractBits:* // 62%, const eval issues -webgpu:shader,validation,expression,call,builtin,faceForward:* // 68%, const eval overflow for abstract/f16 +webgpu:shader,validation,expression,call,builtin,extractBits:count_offset:* // 67%, `offset` + `count` out of range is not a pipeline creation error when they are override expressions +webgpu:shader,validation,expression,call,builtin,faceForward:values:* // 67%, abstract-float operands are concretized to f32 rather than kept abstract, https://github.com/gfx-rs/wgpu/issues/7405 webgpu:shader,validation,expression,call,builtin,fma:* // 85%, const eval issues webgpu:shader,validation,expression,call,builtin,frexp:* // 39%, const/override eval not supported -webgpu:shader,validation,expression,call,builtin,insertBits:* // 76%, missing const eval support +webgpu:shader,validation,expression,call,builtin,insertBits:count_offset:* // 67%, `offset` + `count` out of range is not a pipeline creation error when they are override expressions webgpu:shader,validation,expression,call,builtin,inverseSqrt:* // 61%, const eval overflow for abstract/f16 webgpu:shader,validation,expression,call,builtin,ldexp:* // 43%, const eval not implemented webgpu:shader,validation,expression,call,builtin,mix:* // 66%, const eval issues @@ -98,8 +98,8 @@ webgpu:shader,validation,expression,call,builtin,pack4xI8Clamp:* // 74%, missing webgpu:shader,validation,expression,call,builtin,pack4xU8:* // 74%, missing const eval (#4507) webgpu:shader,validation,expression,call,builtin,pack4xU8Clamp:* // 74%, missing const eval (#4507) webgpu:shader,validation,expression,call,builtin,quantizeToF16:* // 77%, overflow validation issues -webgpu:shader,validation,expression,call,builtin,reflect:* // 39%, const eval not implemented -webgpu:shader,validation,expression,call,builtin,refract:* // 44%, const eval not implemented +webgpu:shader,validation,expression,call,builtin,reflect:values:* // 67%, abstract-float operands are concretized to f32 rather than kept abstract, https://github.com/gfx-rs/wgpu/issues/7405 +webgpu:shader,validation,expression,call,builtin,refract:values:* // 67%, abstract-float operands are concretized to f32 rather than kept abstract, https://github.com/gfx-rs/wgpu/issues/7405 webgpu:shader,validation,expression,call,builtin,smoothstep:* // 69%, const eval issues webgpu:shader,validation,expression,call,builtin,textureDimensions:* // >99%, no external texture in deno webgpu:shader,validation,expression,call,builtin,textureGather:* // 99%, https://github.com/gfx-rs/wgpu/issues/8876 diff --git a/cts_runner/test.lst b/cts_runner/test.lst index 0a80f8ae8..7e6d14d0e 100644 --- a/cts_runner/test.lst +++ b/cts_runner/test.lst @@ -427,10 +427,18 @@ webgpu:shader,validation,expression,call,builtin,distance:values:stage="constant webgpu:shader,validation,expression,call,builtin,dot:* webgpu:shader,validation,expression,call,builtin,exp:* webgpu:shader,validation,expression,call,builtin,exp2:* +webgpu:shader,validation,expression,call,builtin,extractBits:must_use:* +webgpu:shader,validation,expression,call,builtin,extractBits:typed_arguments:* +webgpu:shader,validation,expression,call,builtin,extractBits:values:* +webgpu:shader,validation,expression,call,builtin,faceForward:args:* +webgpu:shader,validation,expression,call,builtin,faceForward:must_use:* webgpu:shader,validation,expression,call,builtin,firstLeadingBit:* webgpu:shader,validation,expression,call,builtin,firstTrailingBit:* webgpu:shader,validation,expression,call,builtin,floor:* webgpu:shader,validation,expression,call,builtin,fract:* +webgpu:shader,validation,expression,call,builtin,insertBits:must_use:* +webgpu:shader,validation,expression,call,builtin,insertBits:typed_arguments:* +webgpu:shader,validation,expression,call,builtin,insertBits:values:* webgpu:shader,validation,expression,call,builtin,length:* webgpu:shader,validation,expression,call,builtin,log:* webgpu:shader,validation,expression,call,builtin,log2:* @@ -439,6 +447,11 @@ webgpu:shader,validation,expression,call,builtin,min:* webgpu:shader,validation,expression,call,builtin,normalize:* webgpu:shader,validation,expression,call,builtin,pow:* webgpu:shader,validation,expression,call,builtin,radians:* +webgpu:shader,validation,expression,call,builtin,reflect:args:* +webgpu:shader,validation,expression,call,builtin,reflect:must_use:* +webgpu:shader,validation,expression,call,builtin,refract:args:* +webgpu:shader,validation,expression,call,builtin,refract:must_use:* +webgpu:shader,validation,expression,call,builtin,refract:return:* webgpu:shader,validation,expression,call,builtin,reverseBits:* webgpu:shader,validation,expression,call,builtin,round:* webgpu:shader,validation,expression,call,builtin,saturate:* diff --git a/naga/src/front/wgsl/lower/mod.rs b/naga/src/front/wgsl/lower/mod.rs index 7a4cfb089..04b7e644c 100644 --- a/naga/src/front/wgsl/lower/mod.rs +++ b/naga/src/front/wgsl/lower/mod.rs @@ -4202,6 +4202,8 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { let rule = self.resolve_overloads(span, fun, fun_overloads, &lowered_arguments, ctx)?; self.apply_automatic_conversions_for_call(&rule, &mut lowered_arguments, ctx)?; + self.check_bitfield_range(span, fun, &rule, &lowered_arguments, ctx)?; + // If this function returns a predeclared type, register it // in `Module::special_types`. The typifier will expect to // be able to find it there. @@ -4218,6 +4220,48 @@ impl<'source, 'temp> Lowerer<'source, 'temp> { }) } + /// Check the `offset` and `count` arguments of a call to [`ExtractBits`] + /// or [`InsertBits`] to make sure it fits inside the number's `width`. + /// + /// If `offset` and `count` are fixed numbers and they pick bits outside + /// the range we must return a shader creation error. + /// + /// If the pipeline overrides the numbers, we do not check them here. + /// [`get_const_val`] reports them as non-const, so they fall through + /// this check. + /// + /// [`ExtractBits`]: ir::MathFunction::ExtractBits + /// [`InsertBits`]: ir::MathFunction::InsertBits + /// [`get_const_val`]: ExpressionContext::get_const_val + fn check_bitfield_range( + &mut self, + span: Span, + fun: ir::MathFunction, + rule: &proc::Rule, + arguments: &[Handle], + ctx: &ExpressionContext<'source, '_, '_>, + ) -> Result<'source, ()> { + let (builtin, offset, count) = match fun { + ir::MathFunction::ExtractBits => ("extractBits", 1, 2), + ir::MathFunction::InsertBits => ("insertBits", 2, 3), + _ => return Ok(()), + }; + + let (Ok(offset), Ok(count)) = ( + ctx.get_const_val::(arguments[offset]), + ctx.get_const_val::(arguments[count]), + ) else { + return Ok(()); + }; + + let Some(scalar) = rule.arguments[0].inner_with(&ctx.module.types).scalar() else { + return Ok(()); + }; + + proc::check_bitfield_range(builtin, offset, count, u32::from(scalar.width) * 8) + .map_err(|e| Box::new(Error::ConstantEvaluatorError(Box::new(e), span))) + } + /// Choose the right overload for a function call. /// /// Return a [`Rule`] representing the most preferred overload in diff --git a/naga/src/proc/constant_evaluator.rs b/naga/src/proc/constant_evaluator.rs index dc7703a6d..df9b8bc91 100644 --- a/naga/src/proc/constant_evaluator.rs +++ b/naga/src/proc/constant_evaluator.rs @@ -632,6 +632,19 @@ where } } +/// The dot product of `a` and `b`. Return `None` if it is not finite. +fn float_dot(a: &[F], b: &[F]) -> Option +where + F: num_traits::Float, +{ + let result = a + .iter() + .zip(b.iter()) + .map(|(&aa, &bb)| aa * bb) + .fold(F::zero(), |acc, x| acc + x); + result.is_finite().then_some(result) +} + #[derive(Debug)] enum Behavior<'a> { Wgsl(WgslRestrictions<'a>), @@ -886,6 +899,16 @@ pub enum ConstantEvaluatorError { InvalidMathArgCount(crate::MathFunction, usize, usize), #[error("{0} built-in function argument is out of valid range")] InvalidMathArgValue(String), + #[error( + "`offset` + `count` must be at most {width}, the bit width of the operand of the \ + {builtin} built-in function, but {offset} + {count} is greater" + )] + BitfieldRangeTooLarge { + builtin: &'static str, + offset: u32, + count: u32, + width: u32, + }, #[error("Cannot apply relational function to type")] InvalidRelationalArg(RelationalFunction), #[error("value of `low` is greater than `high` for clamp built-in function")] @@ -1813,6 +1836,40 @@ impl<'a> ConstantEvaluator<'a> { crate::MathFunction::ReverseBits => { component_wise_concrete_int!(self, span, [arg], |e| { Ok([e.reverse_bits()]) }) } + crate::MathFunction::ExtractBits => { + // https://www.w3.org/TR/WGSL/#extractBits-signed-builtin + let (offset, count) = self.bitfield_range(arg1.unwrap(), arg2.unwrap(), span)?; + let e = self.extract_vec(arg, true)?; + + let result = match_literal_vector!(match e => LiteralVector { + I16 => |e| { extract_bits(e, offset, count)? }, + U16 => |e| { extract_bits(e, offset, count)? }, + I32 => |e| { extract_bits(e, offset, count)? }, + U32 => |e| { extract_bits(e, offset, count)? }, + I64 => |e| { extract_bits(e, offset, count)? }, + U64 => |e| { extract_bits(e, offset, count)? }, + })?; + result.register_as_evaluated_expr(self, span) + } + crate::MathFunction::InsertBits => { + // https://www.w3.org/TR/WGSL/#insertBits-builtin + let (offset, count) = self.bitfield_range(arg2.unwrap(), arg3.unwrap(), span)?; + let e = self.extract_vec(arg, true)?; + let newbits = self.extract_vec(arg1.unwrap(), true)?; + if e.len() != newbits.len() { + return Err(ConstantEvaluatorError::InvalidMathArg); + } + + let result = match_literal_vector!(match (e, newbits) => LiteralVector { + I16 => |e, n| { insert_bits(e, n, offset, count)? }, + U16 => |e, n| { insert_bits(e, n, offset, count)? }, + I32 => |e, n| { insert_bits(e, n, offset, count)? }, + U32 => |e, n| { insert_bits(e, n, offset, count)? }, + I64 => |e, n| { insert_bits(e, n, offset, count)? }, + U64 => |e, n| { insert_bits(e, n, offset, count)? }, + })?; + result.register_as_evaluated_expr(self, span) + } crate::MathFunction::FirstTrailingBit => { component_wise_concrete_int(self, span, [arg], |ci| Ok(first_trailing_bit(ci))) } @@ -1836,22 +1893,6 @@ impl<'a> ConstantEvaluator<'a> { return Err(ConstantEvaluatorError::InvalidMathArg); } - fn float_dot_checked

(a: &[P], b: &[P]) -> Result - where - P: num_traits::Float, - { - let result = a - .iter() - .zip(b.iter()) - .map(|(&aa, &bb)| aa * bb) - .fold(P::zero(), |acc, x| acc + x); - if result.is_finite() { - Ok(result) - } else { - Err(ConstantEvaluatorError::Overflow("in dot built-in".into())) - } - } - fn int_dot_checked

(a: &[P], b: &[P]) -> Result where P: num_traits::PrimInt + num_traits::CheckedAdd + num_traits::CheckedMul, @@ -1882,7 +1923,11 @@ impl<'a> ConstantEvaluator<'a> { } let result = match_literal_vector!(match (e1, e2) => Literal { - Float => |e1, e2| { float_dot_checked(e1, e2)? }, + Float => |e1, e2| { + float_dot(e1, e2).ok_or_else(|| { + ConstantEvaluatorError::Overflow("in mathfunction::dot".into()) + })? + }, AbstractInt => |e1, e2 | { int_dot_checked(e1, e2)? }, I32 => |e1, e2| { int_dot_wrapping(e1, e2) }, U32 => |e1, e2| { int_dot_wrapping(e1, e2) }, @@ -1961,23 +2006,71 @@ impl<'a> ConstantEvaluator<'a> { })?; result.register_as_evaluated_expr(self, span) } + crate::MathFunction::FaceForward => { + // https://www.w3.org/TR/WGSL/#faceForward-builtin + let e1 = self.extract_vec(arg, false)?; + let e2 = self.extract_vec(arg1.unwrap(), false)?; + let e3 = self.extract_vec(arg2.unwrap(), false)?; + if e1.len() != e2.len() || e1.len() != e3.len() { + return Err(ConstantEvaluatorError::InvalidMathArg); + } + + let result = match_literal_vector!(match (e1, e2, e3) => LiteralVector { + Float => |e1, e2, e3| { + float_face_forward(e1, e2, e3).ok_or_else(|| { + ConstantEvaluatorError::Overflow("in mathfunction::faceforward".into()) + })? + }, + })?; + result.register_as_evaluated_expr(self, span) + } + crate::MathFunction::Reflect => { + // https://www.w3.org/TR/WGSL/#reflect-builtin + let e1 = self.extract_vec(arg, false)?; + let e2 = self.extract_vec(arg1.unwrap(), false)?; + if e1.len() != e2.len() { + return Err(ConstantEvaluatorError::InvalidMathArg); + } + + let result = match_literal_vector!(match (e1, e2) => LiteralVector { + Float => |e1, e2| { + float_reflect(e1, e2) + .ok_or_else(|| ConstantEvaluatorError::Overflow("in mathfunction::reflect".into()))? + }, + })?; + result.register_as_evaluated_expr(self, span) + } + crate::MathFunction::Refract => { + // https://www.w3.org/TR/WGSL/#refract-builtin + let e1 = self.extract_vec(arg, false)?; + let e2 = self.extract_vec(arg1.unwrap(), false)?; + // `e3` is the scalar ratio of indices of refraction, extracted + // as a LiteralVector like `e1` and `e2`. + let e3 = self.extract_vec(arg2.unwrap(), true)?; + if e1.len() != e2.len() || e3.len() != 1 { + return Err(ConstantEvaluatorError::InvalidMathArg); + } + + let result = match_literal_vector!(match (e1, e2, e3) => LiteralVector { + Float => |e1, e2, e3| { + float_refract(e1, e2, e3[0]) + .ok_or_else(|| ConstantEvaluatorError::Overflow("in mathfunction::refract".into()))? + }, + })?; + result.register_as_evaluated_expr(self, span) + } // unimplemented crate::MathFunction::Modf | crate::MathFunction::Frexp | crate::MathFunction::Ldexp | crate::MathFunction::Outer - | crate::MathFunction::FaceForward - | crate::MathFunction::Reflect - | crate::MathFunction::Refract | crate::MathFunction::Mix | crate::MathFunction::SmoothStep | crate::MathFunction::Inverse | crate::MathFunction::Transpose | crate::MathFunction::Determinant | crate::MathFunction::QuantizeToF16 - | crate::MathFunction::ExtractBits - | crate::MathFunction::InsertBits | crate::MathFunction::Pack4x8snorm | crate::MathFunction::Pack4x8unorm | crate::MathFunction::Pack2x16snorm @@ -2169,6 +2262,26 @@ impl<'a> ConstantEvaluator<'a> { } } + /// Extract the `offset` and `count` arguments shared by the `extractBits` + /// and `insertBits` built ins, both of which are `u32` scalars. + fn bitfield_range( + &mut self, + offset: Handle, + count: Handle, + span: Span, + ) -> Result<(u32, u32), ConstantEvaluatorError> { + let offset = self.eval_zero_value_and_splat(offset, span)?; + let count = self.eval_zero_value_and_splat(count, span)?; + + match (&self.expressions[offset], &self.expressions[count]) { + ( + &Expression::Literal(Literal::U32(offset)), + &Expression::Literal(Literal::U32(count)), + ) => Ok((offset, count)), + _ => Err(ConstantEvaluatorError::InvalidMathArg), + } + } + fn array_length( &mut self, array: Handle, @@ -3695,6 +3808,320 @@ impl<'a> ConstantEvaluator<'a> { } } +/// If `dot(e2, e3)` is negative, `e1` returns, otherwise `-e1`. +fn float_face_forward( + e1: &[F], + e2: &[F], + e3: &[F], +) -> Option> +where + F: num_traits::Float, +{ + let d = float_dot(e2, e3)?; + + let mut out = ArrayVec::new(); + for &e in e1 { + out.push(if d < F::zero() { e } else { -e }); + } + Some(out) +} + +/// The reflection of incident vector `e1` off a surface oriented `e2`, +/// `e1 - 2 * dot(e2, e1) * e2`. +fn float_reflect(e1: &[F], e2: &[F]) -> Option> +where + F: num_traits::Float, +{ + let d = float_dot(e2, e1)?; + let two = F::one() + F::one(); + + let mut out = ArrayVec::new(); + for (&a, &b) in e1.iter().zip(e2) { + let r = a - two * d * b; + if !r.is_finite() { + return None; + } + out.push(r); + } + Some(out) +} + +/// The refraction of incident vector `e1` through a surface with normal `e2`, +/// for a ratio of indices of refraction `e3`. +fn float_refract(e1: &[F], e2: &[F], e3: F) -> Option> +where + F: num_traits::Float, +{ + let d = float_dot(e2, e1)?; + let one = F::one(); + + let k = one - e3 * e3 * (one - d * d); + if !k.is_finite() { + return None; + } + + let mut out = ArrayVec::new(); + + // If there is total internal reflection, returns zero vector. + if k < F::zero() { + for _ in e1 { + out.push(F::zero()); + } + return Some(out); + } + + let scale = e3 * d + k.sqrt(); + for (&a, &b) in e1.iter().zip(e2) { + let r = e3 * a - scale * b; + if !r.is_finite() { + return None; + } + out.push(r); + } + Some(out) +} + +#[test] +fn face_forward_smoke() { + #[track_caller] + fn ff(e1: &[f32], e2: &[f32], e3: &[f32]) -> Vec { + float_face_forward(e1, e2, e3).unwrap().to_vec() + } + + // If `dot(e2, e3)` is negative, return `e1`, otherwise return `-e1`. + assert_eq!(ff(&[1.0, 2.0], &[-1.0, 0.0], &[1.0, 0.0]), [1.0, 2.0]); + assert_eq!(ff(&[1.0, 2.0], &[1.0, 0.0], &[1.0, 0.0]), [-1.0, -2.0]); + + // Zero = flip `e1`. + assert_eq!(ff(&[1.0, 2.0], &[0.0, 1.0], &[1.0, 0.0]), [-1.0, -2.0]); + + assert_eq!( + ff(&[1.0, 2.0, 3.0], &[-1.0, 0.0, 0.0], &[1.0, 0.0, 0.0]), + [1.0, 2.0, 3.0] + ); + + // Return None if `dot(e2, e3)` is too big to compute. + assert!(float_face_forward(&[1.0f32, 0.0], &[f32::MAX, 0.0], &[f32::MAX, 0.0]).is_none()); +} + +#[test] +fn reflect_smoke() { + #[track_caller] + fn rf(e1: &[f32], e2: &[f32]) -> Vec { + float_reflect(e1, e2).unwrap().to_vec() + } + + // Bouncing off a floor flips the component along the normal. + assert_eq!(rf(&[1.0, -1.0], &[0.0, 1.0]), [1.0, 1.0]); + assert_eq!(rf(&[1.0, -1.0, 0.0], &[0.0, 1.0, 0.0]), [1.0, 1.0, 0.0]); + + // Head-on reverses the vector entirely. + assert_eq!(rf(&[1.0, 0.0], &[1.0, 0.0]), [-1.0, 0.0]); + + // A surface parallel to the incident vector leaves it alone. + assert_eq!(rf(&[1.0, 0.0], &[0.0, 1.0]), [1.0, 0.0]); + + assert!(float_reflect(&[1.0f32, 0.0], &[f32::MAX, 0.0]).is_none()); +} + +#[test] +fn refract_smoke() { + #[track_caller] + fn rr(e1: &[f32], e2: &[f32], e3: f32) -> Vec { + float_refract(e1, e2, e3).unwrap().to_vec() + } + + // No change if blending ratio is 1 and a straight surface collision. + assert_eq!(rr(&[0.0, -1.0], &[0.0, 1.0], 1.0), [0.0, -1.0]); + assert_eq!(rr(&[0.5, -0.5], &[0.0, 1.0], 1.0), [0.5, -0.5]); + + // A normal facing the opposite way will bend vector to other side. + assert_eq!(rr(&[0.5, -0.5], &[0.0, -1.0], 1.0), [0.5, 0.5]); + + // Ratios below 1 shorten the transmitted vector. + assert_eq!(rr(&[0.0, -1.0], &[0.0, 1.0], 0.5), [0.0, -1.0]); + + // ‘no refraction possible’ means k goes negative and result is zero. + assert_eq!(rr(&[0.8, -0.6], &[0.0, 1.0], 2.0), [0.0, 0.0]); + assert_eq!( + rr(&[0.8, -0.6, 0.0], &[0.0, 1.0, 0.0], 2.0), + [0.0, 0.0, 0.0] + ); + + assert!(float_refract(&[1.0f32, 0.0], &[f32::MAX, 0.0], 1.0).is_none()); + assert!(float_refract(&[1.0f32, 0.0], &[0.0, 1.0], f32::MAX).is_none()); +} + +/// Return a u32 according to the number of bits in `T`, the `w` of the +/// `extractBits` and `insertBits` specifications. +const fn bit_width() -> u32 { + size_of::() as u32 * 8 +} + +/// Reject the `offset` and `count` arguments of `extractBits` and `insertBits` +/// if they select bits outside an operand `width` bits wide. +/// +/// The WGSL specification says that this is a shader creation error if `offset` +/// and `count` are const expressions, *even if the operand is not*, so the WGSL +/// front end will fail immediately if it sees both are const. +pub fn check_bitfield_range( + builtin: &'static str, + offset: u32, + count: u32, + width: u32, +) -> Result<(), ConstantEvaluatorError> { + if u64::from(offset) + u64::from(count) > u64::from(width) { + return Err(ConstantEvaluatorError::BitfieldRangeTooLarge { + builtin, + offset, + count, + width, + }); + } + Ok(()) +} + +fn extract_bits( + e: &[T], + offset: u32, + count: u32, +) -> Result, ConstantEvaluatorError> +where + T: num_traits::PrimInt, +{ + check_bitfield_range("extractBits", offset, count, bit_width::())?; + let w = bit_width::(); + + let mut out = ArrayVec::new(); + for &e in e { + out.push(if count == 0 { + T::zero() + } else { + // Shift field up then shift back down. + // - if signed, the empty space fills with the field's top bit + // - if unsigned, the empty space will fill with zeroes + // count is never zero here + (e << (w - offset - count) as usize) >> (w - count) as usize + }); + } + Ok(out) +} + +fn insert_bits( + e: &[T], + newbits: &[T], + offset: u32, + count: u32, +) -> Result, ConstantEvaluatorError> +where + T: num_traits::PrimInt, +{ + check_bitfield_range("insertBits", offset, count, bit_width::())?; + let w = bit_width::(); + + let mut out = ArrayVec::new(); + for (&e, &newbits) in e.iter().zip(newbits) { + out.push(if count == 0 { + e + } else { + let mask = (!T::zero()).unsigned_shr(w - count) << offset as usize; + (e & !mask) | ((newbits << offset as usize) & mask) + }); + } + Ok(out) +} + +#[cfg(test)] +fn extract_bits_scalar(e: T, offset: u32, count: u32) -> T { + extract_bits(&[e], offset, count).unwrap()[0] +} + +#[cfg(test)] +fn insert_bits_scalar(e: T, newbits: T, offset: u32, count: u32) -> T { + insert_bits(&[e], &[newbits], offset, count).unwrap()[0] +} + +#[test] +fn extract_bits_smoke() { + // `count` of zero always yields zero, whatever `offset` selects. + assert_eq!(extract_bits_scalar(0xffffffff_u32, 0, 0), 0); + assert_eq!(extract_bits_scalar(-1_i32, 32, 0), 0); + + // Selecting the whole width is the identity. + assert_eq!(extract_bits_scalar(0x12345678_u32, 0, 32), 0x12345678); + assert_eq!(extract_bits_scalar(i32::MIN, 0, 32), i32::MIN); + + // Unsigned extraction fills the bits above the field with zero. + assert_eq!(extract_bits_scalar(0x12345678_u32, 8, 8), 0x56); + assert_eq!(extract_bits_scalar(0xf0000000_u32, 28, 4), 0xf); + assert_eq!(extract_bits_scalar(0x12345678_u32, 31, 1), 0); + + // Signed extraction fills them from the top bit of the field instead. + assert_eq!(extract_bits_scalar(0x12345678_i32, 8, 8), 0x56); + assert_eq!(extract_bits_scalar(0x8_i32, 3, 1), -1); + assert_eq!(extract_bits_scalar(0xf0000000_u32 as i32, 28, 4), -1); + assert_eq!(extract_bits_scalar(0x70000000_i32, 28, 4), 7); + + // Widths other than 32 use their own `w`. + assert_eq!(extract_bits_scalar(0x1234_u16, 4, 8), 0x23); + assert_eq!(extract_bits_scalar(-1_i16, 0, 16), -1); + assert_eq!( + extract_bits_scalar(0x123456789abcdef0_u64, 32, 32), + 0x12345678 + ); + assert_eq!(extract_bits_scalar(-1_i64, 63, 1), -1); + + // `offset + count` past the end of the type is a shader creation error. + assert!(extract_bits(&[0_u32], 30, 8).is_err()); + assert!(extract_bits(&[0_u32], 33, 0).is_err()); + assert!(extract_bits(&[0_u16], 8, 16).is_err()); + assert!(extract_bits(&[0_u32], u32::MAX, u32::MAX).is_err()); + assert!(extract_bits(&[0_u32], 32, 0).is_ok()); +} + +#[test] +fn insert_bits_smoke() { + // `count` of zero leaves `e` untouched. + assert_eq!( + insert_bits_scalar(0x12345678_u32, 0xffffffff, 0, 0), + 0x12345678 + ); + assert_eq!(insert_bits_scalar(-1_i32, 0, 32, 0), -1); + + // Covering the whole width will replace `e` entirely. + assert_eq!( + insert_bits_scalar(0x12345678_u32, 0xdeadbeef, 0, 32), + 0xdeadbeef + ); + assert_eq!(insert_bits_scalar(0_i32, i32::MIN, 0, 32), i32::MIN); + + // Only bits `offset..offset + count` are taken from `newbits`, and only its + // low `count` bits are used. + assert_eq!(insert_bits_scalar(0x12345678_u32, 0xff, 8, 8), 0x1234ff78); + assert_eq!(insert_bits_scalar(0x12345678_u32, 0xabcd, 8, 8), 0x1234cd78); + assert_eq!(insert_bits_scalar(0_u32, 0xf, 28, 4), 0xf0000000); + assert_eq!(insert_bits_scalar(0_u32, 1, 31, 1), 0x80000000); + + // Signed operands set the sign bit like any other. + assert_eq!(insert_bits_scalar(0_i32, -1, 31, 1), i32::MIN); + assert_eq!(insert_bits_scalar(-1_i32, 0, 0, 31), i32::MIN); + + // Widths other than 32 use their own `w`. + assert_eq!(insert_bits_scalar(0x1234_u16, 0xf, 4, 4), 0x12f4); + assert_eq!(insert_bits_scalar(0_i16, -1, 15, 1), i16::MIN); + assert_eq!( + insert_bits_scalar(0_u64, 0xffffffff, 32, 32), + 0xffffffff00000000 + ); + + // `offset + count` past the end of the type is a shader creation error. + assert!(insert_bits(&[0_u32], &[0], 30, 8).is_err()); + assert!(insert_bits(&[0_u32], &[0], 33, 0).is_err()); + assert!(insert_bits(&[0_u16], &[0], 8, 16).is_err()); + assert!(insert_bits(&[0_u32], &[0], u32::MAX, u32::MAX).is_err()); + assert!(insert_bits(&[0_u32], &[0], 32, 0).is_ok()); +} + fn first_trailing_bit(concrete_int: ConcreteInt<1>) -> ConcreteInt<1> { // NOTE: Bit indices for this built-in start at 0 at the "right" (or LSB). For example, a value // of 1 means the least significant bit is set. Therefore, an input of `0x[80 00…]` would diff --git a/naga/src/proc/mod.rs b/naga/src/proc/mod.rs index 0a094528d..4e4030c37 100644 --- a/naga/src/proc/mod.rs +++ b/naga/src/proc/mod.rs @@ -14,7 +14,8 @@ mod type_methods; mod typifier; pub use constant_evaluator::{ - ConstantEvaluator, ConstantEvaluatorError, ExpressionKind, ExpressionKindTracker, + check_bitfield_range, ConstantEvaluator, ConstantEvaluatorError, ExpressionKind, + ExpressionKindTracker, }; pub use emitter::Emitter; pub use index::{BoundsCheckPolicies, BoundsCheckPolicy, IndexableLength, IndexableLengthError}; diff --git a/naga/tests/naga/wgsl_errors.rs b/naga/tests/naga/wgsl_errors.rs index 59b176313..416a98a95 100644 --- a/naga/tests/naga/wgsl_errors.rs +++ b/naga/tests/naga/wgsl_errors.rs @@ -4383,6 +4383,187 @@ fn const_eval_value_errors() { assert!(variant("f32(abs(-9223372036854775807 - 1))").is_ok()); } +/// Constant evaluation of `extractBits`. +/// +/// +#[test] +fn const_eval_extract_bits() { + check_success( + " + // Unsigned: the bits above the field are zero. + const_assert extractBits(0x12345678u, 8u, 8u) == 0x56u; + const_assert extractBits(0xf0000000u, 28u, 4u) == 0xfu; + const_assert extractBits(0x80000000u, 31u, 1u) == 1u; + + // Signed: the bits above the field copy the top bit of the field. + const_assert extractBits(0x12345678i, 8u, 8u) == 0x56i; + const_assert extractBits(8i, 3u, 1u) == -1i; + const_assert extractBits(0x70000000i, 28u, 4u) == 7i; + + // A `count` of zero yields zero, and covering the full width is the identity. + const_assert extractBits(0xffffffffu, 0u, 0u) == 0u; + const_assert extractBits(0xffffffffu, 32u, 0u) == 0u; + const_assert extractBits(0x12345678u, 0u, 32u) == 0x12345678u; + const_assert extractBits(-1i, 0u, 32u) == -1i; + + // Component-wise on vectors. + const_assert all(extractBits(vec2(0x12345678u, 0xf0f0f0f0u), 4u, 8u) == vec2(0x67u, 0xfu)); + const_assert all(extractBits(vec3(8i, 0i, -1i), 3u, 1u) == vec3(-1i, 0i, -1i)); + ", + ); +} + +/// Constant evaluation of `insertBits`. +/// +/// +#[test] +fn const_eval_insert_bits() { + check_success( + " + // Only bits `offset..offset + count` change, and only the low `count` + // bits of `newbits` are read. + const_assert insertBits(0x12345678u, 0xffu, 8u, 8u) == 0x1234ff78u; + const_assert insertBits(0x12345678u, 0xabcdu, 8u, 8u) == 0x1234cd78u; + const_assert insertBits(0u, 1u, 31u, 1u) == 0x80000000u; + const_assert insertBits(0i, -1i, 31u, 1u) == -2147483647i - 1i; + const_assert insertBits(-1i, 0i, 0u, 31u) == -2147483647i - 1i; + + // A `count` of zero leaves `e` untouched, and covering the full width + // replaces it entirely. + const_assert insertBits(0x12345678u, 0xffffffffu, 0u, 0u) == 0x12345678u; + const_assert insertBits(0x12345678u, 0xffffffffu, 32u, 0u) == 0x12345678u; + const_assert insertBits(0x12345678u, 0xdeadbeefu, 0u, 32u) == 0xdeadbeefu; + + // Component-wise on vectors. + const_assert all(insertBits(vec2(0u, 0u), vec2(0xfu, 0x3u), 4u, 4u) == vec2(0xf0u, 0x30u)); + ", + ); +} + +/// Constant evaluation of `faceForward`, `reflect` and `refract`. +/// +/// The values below are chosen so that every `f32` result doesn't round. +#[test] +fn const_eval_geometry() { + check_success( + " + // faceForward returns `e1` when `dot(e2, e3)` is negative and `-e1` + // otherwise, including when the dot product is exactly zero. + const_assert all(faceForward(vec2(1.0, 2.0), vec2(-1.0, 0.0), vec2(1.0, 0.0)) == vec2(1.0, 2.0)); + const_assert all(faceForward(vec2(1.0, 2.0), vec2(1.0, 0.0), vec2(1.0, 0.0)) == vec2(-1.0, -2.0)); + const_assert all(faceForward(vec2(1.0, 2.0), vec2(0.0, 1.0), vec2(1.0, 0.0)) == vec2(-1.0, -2.0)); + const_assert all(faceForward(vec3(1.0, 2.0, 3.0), vec3(-1.0, 0.0, 0.0), vec3(1.0, 0.0, 0.0)) == vec3(1.0, 2.0, 3.0)); + + // reflect is `e1 - 2 * dot(e2, e1) * e2`. A surface parallel to the + // incident vector leaves it alone. + const_assert all(reflect(vec2(1.0, -1.0), vec2(0.0, 1.0)) == vec2(1.0, 1.0)); + const_assert all(reflect(vec2(1.0, 0.0), vec2(1.0, 0.0)) == vec2(-1.0, 0.0)); + const_assert all(reflect(vec2(1.0, 0.0), vec2(0.0, 1.0)) == vec2(1.0, 0.0)); + const_assert all(reflect(vec3(1.0, -1.0, 0.0), vec3(0.0, 1.0, 0.0)) == vec3(1.0, 1.0, 0.0)); + + // refract transmits the vector when `k` is non-negative. + const_assert all(refract(vec2(0.0, -1.0), vec2(0.0, 1.0), 1.0) == vec2(0.0, -1.0)); + const_assert all(refract(vec2(0.5, -0.5), vec2(0.0, 1.0), 1.0) == vec2(0.5, -0.5)); + const_assert all(refract(vec2(0.5, -0.5), vec2(0.0, -1.0), 1.0) == vec2(0.5, 0.5)); + const_assert all(refract(vec2(0.0, -1.0), vec2(0.0, 1.0), 0.5) == vec2(0.0, -1.0)); + + // Under total internal reflection it returns the zero vector instead. + const_assert all(refract(vec2(0.8, -0.6), vec2(0.0, 1.0), 2.0) == vec2(0.0, 0.0)); + const_assert all(refract(vec3(0.8, -0.6, 0.0), vec3(0.0, 1.0, 0.0), 2.0) == vec3(0.0, 0.0, 0.0)); + ", + ); +} + +/// A dot product that overflows will cause a shader creation error. +/// No resulting to infinity. +#[test] +fn const_eval_geometry_overflow() { + for expr in [ + "faceForward(vec2(1.0, 0.0), vec2(3.4e38, 0.0), vec2(3.4e38, 0.0))", + "reflect(vec2(1.0, 0.0), vec2(3.4e38, 0.0))", + "refract(vec2(1.0, 0.0), vec2(3.4e38, 0.0), 1.0)", + ] { + let input = format!("const x = {expr};"); + let result = naga::front::wgsl::parse_str(&input); + assert!( + result.is_err(), + "expected `{expr}` to overflow, got {result:#?}" + ); + } +} + +/// offset + count past the width of the operand is an error w shader creation +/// when both are const expressions. +#[test] +fn bitfield_range_too_large() { + check_error_matches( + "const x = extractBits(0u, 30u, 8u);", + "`offset` + `count` must be at most 32", + ); + check_error_matches( + "const x = extractBits(0u, 33u, 0u);", + "`offset` + `count` must be at most 32", + ); + check_error_matches( + "const x = insertBits(0i, 0i, 1u, 32u);", + "`offset` + `count` must be at most 32", + ); + check_error_matches( + "const x = insertBits(vec2(0u), vec2(0u), 4294967295u, 4294967295u);", + "`offset` + `count` must be at most 32", + ); +} + +/// Same as above +/// offset + count past the width of the operand is an error w shader creation +/// when both are const expressions. +/// Even if the operand is not. +/// +/// +#[test] +fn bitfield_range_too_large_partially_const() { + // The operand is a function parameter, so these calls never reach constant + // evaluation at all. + check_error_matches( + "fn f(e: u32) -> u32 { return extractBits(e, 30u, 8u); }", + "`offset` + `count` must be at most 32", + ); + check_error_matches( + "fn f(e: i32) -> i32 { return extractBits(e, 30u, 8u); }", + "`offset` + `count` must be at most 32", + ); + check_error_matches( + "fn f(e: vec2) -> vec2 { return extractBits(e, 30u, 8u); }", + "`offset` + `count` must be at most 32", + ); + check_error_matches( + "fn f(e: u32, n: u32) -> u32 { return insertBits(e, n, 30u, 8u); }", + "`offset` + `count` must be at most 32", + ); + + // `offset` and `count` are const expressions here too, just not literals. + check_error_matches( + "const OFFSET = 30u; + fn f(e: u32) -> u32 { return extractBits(e, OFFSET, 8u); }", + "`offset` + `count` must be at most 32", + ); + + // In range, so these are all fine. + check_success("fn f(e: u32) -> u32 { return extractBits(e, 8u, 8u); }"); + check_success("fn f(e: u32) -> u32 { return extractBits(e, 0u, 32u); }"); + check_success("fn f(e: u32) -> u32 { return extractBits(e, 32u, 0u); }"); + check_success("fn f(e: u32, n: u32) -> u32 { return insertBits(e, n, 24u, 8u); }"); + + // Nothing to check when `offset` and `count` are not const expressions. + check_success("fn f(e: u32, o: u32, c: u32) -> u32 { return extractBits(e, o, c); }"); + + // An out-of-range override expression is a pipeline creation error. + check_success( + "override o: u32; + fn f(e: u32) -> u32 { return extractBits(e, o, 40u); }", + ); +} + #[test] fn subgroup_capability() { // Some of these tests should be `check_extension_validation` tests that