Debian Codegraph @

third_party/rust/naga/src/back/hlsl/writer.rs

raw
1 use alloc::{
2 format,
3 string::{String, ToString},
4 vec::Vec,
5 };
6 use core::{fmt, mem};
7
8 use super::{
9 help,
10 help::{
11 WrappedArrayLength, WrappedConstructor, WrappedImageQuery, WrappedStructMatrixAccess,
12 WrappedZeroValue,
13 },
14 storage::StoreValue,
15 BackendResult, Error, FragmentEntryPoint, Options, PipelineOptions, ShaderModel,
16 };
17 use crate::{
18 back::{self, get_entry_points, Baked},
19 common,
20 proc::{self, index, NameKey},
21 valid, Handle, Module, RayQueryFunction, Scalar, ScalarKind, ShaderStage, TypeInner,
22 };
23
24 const LOCATION_SEMANTIC: &str = "LOC";
25 const SPECIAL_CBUF_TYPE: &str = "NagaConstants";
26 const SPECIAL_CBUF_VAR: &str = "_NagaConstants";
27 const SPECIAL_FIRST_VERTEX: &str = "first_vertex";
28 const SPECIAL_FIRST_INSTANCE: &str = "first_instance";
29 const SPECIAL_OTHER: &str = "other";
30
31 pub(crate) const MODF_FUNCTION: &str = "naga_modf";
32 pub(crate) const FREXP_FUNCTION: &str = "naga_frexp";
33 pub(crate) const EXTRACT_BITS_FUNCTION: &str = "naga_extractBits";
34 pub(crate) const INSERT_BITS_FUNCTION: &str = "naga_insertBits";
35 pub(crate) const SAMPLER_HEAP_VAR: &str = "nagaSamplerHeap";
36 pub(crate) const COMPARISON_SAMPLER_HEAP_VAR: &str = "nagaComparisonSamplerHeap";
37 pub(crate) const ABS_FUNCTION: &str = "naga_abs";
38 pub(crate) const DIV_FUNCTION: &str = "naga_div";
39 pub(crate) const MOD_FUNCTION: &str = "naga_mod";
40 pub(crate) const NEG_FUNCTION: &str = "naga_neg";
41 pub(crate) const F2I32_FUNCTION: &str = "naga_f2i32";
42 pub(crate) const F2U32_FUNCTION: &str = "naga_f2u32";
43 pub(crate) const F2I64_FUNCTION: &str = "naga_f2i64";
44 pub(crate) const F2U64_FUNCTION: &str = "naga_f2u64";
45
46 struct EpStructMember {
47 name: String,
48 ty: Handle<crate::Type>,
49 // technically, this should always be `Some`
50 // (we `debug_assert!` this in `write_interface_struct`)
51 binding: Option<crate::Binding>,
52 index: u32,
53 }
54
55 /// Structure contains information required for generating
56 /// wrapped structure of all entry points arguments
57 struct EntryPointBinding {
58 /// Name of the fake EP argument that contains the struct
59 /// with all the flattened input data.
60 arg_name: String,
61 /// Generated structure name
62 ty_name: String,
63 /// Members of generated structure
64 members: Vec<EpStructMember>,
65 }
66
67 pub(super) struct EntryPointInterface {
68 /// If `Some`, the input of an entry point is gathered in a special
69 /// struct with members sorted by binding.
70 /// The `EntryPointBinding::members` array is sorted by index,
71 /// so that we can walk it in `write_ep_arguments_initialization`.
72 input: Option<EntryPointBinding>,
73 /// If `Some`, the output of an entry point is flattened.
74 /// The `EntryPointBinding::members` array is sorted by binding,
75 /// So that we can walk it in `Statement::Return` handler.
76 output: Option<EntryPointBinding>,
77 }
78
79 #[derive(Clone, Eq, PartialEq, PartialOrd, Ord)]
80 enum InterfaceKey {
81 Location(u32),
82 BuiltIn(crate::BuiltIn),
83 Other,
84 }
85
86 impl InterfaceKey {
87 const fn new(binding: Option<&crate::Binding>) -> Self {
88 match binding {
89 Some(&crate::Binding::Location { location, .. }) => Self::Location(location),
90 Some(&crate::Binding::BuiltIn(built_in)) => Self::BuiltIn(built_in),
91 None => Self::Other,
92 }
93 }
94 }
95
96 #[derive(Copy, Clone, PartialEq)]
97 enum Io {
98 Input,
99 Output,
100 }
101
102 const fn is_subgroup_builtin_binding(binding: &Option<crate::Binding>) -> bool {
103 let &Some(crate::Binding::BuiltIn(builtin)) = binding else {
104 return false;
105 };
106 matches!(
107 builtin,
108 crate::BuiltIn::SubgroupSize
109 | crate::BuiltIn::SubgroupInvocationId
110 | crate::BuiltIn::NumSubgroups
111 | crate::BuiltIn::SubgroupId
112 )
113 }
114
115 /// Information for how to generate a `binding_array<sampler>` access.
116 struct BindingArraySamplerInfo {
117 /// Variable name of the sampler heap
118 sampler_heap_name: &'static str,
119 /// Variable name of the sampler index buffer
120 sampler_index_buffer_name: String,
121 /// Variable name of the base index _into_ the sampler index buffer
122 binding_array_base_index_name: String,
123 }
124
125 impl<'a, W: fmt::Write> super::Writer<'a, W> {
126 pub fn new(out: W, options: &'a Options, pipeline_options: &'a PipelineOptions) -> Self {
127 Self {
128 out,
129 names: crate::FastHashMap::default(),
130 namer: proc::Namer::default(),
131 options,
132 pipeline_options,
133 entry_point_io: crate::FastHashMap::default(),
134 named_expressions: crate::NamedExpressions::default(),
135 wrapped: super::Wrapped::default(),
136 written_committed_intersection: false,
137 written_candidate_intersection: false,
138 continue_ctx: back::continue_forward::ContinueCtx::default(),
139 temp_access_chain: Vec::new(),
140 need_bake_expressions: Default::default(),
141 }
142 }
143
144 fn reset(&mut self, module: &Module) {
145 self.names.clear();
146 self.namer.reset(
147 module,
148 &super::keywords::RESERVED_SET,
149 super::keywords::RESERVED_CASE_INSENSITIVE,
150 super::keywords::RESERVED_PREFIXES,
151 &mut self.names,
152 );
153 self.entry_point_io.clear();
154 self.named_expressions.clear();
155 self.wrapped.clear();
156 self.written_committed_intersection = false;
157 self.written_candidate_intersection = false;
158 self.continue_ctx.clear();
159 self.need_bake_expressions.clear();
160 }
161
162 /// Generates statements to be inserted immediately before and at the very
163 /// start of the body of each loop, to defeat infinite loop reasoning.
164 /// The 0th item of the returned tuple should be inserted immediately prior
165 /// to the loop and the 1st item should be inserted at the very start of
166 /// the loop body.
167 ///
168 /// See [`back::msl::Writer::gen_force_bounded_loop_statements`] for details.
169 fn gen_force_bounded_loop_statements(
170 &mut self,
171 level: back::Level,
172 ) -> Option<(String, String)> {
173 if !self.options.force_loop_bounding {
174 return None;
175 }
176
177 let loop_bound_name = self.namer.call("loop_bound");
178 let max = u32::MAX;
179 // Count down from u32::MAX rather than up from 0 to avoid hang on
180 // certain Intel drivers. See <https://github.com/gfx-rs/wgpu/issues/7319>.
181 let decl = format!("{level}uint2 {loop_bound_name} = uint2({max}u, {max}u);");
182 let level = level.next();
183 let break_and_inc = format!(
184 "{level}if (all({loop_bound_name} == uint2(0u, 0u))) {{ break; }}
185 {level}{loop_bound_name} -= uint2({loop_bound_name}.y == 0u, 1u);"
186 );
187
188 Some((decl, break_and_inc))
189 }
190
191 /// Helper method used to find which expressions of a given function require baking
192 ///
193 /// # Notes
194 /// Clears `need_bake_expressions` set before adding to it
195 fn update_expressions_to_bake(
196 &mut self,
197 module: &Module,
198 func: &crate::Function,
199 info: &valid::FunctionInfo,
200 ) {
201 use crate::Expression;
202 self.need_bake_expressions.clear();
203 for (exp_handle, expr) in func.expressions.iter() {
204 let expr_info = &info[exp_handle];
205 let min_ref_count = func.expressions[exp_handle].bake_ref_count();
206 if min_ref_count <= expr_info.ref_count {
207 self.need_bake_expressions.insert(exp_handle);
208 }
209
210 if let Expression::Math { fun, arg, arg1, .. } = *expr {
211 match fun {
212 crate::MathFunction::Asinh
213 | crate::MathFunction::Acosh
214 | crate::MathFunction::Atanh
215 | crate::MathFunction::Unpack2x16float
216 | crate::MathFunction::Unpack2x16snorm
217 | crate::MathFunction::Unpack2x16unorm
218 | crate::MathFunction::Unpack4x8snorm
219 | crate::MathFunction::Unpack4x8unorm
220 | crate::MathFunction::Unpack4xI8
221 | crate::MathFunction::Unpack4xU8
222 | crate::MathFunction::Pack2x16float
223 | crate::MathFunction::Pack2x16snorm
224 | crate::MathFunction::Pack2x16unorm
225 | crate::MathFunction::Pack4x8snorm
226 | crate::MathFunction::Pack4x8unorm
227 | crate::MathFunction::Pack4xI8
228 | crate::MathFunction::Pack4xU8
229 | crate::MathFunction::Pack4xI8Clamp
230 | crate::MathFunction::Pack4xU8Clamp => {
231 self.need_bake_expressions.insert(arg);
232 }
233 crate::MathFunction::CountLeadingZeros => {
234 let inner = info[exp_handle].ty.inner_with(&module.types);
235 if let Some(ScalarKind::Sint) = inner.scalar_kind() {
236 self.need_bake_expressions.insert(arg);
237 }
238 }
239 crate::MathFunction::Dot4U8Packed | crate::MathFunction::Dot4I8Packed => {
240 self.need_bake_expressions.insert(arg);
241 self.need_bake_expressions.insert(arg1.unwrap());
242 }
243 _ => {}
244 }
245 }
246
247 if let Expression::Derivative { axis, ctrl, expr } = *expr {
248 use crate::{DerivativeAxis as Axis, DerivativeControl as Ctrl};
249 if axis == Axis::Width && (ctrl == Ctrl::Coarse || ctrl == Ctrl::Fine) {
250 self.need_bake_expressions.insert(expr);
251 }
252 }
253
254 if let Expression::GlobalVariable(_) = *expr {
255 let inner = info[exp_handle].ty.inner_with(&module.types);
256
257 if let TypeInner::Sampler { .. } = *inner {
258 self.need_bake_expressions.insert(exp_handle);
259 }
260 }
261 }
262 for statement in func.body.iter() {
263 match *statement {
264 crate::Statement::SubgroupCollectiveOperation {
265 op: _,
266 collective_op: crate::CollectiveOperation::InclusiveScan,
267 argument,
268 result: _,
269 } => {
270 self.need_bake_expressions.insert(argument);
271 }
272 _ => {}
273 }
274 }
275 }
276
277 pub fn write(
278 &mut self,
279 module: &Module,
280 module_info: &valid::ModuleInfo,
281 fragment_entry_point: Option<&FragmentEntryPoint<'_>>,
282 ) -> Result<super::ReflectionInfo, Error> {
283 self.reset(module);
284
285 // Write special constants, if needed
286 if let Some(ref bt) = self.options.special_constants_binding {
287 writeln!(self.out, "struct {SPECIAL_CBUF_TYPE} {{")?;
288 writeln!(self.out, "{}int {};", back::INDENT, SPECIAL_FIRST_VERTEX)?;
289 writeln!(self.out, "{}int {};", back::INDENT, SPECIAL_FIRST_INSTANCE)?;
290 writeln!(self.out, "{}uint {};", back::INDENT, SPECIAL_OTHER)?;
291 writeln!(self.out, "}};")?;
292 write!(
293 self.out,
294 "ConstantBuffer<{}> {}: register(b{}",
295 SPECIAL_CBUF_TYPE, SPECIAL_CBUF_VAR, bt.register
296 )?;
297 if bt.space != 0 {
298 write!(self.out, ", space{}", bt.space)?;
299 }
300 writeln!(self.out, ");")?;
301
302 // Extra newline for readability
303 writeln!(self.out)?;
304 }
305
306 for (group, bt) in self.options.dynamic_storage_buffer_offsets_targets.iter() {
307 writeln!(self.out, "struct __dynamic_buffer_offsetsTy{} {{", group)?;
308 for i in 0..bt.size {
309 writeln!(self.out, "{}uint _{};", back::INDENT, i)?;
310 }
311 writeln!(self.out, "}};")?;
312 writeln!(
313 self.out,
314 "ConstantBuffer<__dynamic_buffer_offsetsTy{}> __dynamic_buffer_offsets{}: register(b{}, space{});",
315 group, group, bt.register, bt.space
316 )?;
317
318 // Extra newline for readability
319 writeln!(self.out)?;
320 }
321
322 // Save all entry point output types
323 let ep_results = module
324 .entry_points
325 .iter()
326 .map(|ep| (ep.stage, ep.function.result.clone()))
327 .collect::<Vec<(ShaderStage, Option<crate::FunctionResult>)>>();
328
329 self.write_all_mat_cx2_typedefs_and_functions(module)?;
330
331 // Write all structs
332 for (handle, ty) in module.types.iter() {
333 if let TypeInner::Struct { ref members, span } = ty.inner {
334 if module.types[members.last().unwrap().ty]
335 .inner
336 .is_dynamically_sized(&module.types)
337 {
338 // unsized arrays can only be in storage buffers,
339 // for which we use `ByteAddressBuffer` anyway.
340 continue;
341 }
342
343 let ep_result = ep_results.iter().find(|e| {
344 if let Some(ref result) = e.1 {
345 result.ty == handle
346 } else {
347 false
348 }
349 });
350
351 self.write_struct(
352 module,
353 handle,
354 members,
355 span,
356 ep_result.map(|r| (r.0, Io::Output)),
357 )?;
358 writeln!(self.out)?;
359 }
360 }
361
362 self.write_special_functions(module)?;
363
364 self.write_wrapped_expression_functions(module, &module.global_expressions, None)?;
365 self.write_wrapped_zero_value_functions(module, &module.global_expressions)?;
366
367 // Write all named constants
368 let mut constants = module
369 .constants
370 .iter()
371 .filter(|&(_, c)| c.name.is_some())
372 .peekable();
373 while let Some((handle, _)) = constants.next() {
374 self.write_global_constant(module, handle)?;
375 // Add extra newline for readability on last iteration
376 if constants.peek().is_none() {
377 writeln!(self.out)?;
378 }
379 }
380
381 // Write all globals
382 for (ty, _) in module.global_variables.iter() {
383 self.write_global(module, ty)?;
384 }
385
386 if !module.global_variables.is_empty() {
387 // Add extra newline for readability
388 writeln!(self.out)?;
389 }
390
391 let ep_range = get_entry_points(module, self.pipeline_options.entry_point.as_ref())
392 .map_err(|(stage, name)| Error::EntryPointNotFound(stage, name))?;
393
394 // Write all entry points wrapped structs
395 for index in ep_range.clone() {
396 let ep = &module.entry_points[index];
397 let ep_name = self.names[&NameKey::EntryPoint(index as u16)].clone();
398 let ep_io = self.write_ep_interface(
399 module,
400 &ep.function,
401 ep.stage,
402 &ep_name,
403 fragment_entry_point,
404 )?;
405 self.entry_point_io.insert(index, ep_io);
406 }
407
408 // Write all regular functions
409 for (handle, function) in module.functions.iter() {
410 let info = &module_info[handle];
411
412 // Check if all of the globals are accessible
413 if !self.options.fake_missing_bindings {
414 if let Some((var_handle, _)) =
415 module
416 .global_variables
417 .iter()
418 .find(|&(var_handle, var)| match var.binding {
419 Some(ref binding) if !info[var_handle].is_empty() => {
420 self.options.resolve_resource_binding(binding).is_err()
421 }
422 _ => false,
423 })
424 {
425 log::info!(
426 "Skipping function {:?} (name {:?}) because global {:?} is inaccessible",
427 handle,
428 function.name,
429 var_handle
430 );
431 continue;
432 }
433 }
434
435 let ctx = back::FunctionCtx {
436 ty: back::FunctionType::Function(handle),
437 info,
438 expressions: &function.expressions,
439 named_expressions: &function.named_expressions,
440 };
441 let name = self.names[&NameKey::Function(handle)].clone();
442
443 self.write_wrapped_functions(module, &ctx)?;
444
445 self.write_function(module, name.as_str(), function, &ctx, info)?;
446
447 writeln!(self.out)?;
448 }
449
450 let mut translated_ep_names = Vec::with_capacity(ep_range.len());
451
452 // Write all entry points
453 for index in ep_range {
454 let ep = &module.entry_points[index];
455 let info = module_info.get_entry_point(index);
456
457 if !self.options.fake_missing_bindings {
458 let mut ep_error = None;
459 for (var_handle, var) in module.global_variables.iter() {
460 match var.binding {
461 Some(ref binding) if !info[var_handle].is_empty() => {
462 if let Err(err) = self.options.resolve_resource_binding(binding) {
463 ep_error = Some(err);
464 break;
465 }
466 }
467 _ => {}
468 }
469 }
470 if let Some(err) = ep_error {
471 translated_ep_names.push(Err(err));
472 continue;
473 }
474 }
475
476 let ctx = back::FunctionCtx {
477 ty: back::FunctionType::EntryPoint(index as u16),
478 info,
479 expressions: &ep.function.expressions,
480 named_expressions: &ep.function.named_expressions,
481 };
482
483 self.write_wrapped_functions(module, &ctx)?;
484
485 if ep.stage == ShaderStage::Compute {
486 // HLSL is calling workgroup size "num threads"
487 let num_threads = ep.workgroup_size;
488 writeln!(
489 self.out,
490 "[numthreads({}, {}, {})]",
491 num_threads[0], num_threads[1], num_threads[2]
492 )?;
493 }
494
495 let name = self.names[&NameKey::EntryPoint(index as u16)].clone();
496 self.write_function(module, &name, &ep.function, &ctx, info)?;
497
498 if index < module.entry_points.len() - 1 {
499 writeln!(self.out)?;
500 }
501
502 translated_ep_names.push(Ok(name));
503 }
504
505 Ok(super::ReflectionInfo {
506 entry_point_names: translated_ep_names,
507 })
508 }
509
510 fn write_modifier(&mut self, binding: &crate::Binding) -> BackendResult {
511 match *binding {
512 crate::Binding::BuiltIn(crate::BuiltIn::Position { invariant: true }) => {
513 write!(self.out, "precise ")?;
514 }
515 crate::Binding::Location {
516 interpolation,
517 sampling,
518 ..
519 } => {
520 if let Some(interpolation) = interpolation {
521 if let Some(string) = interpolation.to_hlsl_str() {
522 write!(self.out, "{string} ")?
523 }
524 }
525
526 if let Some(sampling) = sampling {
527 if let Some(string) = sampling.to_hlsl_str() {
528 write!(self.out, "{string} ")?
529 }
530 }
531 }
532 crate::Binding::BuiltIn(_) => {}
533 }
534
535 Ok(())
536 }
537
538 //TODO: we could force fragment outputs to always go through `entry_point_io.output` path
539 // if they are struct, so that the `stage` argument here could be omitted.
540 fn write_semantic(
541 &mut self,
542 binding: &Option<crate::Binding>,
543 stage: Option<(ShaderStage, Io)>,
544 ) -> BackendResult {
545 match *binding {
546 Some(crate::Binding::BuiltIn(builtin)) if !is_subgroup_builtin_binding(binding) => {
547 let builtin_str = builtin.to_hlsl_str()?;
548 write!(self.out, " : {builtin_str}")?;
549 }
550 Some(crate::Binding::Location {
551 blend_src: Some(1), ..
552 }) => {
553 write!(self.out, " : SV_Target1")?;
554 }
555 Some(crate::Binding::Location { location, .. }) => {
556 if stage == Some((ShaderStage::Fragment, Io::Output)) {
557 write!(self.out, " : SV_Target{location}")?;
558 } else {
559 write!(self.out, " : {LOCATION_SEMANTIC}{location}")?;
560 }
561 }
562 _ => {}
563 }
564
565 Ok(())
566 }
567
568 fn write_interface_struct(
569 &mut self,
570 module: &Module,
571 shader_stage: (ShaderStage, Io),
572 struct_name: String,
573 mut members: Vec<EpStructMember>,
574 ) -> Result<EntryPointBinding, Error> {
575 // Sort the members so that first come the user-defined varyings
576 // in ascending locations, and then built-ins. This allows VS and FS
577 // interfaces to match with regards to order.
578 members.sort_by_key(|m| InterfaceKey::new(m.binding.as_ref()));
579
580 write!(self.out, "struct {struct_name}")?;
581 writeln!(self.out, " {{")?;
582 for m in members.iter() {
583 // Sanity check that each IO member is a built-in or is assigned a
584 // location. Also see note about nesting in `write_ep_input_struct`.
585 debug_assert!(m.binding.is_some());
586
587 if is_subgroup_builtin_binding(&m.binding) {
588 continue;
589 }
590 write!(self.out, "{}", back::INDENT)?;
591 if let Some(ref binding) = m.binding {
592 self.write_modifier(binding)?;
593 }
594 self.write_type(module, m.ty)?;
595 write!(self.out, " {}", &m.name)?;
596 self.write_semantic(&m.binding, Some(shader_stage))?;
597 writeln!(self.out, ";")?;
598 }
599 if members.iter().any(|arg| {
600 matches!(
601 arg.binding,
602 Some(crate::Binding::BuiltIn(crate::BuiltIn::SubgroupId))
603 )
604 }) {
605 writeln!(
606 self.out,
607 "{}uint __local_invocation_index : SV_GroupIndex;",
608 back::INDENT
609 )?;
610 }
611 writeln!(self.out, "}};")?;
612 writeln!(self.out)?;
613
614 // See ordering notes on EntryPointInterface fields
615 match shader_stage.1 {
616 Io::Input => {
617 // bring back the original order
618 members.sort_by_key(|m| m.index);
619 }
620 Io::Output => {
621 // keep it sorted by binding
622 }
623 }
624
625 Ok(EntryPointBinding {
626 arg_name: self.namer.call(struct_name.to_lowercase().as_str()),
627 ty_name: struct_name,
628 members,
629 })
630 }
631
632 /// Flatten all entry point arguments into a single struct.
633 /// This is needed since we need to re-order them: first placing user locations,
634 /// then built-ins.
635 fn write_ep_input_struct(
636 &mut self,
637 module: &Module,
638 func: &crate::Function,
639 stage: ShaderStage,
640 entry_point_name: &str,
641 ) -> Result<EntryPointBinding, Error> {
642 let struct_name = format!("{stage:?}Input_{entry_point_name}");
643
644 let mut fake_members = Vec::new();
645 for arg in func.arguments.iter() {
646 // NOTE: We don't need to handle nesting structs. All members must
647 // be either built-ins or assigned a location. I.E. `binding` is
648 // `Some`. This is checked in `VaryingContext::validate`. See:
649 // https://gpuweb.github.io/gpuweb/wgsl/#input-output-locations
650 match module.types[arg.ty].inner {
651 TypeInner::Struct { ref members, .. } => {
652 for member in members.iter() {
653 let name = self.namer.call_or(&member.name, "member");
654 let index = fake_members.len() as u32;
655 fake_members.push(EpStructMember {
656 name,
657 ty: member.ty,
658 binding: member.binding.clone(),
659 index,
660 });
661 }
662 }
663 _ => {
664 let member_name = self.namer.call_or(&arg.name, "member");
665 let index = fake_members.len() as u32;
666 fake_members.push(EpStructMember {
667 name: member_name,
668 ty: arg.ty,
669 binding: arg.binding.clone(),
670 index,
671 });
672 }
673 }
674 }
675
676 self.write_interface_struct(module, (stage, Io::Input), struct_name, fake_members)
677 }
678
679 /// Flatten all entry point results into a single struct.
680 /// This is needed since we need to re-order them: first placing user locations,
681 /// then built-ins.
682 fn write_ep_output_struct(
683 &mut self,
684 module: &Module,
685 result: &crate::FunctionResult,
686 stage: ShaderStage,
687 entry_point_name: &str,
688 frag_ep: Option<&FragmentEntryPoint<'_>>,
689 ) -> Result<EntryPointBinding, Error> {
690 let struct_name = format!("{stage:?}Output_{entry_point_name}");
691
692 let empty = [];
693 let members = match module.types[result.ty].inner {
694 TypeInner::Struct { ref members, .. } => members,
695 ref other => {
696 log::error!("Unexpected {:?} output type without a binding", other);
697 &empty[..]
698 }
699 };
700
701 // Gather list of fragment input locations. We use this below to remove user-defined
702 // varyings from VS outputs that aren't in the FS inputs. This makes the VS interface match
703 // as long as the FS inputs are a subset of the VS outputs. This is only applied if the
704 // writer is supplied with information about the fragment entry point.
705 let fs_input_locs = if let (Some(frag_ep), ShaderStage::Vertex) = (frag_ep, stage) {
706 let mut fs_input_locs = Vec::new();
707 for arg in frag_ep.func.arguments.iter() {
708 let mut push_if_location = |binding: &Option<crate::Binding>| match *binding {
709 Some(crate::Binding::Location { location, .. }) => fs_input_locs.push(location),
710 Some(crate::Binding::BuiltIn(_)) | None => {}
711 };
712
713 // NOTE: We don't need to handle struct nesting. See note in
714 // `write_ep_input_struct`.
715 match frag_ep.module.types[arg.ty].inner {
716 TypeInner::Struct { ref members, .. } => {
717 for member in members.iter() {
718 push_if_location(&member.binding);
719 }
720 }
721 _ => push_if_location(&arg.binding),
722 }
723 }
724 fs_input_locs.sort();
725 Some(fs_input_locs)
726 } else {
727 None
728 };
729
730 let mut fake_members = Vec::new();
731 for (index, member) in members.iter().enumerate() {
732 if let Some(ref fs_input_locs) = fs_input_locs {
733 match member.binding {
734 Some(crate::Binding::Location { location, .. }) => {
735 if fs_input_locs.binary_search(&location).is_err() {
736 continue;
737 }
738 }
739 Some(crate::Binding::BuiltIn(_)) | None => {}
740 }
741 }
742
743 let member_name = self.namer.call_or(&member.name, "member");
744 fake_members.push(EpStructMember {
745 name: member_name,
746 ty: member.ty,
747 binding: member.binding.clone(),
748 index: index as u32,
749 });
750 }
751
752 self.write_interface_struct(module, (stage, Io::Output), struct_name, fake_members)
753 }
754
755 /// Writes special interface structures for an entry point. The special structures have
756 /// all the fields flattened into them and sorted by binding. They are needed to emulate
757 /// subgroup built-ins and to make the interfaces between VS outputs and FS inputs match.
758 fn write_ep_interface(
759 &mut self,
760 module: &Module,
761 func: &crate::Function,
762 stage: ShaderStage,
763 ep_name: &str,
764 frag_ep: Option<&FragmentEntryPoint<'_>>,
765 ) -> Result<EntryPointInterface, Error> {
766 Ok(EntryPointInterface {
767 input: if !func.arguments.is_empty()
768 && (stage == ShaderStage::Fragment
769 || func
770 .arguments
771 .iter()
772 .any(|arg| is_subgroup_builtin_binding(&arg.binding)))
773 {
774 Some(self.write_ep_input_struct(module, func, stage, ep_name)?)
775 } else {
776 None
777 },
778 output: match func.result {
779 Some(ref fr) if fr.binding.is_none() && stage == ShaderStage::Vertex => {
780 Some(self.write_ep_output_struct(module, fr, stage, ep_name, frag_ep)?)
781 }
782 _ => None,
783 },
784 })
785 }
786
787 fn write_ep_argument_initialization(
788 &mut self,
789 ep: &crate::EntryPoint,
790 ep_input: &EntryPointBinding,
791 fake_member: &EpStructMember,
792 ) -> BackendResult {
793 match fake_member.binding {
794 Some(crate::Binding::BuiltIn(crate::BuiltIn::SubgroupSize)) => {
795 write!(self.out, "WaveGetLaneCount()")?
796 }
797 Some(crate::Binding::BuiltIn(crate::BuiltIn::SubgroupInvocationId)) => {
798 write!(self.out, "WaveGetLaneIndex()")?
799 }
800 Some(crate::Binding::BuiltIn(crate::BuiltIn::NumSubgroups)) => write!(
801 self.out,
802 "({}u + WaveGetLaneCount() - 1u) / WaveGetLaneCount()",
803 ep.workgroup_size[0] * ep.workgroup_size[1] * ep.workgroup_size[2]
804 )?,
805 Some(crate::Binding::BuiltIn(crate::BuiltIn::SubgroupId)) => {
806 write!(
807 self.out,
808 "{}.__local_invocation_index / WaveGetLaneCount()",
809 ep_input.arg_name
810 )?;
811 }
812 _ => {
813 write!(self.out, "{}.{}", ep_input.arg_name, fake_member.name)?;
814 }
815 }
816 Ok(())
817 }
818
819 /// Write an entry point preface that initializes the arguments as specified in IR.
820 fn write_ep_arguments_initialization(
821 &mut self,
822 module: &Module,
823 func: &crate::Function,
824 ep_index: u16,
825 ) -> BackendResult {
826 let ep = &module.entry_points[ep_index as usize];
827 let ep_input = match self
828 .entry_point_io
829 .get_mut(&(ep_index as usize))
830 .unwrap()
831 .input
832 .take()
833 {
834 Some(ep_input) => ep_input,
835 None => return Ok(()),
836 };
837 let mut fake_iter = ep_input.members.iter();
838 for (arg_index, arg) in func.arguments.iter().enumerate() {
839 write!(self.out, "{}", back::INDENT)?;
840 self.write_type(module, arg.ty)?;
841 let arg_name = &self.names[&NameKey::EntryPointArgument(ep_index, arg_index as u32)];
842 write!(self.out, " {arg_name}")?;
843 match module.types[arg.ty].inner {
844 TypeInner::Array { base, size, .. } => {
845 self.write_array_size(module, base, size)?;
846 write!(self.out, " = ")?;
847 self.write_ep_argument_initialization(
848 ep,
849 &ep_input,
850 fake_iter.next().unwrap(),
851 )?;
852 writeln!(self.out, ";")?;
853 }
854 TypeInner::Struct { ref members, .. } => {
855 write!(self.out, " = {{ ")?;
856 for index in 0..members.len() {
857 if index != 0 {
858 write!(self.out, ", ")?;
859 }
860 self.write_ep_argument_initialization(
861 ep,
862 &ep_input,
863 fake_iter.next().unwrap(),
864 )?;
865 }
866 writeln!(self.out, " }};")?;
867 }
868 _ => {
869 write!(self.out, " = ")?;
870 self.write_ep_argument_initialization(
871 ep,
872 &ep_input,
873 fake_iter.next().unwrap(),
874 )?;
875 writeln!(self.out, ";")?;
876 }
877 }
878 }
879 assert!(fake_iter.next().is_none());
880 Ok(())
881 }
882
883 /// Helper method used to write global variables
884 /// # Notes
885 /// Always adds a newline
886 fn write_global(
887 &mut self,
888 module: &Module,
889 handle: Handle<crate::GlobalVariable>,
890 ) -> BackendResult {
891 let global = &module.global_variables[handle];
892 let inner = &module.types[global.ty].inner;
893
894 if let Some(ref binding) = global.binding {
895 if let Err(err) = self.options.resolve_resource_binding(binding) {
896 log::info!(
897 "Skipping global {:?} (name {:?}) for being inaccessible: {}",
898 handle,
899 global.name,
900 err,
901 );
902 return Ok(());
903 }
904 }
905
906 let handle_ty = match *inner {
907 TypeInner::BindingArray { ref base, .. } => &module.types[*base].inner,
908 _ => inner,
909 };
910
911 // Samplers are handled entirely differently, so defer entirely to that method.
912 let is_sampler = matches!(*handle_ty, TypeInner::Sampler { .. });
913
914 if is_sampler {
915 return self.write_global_sampler(module, handle, global);
916 }
917
918 // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-variable-register
919 let register_ty = match global.space {
920 crate::AddressSpace::Function => unreachable!("Function address space"),
921 crate::AddressSpace::Private => {
922 write!(self.out, "static ")?;
923 self.write_type(module, global.ty)?;
924 ""
925 }
926 crate::AddressSpace::WorkGroup => {
927 write!(self.out, "groupshared ")?;
928 self.write_type(module, global.ty)?;
929 ""
930 }
931 crate::AddressSpace::Uniform => {
932 // constant buffer declarations are expected to be inlined, e.g.
933 // `cbuffer foo: register(b0) { field1: type1; }`
934 write!(self.out, "cbuffer")?;
935 "b"
936 }
937 crate::AddressSpace::Storage { access } => {
938 let (prefix, register) = if access.contains(crate::StorageAccess::STORE) {
939 ("RW", "u")
940 } else {
941 ("", "t")
942 };
943 write!(self.out, "{prefix}ByteAddressBuffer")?;
944 register
945 }
946 crate::AddressSpace::Handle => {
947 let register = match *handle_ty {
948 // all storage textures are UAV, unconditionally
949 TypeInner::Image {
950 class: crate::ImageClass::Storage { .. },
951 ..
952 } => "u",
953 _ => "t",
954 };
955 self.write_type(module, global.ty)?;
956 register
957 }
958 crate::AddressSpace::PushConstant => {
959 // The type of the push constants will be wrapped in `ConstantBuffer`
960 write!(self.out, "ConstantBuffer<")?;
961 "b"
962 }
963 };
964
965 // If the global is a push constant write the type now because it will be a
966 // generic argument to `ConstantBuffer`
967 if global.space == crate::AddressSpace::PushConstant {
968 self.write_global_type(module, global.ty)?;
969
970 // need to write the array size if the type was emitted with `write_type`
971 if let TypeInner::Array { base, size, .. } = module.types[global.ty].inner {
972 self.write_array_size(module, base, size)?;
973 }
974
975 // Close the angled brackets for the generic argument
976 write!(self.out, ">")?;
977 }
978
979 let name = &self.names[&NameKey::GlobalVariable(handle)];
980 write!(self.out, " {name}")?;
981
982 // Push constants need to be assigned a binding explicitly by the consumer
983 // since naga has no way to know the binding from the shader alone
984 if global.space == crate::AddressSpace::PushConstant {
985 match module.types[global.ty].inner {
986 TypeInner::Struct { .. } => {}
987 _ => {
988 return Err(Error::Unimplemented(format!(
989 "push-constant '{name}' has non-struct type; tracked by: https://github.com/gfx-rs/wgpu/issues/5683"
990 )));
991 }
992 }
993
994 let target = self
995 .options
996 .push_constants_target
997 .as_ref()
998 .expect("No bind target was defined for the push constants block");
999 write!(self.out, ": register(b{}", target.register)?;
1000 if target.space != 0 {
1001 write!(self.out, ", space{}", target.space)?;
1002 }
1003 write!(self.out, ")")?;
1004 }
1005
1006 if let Some(ref binding) = global.binding {
1007 // this was already resolved earlier when we started evaluating an entry point.
1008 let bt = self.options.resolve_resource_binding(binding).unwrap();
1009
1010 // need to write the binding array size if the type was emitted with `write_type`
1011 if let TypeInner::BindingArray { base, size, .. } = module.types[global.ty].inner {
1012 if let Some(overridden_size) = bt.binding_array_size {
1013 write!(self.out, "[{overridden_size}]")?;
1014 } else {
1015 self.write_array_size(module, base, size)?;
1016 }
1017 }
1018
1019 write!(self.out, " : register({}{}", register_ty, bt.register)?;
1020 if bt.space != 0 {
1021 write!(self.out, ", space{}", bt.space)?;
1022 }
1023 write!(self.out, ")")?;
1024 } else {
1025 // need to write the array size if the type was emitted with `write_type`
1026 if let TypeInner::Array { base, size, .. } = module.types[global.ty].inner {
1027 self.write_array_size(module, base, size)?;
1028 }
1029 if global.space == crate::AddressSpace::Private {
1030 write!(self.out, " = ")?;
1031 if let Some(init) = global.init {
1032 self.write_const_expression(module, init, &module.global_expressions)?;
1033 } else {
1034 self.write_default_init(module, global.ty)?;
1035 }
1036 }
1037 }
1038
1039 if global.space == crate::AddressSpace::Uniform {
1040 write!(self.out, " {{ ")?;
1041
1042 self.write_global_type(module, global.ty)?;
1043
1044 write!(
1045 self.out,
1046 " {}",
1047 &self.names[&NameKey::GlobalVariable(handle)]
1048 )?;
1049
1050 // need to write the array size if the type was emitted with `write_type`
1051 if let TypeInner::Array { base, size, .. } = module.types[global.ty].inner {
1052 self.write_array_size(module, base, size)?;
1053 }
1054
1055 writeln!(self.out, "; }}")?;
1056 } else {
1057 writeln!(self.out, ";")?;
1058 }
1059
1060 Ok(())
1061 }
1062
1063 fn write_global_sampler(
1064 &mut self,
1065 module: &Module,
1066 handle: Handle<crate::GlobalVariable>,
1067 global: &crate::GlobalVariable,
1068 ) -> BackendResult {
1069 let binding = *global.binding.as_ref().unwrap();
1070
1071 let key = super::SamplerIndexBufferKey {
1072 group: binding.group,
1073 };
1074 self.write_wrapped_sampler_buffer(key)?;
1075
1076 // This was already validated, so we can confidently unwrap it.
1077 let bt = self.options.resolve_resource_binding(&binding).unwrap();
1078
1079 match module.types[global.ty].inner {
1080 TypeInner::Sampler { comparison } => {
1081 // If we are generating a static access, we create a variable for the sampler.
1082 //
1083 // This prevents the DXIL from containing multiple lookups for the sampler, which
1084 // the backend compiler will then have to eliminate. AMD does seem to be able to
1085 // eliminate these, but better safe than sorry.
1086
1087 write!(self.out, "static const ")?;
1088 self.write_type(module, global.ty)?;
1089
1090 let heap_var = if comparison {
1091 COMPARISON_SAMPLER_HEAP_VAR
1092 } else {
1093 SAMPLER_HEAP_VAR
1094 };
1095
1096 let index_buffer_name = &self.wrapped.sampler_index_buffers[&key];
1097 let name = &self.names[&NameKey::GlobalVariable(handle)];
1098 writeln!(
1099 self.out,
1100 " {name} = {heap_var}[{index_buffer_name}[{register}]];",
1101 register = bt.register
1102 )?;
1103 }
1104 TypeInner::BindingArray { .. } => {
1105 // If we are generating a binding array, we cannot directly access the sampler as the index
1106 // into the sampler index buffer is unknown at compile time. Instead we generate a constant
1107 // that represents the "base" index into the sampler index buffer. This constant is added
1108 // to the user provided index to get the final index into the sampler index buffer.
1109
1110 let name = &self.names[&NameKey::GlobalVariable(handle)];
1111 writeln!(
1112 self.out,
1113 "static const uint {name} = {register};",
1114 register = bt.register
1115 )?;
1116 }
1117 _ => unreachable!(),
1118 };
1119
1120 Ok(())
1121 }
1122
1123 /// Helper method used to write global constants
1124 ///
1125 /// # Notes
1126 /// Ends in a newline
1127 fn write_global_constant(
1128 &mut self,
1129 module: &Module,
1130 handle: Handle<crate::Constant>,
1131 ) -> BackendResult {
1132 write!(self.out, "static const ")?;
1133 let constant = &module.constants[handle];
1134 self.write_type(module, constant.ty)?;
1135 let name = &self.names[&NameKey::Constant(handle)];
1136 write!(self.out, " {name}")?;
1137 // Write size for array type
1138 if let TypeInner::Array { base, size, .. } = module.types[constant.ty].inner {
1139 self.write_array_size(module, base, size)?;
1140 }
1141 write!(self.out, " = ")?;
1142 self.write_const_expression(module, constant.init, &module.global_expressions)?;
1143 writeln!(self.out, ";")?;
1144 Ok(())
1145 }
1146
1147 pub(super) fn write_array_size(
1148 &mut self,
1149 module: &Module,
1150 base: Handle<crate::Type>,
1151 size: crate::ArraySize,
1152 ) -> BackendResult {
1153 write!(self.out, "[")?;
1154
1155 match size.resolve(module.to_ctx())? {
1156 proc::IndexableLength::Known(size) => {
1157 write!(self.out, "{size}")?;
1158 }
1159 proc::IndexableLength::Dynamic => unreachable!(),
1160 }
1161
1162 write!(self.out, "]")?;
1163
1164 if let TypeInner::Array {
1165 base: next_base,
1166 size: next_size,
1167 ..
1168 } = module.types[base].inner
1169 {
1170 self.write_array_size(module, next_base, next_size)?;
1171 }
1172
1173 Ok(())
1174 }
1175
1176 /// Helper method used to write structs
1177 ///
1178 /// # Notes
1179 /// Ends in a newline
1180 fn write_struct(
1181 &mut self,
1182 module: &Module,
1183 handle: Handle<crate::Type>,
1184 members: &[crate::StructMember],
1185 span: u32,
1186 shader_stage: Option<(ShaderStage, Io)>,
1187 ) -> BackendResult {
1188 // Write struct name
1189 let struct_name = &self.names[&NameKey::Type(handle)];
1190 writeln!(self.out, "struct {struct_name} {{")?;
1191
1192 let mut last_offset = 0;
1193 for (index, member) in members.iter().enumerate() {
1194 if member.binding.is_none() && member.offset > last_offset {
1195 // using int as padding should work as long as the backend
1196 // doesn't support a type that's less than 4 bytes in size
1197 // (Error::UnsupportedScalar catches this)
1198 let padding = (member.offset - last_offset) / 4;
1199 for i in 0..padding {
1200 writeln!(self.out, "{}int _pad{}_{};", back::INDENT, index, i)?;
1201 }
1202 }
1203 let ty_inner = &module.types[member.ty].inner;
1204 last_offset = member.offset + ty_inner.size_hlsl(module.to_ctx())?;
1205
1206 // The indentation is only for readability
1207 write!(self.out, "{}", back::INDENT)?;
1208
1209 match module.types[member.ty].inner {
1210 TypeInner::Array { base, size, .. } => {
1211 // HLSL arrays are written as `type name[size]`
1212
1213 self.write_global_type(module, member.ty)?;
1214
1215 // Write `name`
1216 write!(
1217 self.out,
1218 " {}",
1219 &self.names[&NameKey::StructMember(handle, index as u32)]
1220 )?;
1221 // Write [size]
1222 self.write_array_size(module, base, size)?;
1223 }
1224 // We treat matrices of the form `matCx2` as a sequence of C `vec2`s.
1225 // See the module-level block comment in mod.rs for details.
1226 TypeInner::Matrix {
1227 rows,
1228 columns,
1229 scalar,
1230 } if member.binding.is_none() && rows == crate::VectorSize::Bi => {
1231 let vec_ty = TypeInner::Vector { size: rows, scalar };
1232 let field_name_key = NameKey::StructMember(handle, index as u32);
1233
1234 for i in 0..columns as u8 {
1235 if i != 0 {
1236 write!(self.out, "; ")?;
1237 }
1238 self.write_value_type(module, &vec_ty)?;
1239 write!(self.out, " {}_{}", &self.names[&field_name_key], i)?;
1240 }
1241 }
1242 _ => {
1243 // Write modifier before type
1244 if let Some(ref binding) = member.binding {
1245 self.write_modifier(binding)?;
1246 }
1247
1248 // Even though Naga IR matrices are column-major, we must describe
1249 // matrices passed from the CPU as being in row-major order.
1250 // See the module-level block comment in mod.rs for details.
1251 if let TypeInner::Matrix { .. } = module.types[member.ty].inner {
1252 write!(self.out, "row_major ")?;
1253 }
1254
1255 // Write the member type and name
1256 self.write_type(module, member.ty)?;
1257 write!(
1258 self.out,
1259 " {}",
1260 &self.names[&NameKey::StructMember(handle, index as u32)]
1261 )?;
1262 }
1263 }
1264
1265 self.write_semantic(&member.binding, shader_stage)?;
1266 writeln!(self.out, ";")?;
1267 }
1268
1269 // add padding at the end since sizes of types don't get rounded up to their alignment in HLSL
1270 if members.last().unwrap().binding.is_none() && span > last_offset {
1271 let padding = (span - last_offset) / 4;
1272 for i in 0..padding {
1273 writeln!(self.out, "{}int _end_pad_{};", back::INDENT, i)?;
1274 }
1275 }
1276
1277 writeln!(self.out, "}};")?;
1278 Ok(())
1279 }
1280
1281 /// Helper method used to write global/structs non image/sampler types
1282 ///
1283 /// # Notes
1284 /// Adds no trailing or leading whitespace
1285 pub(super) fn write_global_type(
1286 &mut self,
1287 module: &Module,
1288 ty: Handle<crate::Type>,
1289 ) -> BackendResult {
1290 let matrix_data = get_inner_matrix_data(module, ty);
1291
1292 // We treat matrices of the form `matCx2` as a sequence of C `vec2`s.
1293 // See the module-level block comment in mod.rs for details.
1294 if let Some(MatrixType {
1295 columns,
1296 rows: crate::VectorSize::Bi,
1297 width: 4,
1298 }) = matrix_data
1299 {
1300 write!(self.out, "__mat{}x2", columns as u8)?;
1301 } else {
1302 // Even though Naga IR matrices are column-major, we must describe
1303 // matrices passed from the CPU as being in row-major order.
1304 // See the module-level block comment in mod.rs for details.
1305 if matrix_data.is_some() {
1306 write!(self.out, "row_major ")?;
1307 }
1308
1309 self.write_type(module, ty)?;
1310 }
1311
1312 Ok(())
1313 }
1314
1315 /// Helper method used to write non image/sampler types
1316 ///
1317 /// # Notes
1318 /// Adds no trailing or leading whitespace
1319 pub(super) fn write_type(&mut self, module: &Module, ty: Handle<crate::Type>) -> BackendResult {
1320 let inner = &module.types[ty].inner;
1321 match *inner {
1322 TypeInner::Struct { .. } => write!(self.out, "{}", self.names[&NameKey::Type(ty)])?,
1323 // hlsl array has the size separated from the base type
1324 TypeInner::Array { base, .. } | TypeInner::BindingArray { base, .. } => {
1325 self.write_type(module, base)?
1326 }
1327 ref other => self.write_value_type(module, other)?,
1328 }
1329
1330 Ok(())
1331 }
1332
1333 /// Helper method used to write value types
1334 ///
1335 /// # Notes
1336 /// Adds no trailing or leading whitespace
1337 pub(super) fn write_value_type(&mut self, module: &Module, inner: &TypeInner) -> BackendResult {
1338 match *inner {
1339 TypeInner::Scalar(scalar) | TypeInner::Atomic(scalar) => {
1340 write!(self.out, "{}", scalar.to_hlsl_str()?)?;
1341 }
1342 TypeInner::Vector { size, scalar } => {
1343 write!(
1344 self.out,
1345 "{}{}",
1346 scalar.to_hlsl_str()?,
1347 common::vector_size_str(size)
1348 )?;
1349 }
1350 TypeInner::Matrix {
1351 columns,
1352 rows,
1353 scalar,
1354 } => {
1355 // The IR supports only float matrix
1356 // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-matrix
1357
1358 // Because of the implicit transpose all matrices have in HLSL, we need to transpose the size as well.
1359 write!(
1360 self.out,
1361 "{}{}x{}",
1362 scalar.to_hlsl_str()?,
1363 common::vector_size_str(columns),
1364 common::vector_size_str(rows),
1365 )?;
1366 }
1367 TypeInner::Image {
1368 dim,
1369 arrayed,
1370 class,
1371 } => {
1372 self.write_image_type(dim, arrayed, class)?;
1373 }
1374 TypeInner::Sampler { comparison } => {
1375 let sampler = if comparison {
1376 "SamplerComparisonState"
1377 } else {
1378 "SamplerState"
1379 };
1380 write!(self.out, "{sampler}")?;
1381 }
1382 // HLSL arrays are written as `type name[size]`
1383 // Current code is written arrays only as `[size]`
1384 // Base `type` and `name` should be written outside
1385 TypeInner::Array { base, size, .. } | TypeInner::BindingArray { base, size } => {
1386 self.write_array_size(module, base, size)?;
1387 }
1388 TypeInner::AccelerationStructure { .. } => {
1389 write!(self.out, "RaytracingAccelerationStructure")?;
1390 }
1391 TypeInner::RayQuery { .. } => {
1392 // these are constant flags, there are dynamic flags also but constant flags are not supported by naga
1393 write!(self.out, "RayQuery<RAY_FLAG_NONE>")?;
1394 }
1395 _ => return Err(Error::Unimplemented(format!("write_value_type {inner:?}"))),
1396 }
1397
1398 Ok(())
1399 }
1400
1401 /// Helper method used to write functions
1402 /// # Notes
1403 /// Ends in a newline
1404 fn write_function(
1405 &mut self,
1406 module: &Module,
1407 name: &str,
1408 func: &crate::Function,
1409 func_ctx: &back::FunctionCtx<'_>,
1410 info: &valid::FunctionInfo,
1411 ) -> BackendResult {
1412 // Function Declaration Syntax - https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-function-syntax
1413
1414 self.update_expressions_to_bake(module, func, info);
1415
1416 if let Some(ref result) = func.result {
1417 // Write typedef if return type is an array
1418 let array_return_type = match module.types[result.ty].inner {
1419 TypeInner::Array { base, size, .. } => {
1420 let array_return_type = self.namer.call(&format!("ret_{name}"));
1421 write!(self.out, "typedef ")?;
1422 self.write_type(module, result.ty)?;
1423 write!(self.out, " {}", array_return_type)?;
1424 self.write_array_size(module, base, size)?;
1425 writeln!(self.out, ";")?;
1426 Some(array_return_type)
1427 }
1428 _ => None,
1429 };
1430
1431 // Write modifier
1432 if let Some(
1433 ref binding @ crate::Binding::BuiltIn(crate::BuiltIn::Position { invariant: true }),
1434 ) = result.binding
1435 {
1436 self.write_modifier(binding)?;
1437 }
1438
1439 // Write return type
1440 match func_ctx.ty {
1441 back::FunctionType::Function(_) => {
1442 if let Some(array_return_type) = array_return_type {
1443 write!(self.out, "{array_return_type}")?;
1444 } else {
1445 self.write_type(module, result.ty)?;
1446 }
1447 }
1448 back::FunctionType::EntryPoint(index) => {
1449 if let Some(ref ep_output) =
1450 self.entry_point_io.get(&(index as usize)).unwrap().output
1451 {
1452 write!(self.out, "{}", ep_output.ty_name)?;
1453 } else {
1454 self.write_type(module, result.ty)?;
1455 }
1456 }
1457 }
1458 } else {
1459 write!(self.out, "void")?;
1460 }
1461
1462 // Write function name
1463 write!(self.out, " {name}(")?;
1464
1465 let need_workgroup_variables_initialization =
1466 self.need_workgroup_variables_initialization(func_ctx, module);
1467
1468 // Write function arguments for non entry point functions
1469 match func_ctx.ty {
1470 back::FunctionType::Function(handle) => {
1471 for (index, arg) in func.arguments.iter().enumerate() {
1472 if index != 0 {
1473 write!(self.out, ", ")?;
1474 }
1475 // Write argument type
1476 let arg_ty = match module.types[arg.ty].inner {
1477 // pointers in function arguments are expected and resolve to `inout`
1478 TypeInner::Pointer { base, .. } => {
1479 //TODO: can we narrow this down to just `in` when possible?
1480 write!(self.out, "inout ")?;
1481 base
1482 }
1483 _ => arg.ty,
1484 };
1485 self.write_type(module, arg_ty)?;
1486
1487 let argument_name =
1488 &self.names[&NameKey::FunctionArgument(handle, index as u32)];
1489
1490 // Write argument name. Space is important.
1491 write!(self.out, " {argument_name}")?;
1492 if let TypeInner::Array { base, size, .. } = module.types[arg_ty].inner {
1493 self.write_array_size(module, base, size)?;
1494 }
1495 }
1496 }
1497 back::FunctionType::EntryPoint(ep_index) => {
1498 if let Some(ref ep_input) =
1499 self.entry_point_io.get(&(ep_index as usize)).unwrap().input
1500 {
1501 write!(self.out, "{} {}", ep_input.ty_name, ep_input.arg_name)?;
1502 } else {
1503 let stage = module.entry_points[ep_index as usize].stage;
1504 for (index, arg) in func.arguments.iter().enumerate() {
1505 if index != 0 {
1506 write!(self.out, ", ")?;
1507 }
1508 self.write_type(module, arg.ty)?;
1509
1510 let argument_name =
1511 &self.names[&NameKey::EntryPointArgument(ep_index, index as u32)];
1512
1513 write!(self.out, " {argument_name}")?;
1514 if let TypeInner::Array { base, size, .. } = module.types[arg.ty].inner {
1515 self.write_array_size(module, base, size)?;
1516 }
1517
1518 self.write_semantic(&arg.binding, Some((stage, Io::Input)))?;
1519 }
1520 }
1521 if need_workgroup_variables_initialization {
1522 if self
1523 .entry_point_io
1524 .get(&(ep_index as usize))
1525 .unwrap()
1526 .input
1527 .is_some()
1528 || !func.arguments.is_empty()
1529 {
1530 write!(self.out, ", ")?;
1531 }
1532 write!(self.out, "uint3 __local_invocation_id : SV_GroupThreadID")?;
1533 }
1534 }
1535 }
1536 // Ends of arguments
1537 write!(self.out, ")")?;
1538
1539 // Write semantic if it present
1540 if let back::FunctionType::EntryPoint(index) = func_ctx.ty {
1541 let stage = module.entry_points[index as usize].stage;
1542 if let Some(crate::FunctionResult { ref binding, .. }) = func.result {
1543 self.write_semantic(binding, Some((stage, Io::Output)))?;
1544 }
1545 }
1546
1547 // Function body start
1548 writeln!(self.out)?;
1549 writeln!(self.out, "{{")?;
1550
1551 if need_workgroup_variables_initialization {
1552 self.write_workgroup_variables_initialization(func_ctx, module)?;
1553 }
1554
1555 if let back::FunctionType::EntryPoint(index) = func_ctx.ty {
1556 self.write_ep_arguments_initialization(module, func, index)?;
1557 }
1558
1559 // Write function local variables
1560 for (handle, local) in func.local_variables.iter() {
1561 // Write indentation (only for readability)
1562 write!(self.out, "{}", back::INDENT)?;
1563
1564 // Write the local name
1565 // The leading space is important
1566 self.write_type(module, local.ty)?;
1567 write!(self.out, " {}", self.names[&func_ctx.name_key(handle)])?;
1568 // Write size for array type
1569 if let TypeInner::Array { base, size, .. } = module.types[local.ty].inner {
1570 self.write_array_size(module, base, size)?;
1571 }
1572
1573 match module.types[local.ty].inner {
1574 // from https://microsoft.github.io/DirectX-Specs/d3d/Raytracing.html#tracerayinline-example-1 it seems that ray queries shouldn't be zeroed
1575 TypeInner::RayQuery { .. } => {}
1576 _ => {
1577 write!(self.out, " = ")?;
1578 // Write the local initializer if needed
1579 if let Some(init) = local.init {
1580 self.write_expr(module, init, func_ctx)?;
1581 } else {
1582 // Zero initialize local variables
1583 self.write_default_init(module, local.ty)?;
1584 }
1585 }
1586 }
1587 // Finish the local with `;` and add a newline (only for readability)
1588 writeln!(self.out, ";")?
1589 }
1590
1591 if !func.local_variables.is_empty() {
1592 writeln!(self.out)?;
1593 }
1594
1595 // Write the function body (statement list)
1596 for sta in func.body.iter() {
1597 // The indentation should always be 1 when writing the function body
1598 self.write_stmt(module, sta, func_ctx, back::Level(1))?;
1599 }
1600
1601 writeln!(self.out, "}}")?;
1602
1603 self.named_expressions.clear();
1604
1605 Ok(())
1606 }
1607
1608 fn need_workgroup_variables_initialization(
1609 &mut self,
1610 func_ctx: &back::FunctionCtx,
1611 module: &Module,
1612 ) -> bool {
1613 self.options.zero_initialize_workgroup_memory
1614 && func_ctx.ty.is_compute_entry_point(module)
1615 && module.global_variables.iter().any(|(handle, var)| {
1616 !func_ctx.info[handle].is_empty() && var.space == crate::AddressSpace::WorkGroup
1617 })
1618 }
1619
1620 fn write_workgroup_variables_initialization(
1621 &mut self,
1622 func_ctx: &back::FunctionCtx,
1623 module: &Module,
1624 ) -> BackendResult {
1625 let level = back::Level(1);
1626
1627 writeln!(
1628 self.out,
1629 "{level}if (all(__local_invocation_id == uint3(0u, 0u, 0u))) {{"
1630 )?;
1631
1632 let vars = module.global_variables.iter().filter(|&(handle, var)| {
1633 !func_ctx.info[handle].is_empty() && var.space == crate::AddressSpace::WorkGroup
1634 });
1635
1636 for (handle, var) in vars {
1637 let name = &self.names[&NameKey::GlobalVariable(handle)];
1638 write!(self.out, "{}{} = ", level.next(), name)?;
1639 self.write_default_init(module, var.ty)?;
1640 writeln!(self.out, ";")?;
1641 }
1642
1643 writeln!(self.out, "{level}}}")?;
1644 self.write_barrier(crate::Barrier::WORK_GROUP, level)
1645 }
1646
1647 /// Helper method used to write switches
1648 fn write_switch(
1649 &mut self,
1650 module: &Module,
1651 func_ctx: &back::FunctionCtx<'_>,
1652 level: back::Level,
1653 selector: Handle<crate::Expression>,
1654 cases: &[crate::SwitchCase],
1655 ) -> BackendResult {
1656 // Write all cases
1657 let indent_level_1 = level.next();
1658 let indent_level_2 = indent_level_1.next();
1659
1660 // See docs of `back::continue_forward` module.
1661 if let Some(variable) = self.continue_ctx.enter_switch(&mut self.namer) {
1662 writeln!(self.out, "{level}bool {variable} = false;",)?;
1663 };
1664
1665 // Check if there is only one body, by seeing if all except the last case are fall through
1666 // with empty bodies. FXC doesn't handle these switches correctly, so
1667 // we generate a `do {} while(false);` loop instead. There must be a default case, so there
1668 // is no need to check if one of the cases would have matched.
1669 let one_body = cases
1670 .iter()
1671 .rev()
1672 .skip(1)
1673 .all(|case| case.fall_through && case.body.is_empty());
1674 if one_body {
1675 // Start the do-while
1676 writeln!(self.out, "{level}do {{")?;
1677 // Note: Expressions have no side-effects so we don't need to emit selector expression.
1678
1679 // Body
1680 if let Some(case) = cases.last() {
1681 for sta in case.body.iter() {
1682 self.write_stmt(module, sta, func_ctx, indent_level_1)?;
1683 }
1684 }
1685 // End do-while
1686 writeln!(self.out, "{level}}} while(false);")?;
1687 } else {
1688 // Start the switch
1689 write!(self.out, "{level}")?;
1690 write!(self.out, "switch(")?;
1691 self.write_expr(module, selector, func_ctx)?;
1692 writeln!(self.out, ") {{")?;
1693
1694 for (i, case) in cases.iter().enumerate() {
1695 match case.value {
1696 crate::SwitchValue::I32(value) => {
1697 write!(self.out, "{indent_level_1}case {value}:")?
1698 }
1699 crate::SwitchValue::U32(value) => {
1700 write!(self.out, "{indent_level_1}case {value}u:")?
1701 }
1702 crate::SwitchValue::Default => write!(self.out, "{indent_level_1}default:")?,
1703 }
1704
1705 // The new block is not only stylistic, it plays a role here:
1706 // We might end up having to write the same case body
1707 // multiple times due to FXC not supporting fallthrough.
1708 // Therefore, some `Expression`s written by `Statement::Emit`
1709 // will end up having the same name (`_expr<handle_index>`).
1710 // So we need to put each case in its own scope.
1711 let write_block_braces = !(case.fall_through && case.body.is_empty());
1712 if write_block_braces {
1713 writeln!(self.out, " {{")?;
1714 } else {
1715 writeln!(self.out)?;
1716 }
1717
1718 // Although FXC does support a series of case clauses before
1719 // a block[^yes], it does not support fallthrough from a
1720 // non-empty case block to the next[^no]. If this case has a
1721 // non-empty body with a fallthrough, emulate that by
1722 // duplicating the bodies of all the cases it would fall
1723 // into as extensions of this case's own body. This makes
1724 // the HLSL output potentially quadratic in the size of the
1725 // Naga IR.
1726 //
1727 // [^yes]: ```hlsl
1728 // case 1:
1729 // case 2: do_stuff()
1730 // ```
1731 // [^no]: ```hlsl
1732 // case 1: do_this();
1733 // case 2: do_that();
1734 // ```
1735 if case.fall_through && !case.body.is_empty() {
1736 let curr_len = i + 1;
1737 let end_case_idx = curr_len
1738 + cases
1739 .iter()
1740 .skip(curr_len)
1741 .position(|case| !case.fall_through)
1742 .unwrap();
1743 let indent_level_3 = indent_level_2.next();
1744 for case in &cases[i..=end_case_idx] {
1745 writeln!(self.out, "{indent_level_2}{{")?;
1746 let prev_len = self.named_expressions.len();
1747 for sta in case.body.iter() {
1748 self.write_stmt(module, sta, func_ctx, indent_level_3)?;
1749 }
1750 // Clear all named expressions that were previously inserted by the statements in the block
1751 self.named_expressions.truncate(prev_len);
1752 writeln!(self.out, "{indent_level_2}}}")?;
1753 }
1754
1755 let last_case = &cases[end_case_idx];
1756 if last_case.body.last().is_none_or(|s| !s.is_terminator()) {
1757 writeln!(self.out, "{indent_level_2}break;")?;
1758 }
1759 } else {
1760 for sta in case.body.iter() {
1761 self.write_stmt(module, sta, func_ctx, indent_level_2)?;
1762 }
1763 if !case.fall_through && case.body.last().is_none_or(|s| !s.is_terminator()) {
1764 writeln!(self.out, "{indent_level_2}break;")?;
1765 }
1766 }
1767
1768 if write_block_braces {
1769 writeln!(self.out, "{indent_level_1}}}")?;
1770 }
1771 }
1772
1773 writeln!(self.out, "{level}}}")?;
1774 }
1775
1776 // Handle any forwarded continue statements.
1777 use back::continue_forward::ExitControlFlow;
1778 let op = match self.continue_ctx.exit_switch() {
1779 ExitControlFlow::None => None,
1780 ExitControlFlow::Continue { variable } => Some(("continue", variable)),
1781 ExitControlFlow::Break { variable } => Some(("break", variable)),
1782 };
1783 if let Some((control_flow, variable)) = op {
1784 writeln!(self.out, "{level}if ({variable}) {{")?;
1785 writeln!(self.out, "{indent_level_1}{control_flow};")?;
1786 writeln!(self.out, "{level}}}")?;
1787 }
1788
1789 Ok(())
1790 }
1791
1792 /// Helper method used to write statements
1793 ///
1794 /// # Notes
1795 /// Always adds a newline
1796 fn write_stmt(
1797 &mut self,
1798 module: &Module,
1799 stmt: &crate::Statement,
1800 func_ctx: &back::FunctionCtx<'_>,
1801 level: back::Level,
1802 ) -> BackendResult {
1803 use crate::Statement;
1804
1805 match *stmt {
1806 Statement::Emit(ref range) => {
1807 for handle in range.clone() {
1808 let ptr_class = func_ctx.resolve_type(handle, &module.types).pointer_space();
1809 let expr_name = if ptr_class.is_some() {
1810 // HLSL can't save a pointer-valued expression in a variable,
1811 // but we shouldn't ever need to: they should never be named expressions,
1812 // and none of the expression types flagged by bake_ref_count can be pointer-valued.
1813 None
1814 } else if let Some(name) = func_ctx.named_expressions.get(&handle) {
1815 // Front end provides names for all variables at the start of writing.
1816 // But we write them to step by step. We need to recache them
1817 // Otherwise, we could accidentally write variable name instead of full expression.
1818 // Also, we use sanitized names! It defense backend from generating variable with name from reserved keywords.
1819 Some(self.namer.call(name))
1820 } else if self.need_bake_expressions.contains(&handle) {
1821 Some(Baked(handle).to_string())
1822 } else {
1823 None
1824 };
1825
1826 if let Some(name) = expr_name {
1827 write!(self.out, "{level}")?;
1828 self.write_named_expr(module, handle, name, handle, func_ctx)?;
1829 }
1830 }
1831 }
1832 // TODO: copy-paste from glsl-out
1833 Statement::Block(ref block) => {
1834 write!(self.out, "{level}")?;
1835 writeln!(self.out, "{{")?;
1836 for sta in block.iter() {
1837 // Increase the indentation to help with readability
1838 self.write_stmt(module, sta, func_ctx, level.next())?
1839 }
1840 writeln!(self.out, "{level}}}")?
1841 }
1842 // TODO: copy-paste from glsl-out
1843 Statement::If {
1844 condition,
1845 ref accept,
1846 ref reject,
1847 } => {
1848 write!(self.out, "{level}")?;
1849 write!(self.out, "if (")?;
1850 self.write_expr(module, condition, func_ctx)?;
1851 writeln!(self.out, ") {{")?;
1852
1853 let l2 = level.next();
1854 for sta in accept {
1855 // Increase indentation to help with readability
1856 self.write_stmt(module, sta, func_ctx, l2)?;
1857 }
1858
1859 // If there are no statements in the reject block we skip writing it
1860 // This is only for readability
1861 if !reject.is_empty() {
1862 writeln!(self.out, "{level}}} else {{")?;
1863
1864 for sta in reject {
1865 // Increase indentation to help with readability
1866 self.write_stmt(module, sta, func_ctx, l2)?;
1867 }
1868 }
1869
1870 writeln!(self.out, "{level}}}")?
1871 }
1872 // TODO: copy-paste from glsl-out
1873 Statement::Kill => writeln!(self.out, "{level}discard;")?,
1874 Statement::Return { value: None } => {
1875 writeln!(self.out, "{level}return;")?;
1876 }
1877 Statement::Return { value: Some(expr) } => {
1878 let base_ty_res = &func_ctx.info[expr].ty;
1879 let mut resolved = base_ty_res.inner_with(&module.types);
1880 if let TypeInner::Pointer { base, space: _ } = *resolved {
1881 resolved = &module.types[base].inner;
1882 }
1883
1884 if let TypeInner::Struct { .. } = *resolved {
1885 // We can safely unwrap here, since we now we working with struct
1886 let ty = base_ty_res.handle().unwrap();
1887 let struct_name = &self.names[&NameKey::Type(ty)];
1888 let variable_name = self.namer.call(&struct_name.to_lowercase());
1889 write!(self.out, "{level}const {struct_name} {variable_name} = ",)?;
1890 self.write_expr(module, expr, func_ctx)?;
1891 writeln!(self.out, ";")?;
1892
1893 // for entry point returns, we may need to reshuffle the outputs into a different struct
1894 let ep_output = match func_ctx.ty {
1895 back::FunctionType::Function(_) => None,
1896 back::FunctionType::EntryPoint(index) => self
1897 .entry_point_io
1898 .get(&(index as usize))
1899 .unwrap()
1900 .output
1901 .as_ref(),
1902 };
1903 let final_name = match ep_output {
1904 Some(ep_output) => {
1905 let final_name = self.namer.call(&variable_name);
1906 write!(
1907 self.out,
1908 "{}const {} {} = {{ ",
1909 level, ep_output.ty_name, final_name,
1910 )?;
1911 for (index, m) in ep_output.members.iter().enumerate() {
1912 if index != 0 {
1913 write!(self.out, ", ")?;
1914 }
1915 let member_name = &self.names[&NameKey::StructMember(ty, m.index)];
1916 write!(self.out, "{variable_name}.{member_name}")?;
1917 }
1918 writeln!(self.out, " }};")?;
1919 final_name
1920 }
1921 None => variable_name,
1922 };
1923 writeln!(self.out, "{level}return {final_name};")?;
1924 } else {
1925 write!(self.out, "{level}return ")?;
1926 self.write_expr(module, expr, func_ctx)?;
1927 writeln!(self.out, ";")?
1928 }
1929 }
1930 Statement::Store { pointer, value } => {
1931 let ty_inner = func_ctx.resolve_type(pointer, &module.types);
1932 if let Some(crate::AddressSpace::Storage { .. }) = ty_inner.pointer_space() {
1933 let var_handle = self.fill_access_chain(module, pointer, func_ctx)?;
1934 self.write_storage_store(
1935 module,
1936 var_handle,
1937 StoreValue::Expression(value),
1938 func_ctx,
1939 level,
1940 )?;
1941 } else {
1942 // We treat matrices of the form `matCx2` as a sequence of C `vec2`s.
1943 // See the module-level block comment in mod.rs for details.
1944 //
1945 // We handle matrix Stores here directly (including sub accesses for Vectors and Scalars).
1946 // Loads are handled by `Expression::AccessIndex` (since sub accesses work fine for Loads).
1947 struct MatrixAccess {
1948 base: Handle<crate::Expression>,
1949 index: u32,
1950 }
1951 enum Index {
1952 Expression(Handle<crate::Expression>),
1953 Static(u32),
1954 }
1955
1956 let get_members = |expr: Handle<crate::Expression>| {
1957 let resolved = func_ctx.resolve_type(expr, &module.types);
1958 match *resolved {
1959 TypeInner::Pointer { base, .. } => match module.types[base].inner {
1960 TypeInner::Struct { ref members, .. } => Some(members),
1961 _ => None,
1962 },
1963 _ => None,
1964 }
1965 };
1966
1967 let mut matrix = None;
1968 let mut vector = None;
1969 let mut scalar = None;
1970
1971 let mut current_expr = pointer;
1972 for _ in 0..3 {
1973 let resolved = func_ctx.resolve_type(current_expr, &module.types);
1974
1975 match (resolved, &func_ctx.expressions[current_expr]) {
1976 (
1977 &TypeInner::Pointer { base: ty, .. },
1978 &crate::Expression::AccessIndex { base, index },
1979 ) if matches!(
1980 module.types[ty].inner,
1981 TypeInner::Matrix {
1982 rows: crate::VectorSize::Bi,
1983 ..
1984 }
1985 ) && get_members(base)
1986 .map(|members| members[index as usize].binding.is_none())
1987 == Some(true) =>
1988 {
1989 matrix = Some(MatrixAccess { base, index });
1990 break;
1991 }
1992 (
1993 &TypeInner::ValuePointer {
1994 size: Some(crate::VectorSize::Bi),
1995 ..
1996 },
1997 &crate::Expression::Access { base, index },
1998 ) => {
1999 vector = Some(Index::Expression(index));
2000 current_expr = base;
2001 }
2002 (
2003 &TypeInner::ValuePointer {
2004 size: Some(crate::VectorSize::Bi),
2005 ..
2006 },
2007 &crate::Expression::AccessIndex { base, index },
2008 ) => {
2009 vector = Some(Index::Static(index));
2010 current_expr = base;
2011 }
2012 (
2013 &TypeInner::ValuePointer { size: None, .. },
2014 &crate::Expression::Access { base, index },
2015 ) => {
2016 scalar = Some(Index::Expression(index));
2017 current_expr = base;
2018 }
2019 (
2020 &TypeInner::ValuePointer { size: None, .. },
2021 &crate::Expression::AccessIndex { base, index },
2022 ) => {
2023 scalar = Some(Index::Static(index));
2024 current_expr = base;
2025 }
2026 _ => break,
2027 }
2028 }
2029
2030 write!(self.out, "{level}")?;
2031
2032 if let Some(MatrixAccess { index, base }) = matrix {
2033 let base_ty_res = &func_ctx.info[base].ty;
2034 let resolved = base_ty_res.inner_with(&module.types);
2035 let ty = match *resolved {
2036 TypeInner::Pointer { base, .. } => base,
2037 _ => base_ty_res.handle().unwrap(),
2038 };
2039
2040 if let Some(Index::Static(vec_index)) = vector {
2041 self.write_expr(module, base, func_ctx)?;
2042 write!(
2043 self.out,
2044 ".{}_{}",
2045 &self.names[&NameKey::StructMember(ty, index)],
2046 vec_index
2047 )?;
2048
2049 if let Some(scalar_index) = scalar {
2050 write!(self.out, "[")?;
2051 match scalar_index {
2052 Index::Static(index) => {
2053 write!(self.out, "{index}")?;
2054 }
2055 Index::Expression(index) => {
2056 self.write_expr(module, index, func_ctx)?;
2057 }
2058 }
2059 write!(self.out, "]")?;
2060 }
2061
2062 write!(self.out, " = ")?;
2063 self.write_expr(module, value, func_ctx)?;
2064 writeln!(self.out, ";")?;
2065 } else {
2066 let access = WrappedStructMatrixAccess { ty, index };
2067 match (&vector, &scalar) {
2068 (&Some(_), &Some(_)) => {
2069 self.write_wrapped_struct_matrix_set_scalar_function_name(
2070 access,
2071 )?;
2072 }
2073 (&Some(_), &None) => {
2074 self.write_wrapped_struct_matrix_set_vec_function_name(access)?;
2075 }
2076 (&None, _) => {
2077 self.write_wrapped_struct_matrix_set_function_name(access)?;
2078 }
2079 }
2080
2081 write!(self.out, "(")?;
2082 self.write_expr(module, base, func_ctx)?;
2083 write!(self.out, ", ")?;
2084 self.write_expr(module, value, func_ctx)?;
2085
2086 if let Some(Index::Expression(vec_index)) = vector {
2087 write!(self.out, ", ")?;
2088 self.write_expr(module, vec_index, func_ctx)?;
2089
2090 if let Some(scalar_index) = scalar {
2091 write!(self.out, ", ")?;
2092 match scalar_index {
2093 Index::Static(index) => {
2094 write!(self.out, "{index}")?;
2095 }
2096 Index::Expression(index) => {
2097 self.write_expr(module, index, func_ctx)?;
2098 }
2099 }
2100 }
2101 }
2102 writeln!(self.out, ");")?;
2103 }
2104 } else {
2105 // We handle `Store`s to __matCx2 column vectors and scalar elements via
2106 // the previously injected functions __set_col_of_matCx2 / __set_el_of_matCx2.
2107 struct MatrixData {
2108 columns: crate::VectorSize,
2109 base: Handle<crate::Expression>,
2110 }
2111
2112 enum Index {
2113 Expression(Handle<crate::Expression>),
2114 Static(u32),
2115 }
2116
2117 let mut matrix = None;
2118 let mut vector = None;
2119 let mut scalar = None;
2120
2121 let mut current_expr = pointer;
2122 for _ in 0..3 {
2123 let resolved = func_ctx.resolve_type(current_expr, &module.types);
2124 match (resolved, &func_ctx.expressions[current_expr]) {
2125 (
2126 &TypeInner::ValuePointer {
2127 size: Some(crate::VectorSize::Bi),
2128 ..
2129 },
2130 &crate::Expression::Access { base, index },
2131 ) => {
2132 vector = Some(index);
2133 current_expr = base;
2134 }
2135 (
2136 &TypeInner::ValuePointer { size: None, .. },
2137 &crate::Expression::Access { base, index },
2138 ) => {
2139 scalar = Some(Index::Expression(index));
2140 current_expr = base;
2141 }
2142 (
2143 &TypeInner::ValuePointer { size: None, .. },
2144 &crate::Expression::AccessIndex { base, index },
2145 ) => {
2146 scalar = Some(Index::Static(index));
2147 current_expr = base;
2148 }
2149 _ => {
2150 if let Some(MatrixType {
2151 columns,
2152 rows: crate::VectorSize::Bi,
2153 width: 4,
2154 }) = get_inner_matrix_of_struct_array_member(
2155 module,
2156 current_expr,
2157 func_ctx,
2158 true,
2159 ) {
2160 matrix = Some(MatrixData {
2161 columns,
2162 base: current_expr,
2163 });
2164 }
2165
2166 break;
2167 }
2168 }
2169 }
2170
2171 if let (Some(MatrixData { columns, base }), Some(vec_index)) =
2172 (matrix, vector)
2173 {
2174 if scalar.is_some() {
2175 write!(self.out, "__set_el_of_mat{}x2", columns as u8)?;
2176 } else {
2177 write!(self.out, "__set_col_of_mat{}x2", columns as u8)?;
2178 }
2179 write!(self.out, "(")?;
2180 self.write_expr(module, base, func_ctx)?;
2181 write!(self.out, ", ")?;
2182 self.write_expr(module, vec_index, func_ctx)?;
2183
2184 if let Some(scalar_index) = scalar {
2185 write!(self.out, ", ")?;
2186 match scalar_index {
2187 Index::Static(index) => {
2188 write!(self.out, "{index}")?;
2189 }
2190 Index::Expression(index) => {
2191 self.write_expr(module, index, func_ctx)?;
2192 }
2193 }
2194 }
2195
2196 write!(self.out, ", ")?;
2197 self.write_expr(module, value, func_ctx)?;
2198
2199 writeln!(self.out, ");")?;
2200 } else {
2201 self.write_expr(module, pointer, func_ctx)?;
2202 write!(self.out, " = ")?;
2203
2204 // We cast the RHS of this store in cases where the LHS
2205 // is a struct member with type:
2206 // - matCx2 or
2207 // - a (possibly nested) array of matCx2's
2208 if let Some(MatrixType {
2209 columns,
2210 rows: crate::VectorSize::Bi,
2211 width: 4,
2212 }) = get_inner_matrix_of_struct_array_member(
2213 module, pointer, func_ctx, false,
2214 ) {
2215 let mut resolved = func_ctx.resolve_type(pointer, &module.types);
2216 if let TypeInner::Pointer { base, .. } = *resolved {
2217 resolved = &module.types[base].inner;
2218 }
2219
2220 write!(self.out, "(__mat{}x2", columns as u8)?;
2221 if let TypeInner::Array { base, size, .. } = *resolved {
2222 self.write_array_size(module, base, size)?;
2223 }
2224 write!(self.out, ")")?;
2225 }
2226
2227 self.write_expr(module, value, func_ctx)?;
2228 writeln!(self.out, ";")?
2229 }
2230 }
2231 }
2232 }
2233 Statement::Loop {
2234 ref body,
2235 ref continuing,
2236 break_if,
2237 } => {
2238 let force_loop_bound_statements = self.gen_force_bounded_loop_statements(level);
2239 let gate_name = (!continuing.is_empty() || break_if.is_some())
2240 .then(|| self.namer.call("loop_init"));
2241
2242 if let Some((ref decl, _)) = force_loop_bound_statements {
2243 writeln!(self.out, "{decl}")?;
2244 }
2245 if let Some(ref gate_name) = gate_name {
2246 writeln!(self.out, "{level}bool {gate_name} = true;")?;
2247 }
2248
2249 self.continue_ctx.enter_loop();
2250 writeln!(self.out, "{level}while(true) {{")?;
2251 if let Some((_, ref break_and_inc)) = force_loop_bound_statements {
2252 writeln!(self.out, "{break_and_inc}")?;
2253 }
2254 let l2 = level.next();
2255 if let Some(gate_name) = gate_name {
2256 writeln!(self.out, "{l2}if (!{gate_name}) {{")?;
2257 let l3 = l2.next();
2258 for sta in continuing.iter() {
2259 self.write_stmt(module, sta, func_ctx, l3)?;
2260 }
2261 if let Some(condition) = break_if {
2262 write!(self.out, "{l3}if (")?;
2263 self.write_expr(module, condition, func_ctx)?;
2264 writeln!(self.out, ") {{")?;
2265 writeln!(self.out, "{}break;", l3.next())?;
2266 writeln!(self.out, "{l3}}}")?;
2267 }
2268 writeln!(self.out, "{l2}}}")?;
2269 writeln!(self.out, "{l2}{gate_name} = false;")?;
2270 }
2271
2272 for sta in body.iter() {
2273 self.write_stmt(module, sta, func_ctx, l2)?;
2274 }
2275
2276 writeln!(self.out, "{level}}}")?;
2277 self.continue_ctx.exit_loop();
2278 }
2279 Statement::Break => writeln!(self.out, "{level}break;")?,
2280 Statement::Continue => {
2281 if let Some(variable) = self.continue_ctx.continue_encountered() {
2282 writeln!(self.out, "{level}{variable} = true;")?;
2283 writeln!(self.out, "{level}break;")?
2284 } else {
2285 writeln!(self.out, "{level}continue;")?
2286 }
2287 }
2288 Statement::Barrier(barrier) => {
2289 self.write_barrier(barrier, level)?;
2290 }
2291 Statement::ImageStore {
2292 image,
2293 coordinate,
2294 array_index,
2295 value,
2296 } => {
2297 write!(self.out, "{level}")?;
2298 self.write_expr(module, image, func_ctx)?;
2299
2300 write!(self.out, "[")?;
2301 if let Some(index) = array_index {
2302 // Array index accepted only for texture_storage_2d_array, so we can safety use int3(coordinate, array_index) here
2303 write!(self.out, "int3(")?;
2304 self.write_expr(module, coordinate, func_ctx)?;
2305 write!(self.out, ", ")?;
2306 self.write_expr(module, index, func_ctx)?;
2307 write!(self.out, ")")?;
2308 } else {
2309 self.write_expr(module, coordinate, func_ctx)?;
2310 }
2311 write!(self.out, "]")?;
2312
2313 write!(self.out, " = ")?;
2314 self.write_expr(module, value, func_ctx)?;
2315 writeln!(self.out, ";")?;
2316 }
2317 Statement::Call {
2318 function,
2319 ref arguments,
2320 result,
2321 } => {
2322 write!(self.out, "{level}")?;
2323 if let Some(expr) = result {
2324 write!(self.out, "const ")?;
2325 let name = Baked(expr).to_string();
2326 let expr_ty = &func_ctx.info[expr].ty;
2327 let ty_inner = match *expr_ty {
2328 proc::TypeResolution::Handle(handle) => {
2329 self.write_type(module, handle)?;
2330 &module.types[handle].inner
2331 }
2332 proc::TypeResolution::Value(ref value) => {
2333 self.write_value_type(module, value)?;
2334 value
2335 }
2336 };
2337 write!(self.out, " {name}")?;
2338 if let TypeInner::Array { base, size, .. } = *ty_inner {
2339 self.write_array_size(module, base, size)?;
2340 }
2341 write!(self.out, " = ")?;
2342 self.named_expressions.insert(expr, name);
2343 }
2344 let func_name = &self.names[&NameKey::Function(function)];
2345 write!(self.out, "{func_name}(")?;
2346 for (index, argument) in arguments.iter().enumerate() {
2347 if index != 0 {
2348 write!(self.out, ", ")?;
2349 }
2350 self.write_expr(module, *argument, func_ctx)?;
2351 }
2352 writeln!(self.out, ");")?
2353 }
2354 Statement::Atomic {
2355 pointer,
2356 ref fun,
2357 value,
2358 result,
2359 } => {
2360 write!(self.out, "{level}")?;
2361 let res_name = match result {
2362 None => None,
2363 Some(result) => {
2364 let name = Baked(result).to_string();
2365 match func_ctx.info[result].ty {
2366 proc::TypeResolution::Handle(handle) => {
2367 self.write_type(module, handle)?
2368 }
2369 proc::TypeResolution::Value(ref value) => {
2370 self.write_value_type(module, value)?
2371 }
2372 };
2373 write!(self.out, " {name}; ")?;
2374 Some((result, name))
2375 }
2376 };
2377
2378 // Validation ensures that `pointer` has a `Pointer` type.
2379 let pointer_space = func_ctx
2380 .resolve_type(pointer, &module.types)
2381 .pointer_space()
2382 .unwrap();
2383
2384 let fun_str = fun.to_hlsl_suffix();
2385 match pointer_space {
2386 crate::AddressSpace::WorkGroup => {
2387 write!(self.out, "Interlocked{fun_str}(")?;
2388 self.write_expr(module, pointer, func_ctx)?;
2389 }
2390 crate::AddressSpace::Storage { .. } => {
2391 let var_handle = self.fill_access_chain(module, pointer, func_ctx)?;
2392 // The call to `self.write_storage_address` wants
2393 // mutable access to all of `self`, so temporarily take
2394 // ownership of our reusable access chain buffer.
2395 let chain = mem::take(&mut self.temp_access_chain);
2396 let var_name = &self.names[&NameKey::GlobalVariable(var_handle)];
2397 let width = match func_ctx.resolve_type(value, &module.types) {
2398 &TypeInner::Scalar(Scalar { width: 8, .. }) => "64",
2399 _ => "",
2400 };
2401 write!(self.out, "{var_name}.Interlocked{fun_str}{width}(")?;
2402 self.write_storage_address(module, &chain, func_ctx)?;
2403 self.temp_access_chain = chain;
2404 }
2405 ref other => {
2406 return Err(Error::Custom(format!(
2407 "invalid address space {other:?} for atomic statement"
2408 )))
2409 }
2410 }
2411 write!(self.out, ", ")?;
2412 // handle the special cases
2413 match *fun {
2414 crate::AtomicFunction::Subtract => {
2415 // we just wrote `InterlockedAdd`, so negate the argument
2416 write!(self.out, "-")?;
2417 }
2418 crate::AtomicFunction::Exchange { compare: Some(_) } => {
2419 return Err(Error::Unimplemented("atomic CompareExchange".to_string()));
2420 }
2421 _ => {}
2422 }
2423 self.write_expr(module, value, func_ctx)?;
2424
2425 // The `original_value` out parameter is optional for all the
2426 // `Interlocked` functions we generate other than
2427 // `InterlockedExchange`.
2428 if let Some((result, name)) = res_name {
2429 write!(self.out, ", {name}")?;
2430 self.named_expressions.insert(result, name);
2431 }
2432
2433 writeln!(self.out, ");")?;
2434 }
2435 Statement::ImageAtomic {
2436 image,
2437 coordinate,
2438 array_index,
2439 fun,
2440 value,
2441 } => {
2442 write!(self.out, "{level}")?;
2443
2444 let fun_str = fun.to_hlsl_suffix();
2445 write!(self.out, "Interlocked{fun_str}(")?;
2446 self.write_expr(module, image, func_ctx)?;
2447 write!(self.out, "[")?;
2448 self.write_texture_coordinates(
2449 "int",
2450 coordinate,
2451 array_index,
2452 None,
2453 module,
2454 func_ctx,
2455 )?;
2456 write!(self.out, "],")?;
2457
2458 self.write_expr(module, value, func_ctx)?;
2459 writeln!(self.out, ");")?;
2460 }
2461 Statement::WorkGroupUniformLoad { pointer, result } => {
2462 self.write_barrier(crate::Barrier::WORK_GROUP, level)?;
2463 write!(self.out, "{level}")?;
2464 let name = Baked(result).to_string();
2465 self.write_named_expr(module, pointer, name, result, func_ctx)?;
2466
2467 self.write_barrier(crate::Barrier::WORK_GROUP, level)?;
2468 }
2469 Statement::Switch {
2470 selector,
2471 ref cases,
2472 } => {
2473 self.write_switch(module, func_ctx, level, selector, cases)?;
2474 }
2475 Statement::RayQuery { query, ref fun } => match *fun {
2476 RayQueryFunction::Initialize {
2477 acceleration_structure,
2478 descriptor,
2479 } => {
2480 write!(self.out, "{level}")?;
2481 self.write_expr(module, query, func_ctx)?;
2482 write!(self.out, ".TraceRayInline(")?;
2483 self.write_expr(module, acceleration_structure, func_ctx)?;
2484 write!(self.out, ", ")?;
2485 self.write_expr(module, descriptor, func_ctx)?;
2486 write!(self.out, ".flags, ")?;
2487 self.write_expr(module, descriptor, func_ctx)?;
2488 write!(self.out, ".cull_mask, ")?;
2489 write!(self.out, "RayDescFromRayDesc_(")?;
2490 self.write_expr(module, descriptor, func_ctx)?;
2491 writeln!(self.out, "));")?;
2492 }
2493 RayQueryFunction::Proceed { result } => {
2494 write!(self.out, "{level}")?;
2495 let name = Baked(result).to_string();
2496 write!(self.out, "const bool {name} = ")?;
2497 self.named_expressions.insert(result, name);
2498 self.write_expr(module, query, func_ctx)?;
2499 writeln!(self.out, ".Proceed();")?;
2500 }
2501 RayQueryFunction::GenerateIntersection { hit_t } => {
2502 write!(self.out, "{level}")?;
2503 self.write_expr(module, query, func_ctx)?;
2504 write!(self.out, ".CommitProceduralPrimitiveHit(")?;
2505 self.write_expr(module, hit_t, func_ctx)?;
2506 writeln!(self.out, ");")?;
2507 }
2508 RayQueryFunction::ConfirmIntersection => {
2509 write!(self.out, "{level}")?;
2510 self.write_expr(module, query, func_ctx)?;
2511 writeln!(self.out, ".CommitNonOpaqueTriangleHit();")?;
2512 }
2513 RayQueryFunction::Terminate => {
2514 write!(self.out, "{level}")?;
2515 self.write_expr(module, query, func_ctx)?;
2516 writeln!(self.out, ".Abort();")?;
2517 }
2518 },
2519 Statement::SubgroupBallot { result, predicate } => {
2520 write!(self.out, "{level}")?;
2521 let name = Baked(result).to_string();
2522 write!(self.out, "const uint4 {name} = ")?;
2523 self.named_expressions.insert(result, name);
2524
2525 write!(self.out, "WaveActiveBallot(")?;
2526 match predicate {
2527 Some(predicate) => self.write_expr(module, predicate, func_ctx)?,
2528 None => write!(self.out, "true")?,
2529 }
2530 writeln!(self.out, ");")?;
2531 }
2532 Statement::SubgroupCollectiveOperation {
2533 op,
2534 collective_op,
2535 argument,
2536 result,
2537 } => {
2538 write!(self.out, "{level}")?;
2539 write!(self.out, "const ")?;
2540 let name = Baked(result).to_string();
2541 match func_ctx.info[result].ty {
2542 proc::TypeResolution::Handle(handle) => self.write_type(module, handle)?,
2543 proc::TypeResolution::Value(ref value) => {
2544 self.write_value_type(module, value)?
2545 }
2546 };
2547 write!(self.out, " {name} = ")?;
2548 self.named_expressions.insert(result, name);
2549
2550 match (collective_op, op) {
2551 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::All) => {
2552 write!(self.out, "WaveActiveAllTrue(")?
2553 }
2554 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Any) => {
2555 write!(self.out, "WaveActiveAnyTrue(")?
2556 }
2557 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Add) => {
2558 write!(self.out, "WaveActiveSum(")?
2559 }
2560 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Mul) => {
2561 write!(self.out, "WaveActiveProduct(")?
2562 }
2563 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Max) => {
2564 write!(self.out, "WaveActiveMax(")?
2565 }
2566 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Min) => {
2567 write!(self.out, "WaveActiveMin(")?
2568 }
2569 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::And) => {
2570 write!(self.out, "WaveActiveBitAnd(")?
2571 }
2572 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Or) => {
2573 write!(self.out, "WaveActiveBitOr(")?
2574 }
2575 (crate::CollectiveOperation::Reduce, crate::SubgroupOperation::Xor) => {
2576 write!(self.out, "WaveActiveBitXor(")?
2577 }
2578 (crate::CollectiveOperation::ExclusiveScan, crate::SubgroupOperation::Add) => {
2579 write!(self.out, "WavePrefixSum(")?
2580 }
2581 (crate::CollectiveOperation::ExclusiveScan, crate::SubgroupOperation::Mul) => {
2582 write!(self.out, "WavePrefixProduct(")?
2583 }
2584 (crate::CollectiveOperation::InclusiveScan, crate::SubgroupOperation::Add) => {
2585 self.write_expr(module, argument, func_ctx)?;
2586 write!(self.out, " + WavePrefixSum(")?;
2587 }
2588 (crate::CollectiveOperation::InclusiveScan, crate::SubgroupOperation::Mul) => {
2589 self.write_expr(module, argument, func_ctx)?;
2590 write!(self.out, " * WavePrefixProduct(")?;
2591 }
2592 _ => unimplemented!(),
2593 }
2594 self.write_expr(module, argument, func_ctx)?;
2595 writeln!(self.out, ");")?;
2596 }
2597 Statement::SubgroupGather {
2598 mode,
2599 argument,
2600 result,
2601 } => {
2602 write!(self.out, "{level}")?;
2603 write!(self.out, "const ")?;
2604 let name = Baked(result).to_string();
2605 match func_ctx.info[result].ty {
2606 proc::TypeResolution::Handle(handle) => self.write_type(module, handle)?,
2607 proc::TypeResolution::Value(ref value) => {
2608 self.write_value_type(module, value)?
2609 }
2610 };
2611 write!(self.out, " {name} = ")?;
2612 self.named_expressions.insert(result, name);
2613
2614 if matches!(mode, crate::GatherMode::BroadcastFirst) {
2615 write!(self.out, "WaveReadLaneFirst(")?;
2616 self.write_expr(module, argument, func_ctx)?;
2617 } else {
2618 write!(self.out, "WaveReadLaneAt(")?;
2619 self.write_expr(module, argument, func_ctx)?;
2620 write!(self.out, ", ")?;
2621 match mode {
2622 crate::GatherMode::BroadcastFirst => unreachable!(),
2623 crate::GatherMode::Broadcast(index) | crate::GatherMode::Shuffle(index) => {
2624 self.write_expr(module, index, func_ctx)?;
2625 }
2626 crate::GatherMode::ShuffleDown(index) => {
2627 write!(self.out, "WaveGetLaneIndex() + ")?;
2628 self.write_expr(module, index, func_ctx)?;
2629 }
2630 crate::GatherMode::ShuffleUp(index) => {
2631 write!(self.out, "WaveGetLaneIndex() - ")?;
2632 self.write_expr(module, index, func_ctx)?;
2633 }
2634 crate::GatherMode::ShuffleXor(index) => {
2635 write!(self.out, "WaveGetLaneIndex() ^ ")?;
2636 self.write_expr(module, index, func_ctx)?;
2637 }
2638 }
2639 }
2640 writeln!(self.out, ");")?;
2641 }
2642 }
2643
2644 Ok(())
2645 }
2646
2647 fn write_const_expression(
2648 &mut self,
2649 module: &Module,
2650 expr: Handle<crate::Expression>,
2651 arena: &crate::Arena<crate::Expression>,
2652 ) -> BackendResult {
2653 self.write_possibly_const_expression(module, expr, arena, |writer, expr| {
2654 writer.write_const_expression(module, expr, arena)
2655 })
2656 }
2657
2658 pub(super) fn write_literal(&mut self, literal: crate::Literal) -> BackendResult {
2659 match literal {
2660 crate::Literal::F64(value) => write!(self.out, "{value:?}L")?,
2661 crate::Literal::F32(value) => write!(self.out, "{value:?}")?,
2662 crate::Literal::F16(value) => write!(self.out, "{value:?}h")?,
2663 crate::Literal::U32(value) => write!(self.out, "{value}u")?,
2664 // `-2147483648` is parsed by some compilers as unary negation of
2665 // positive 2147483648, which is too large for an int, causing
2666 // issues for some compilers. Neither DXC nor FXC appear to have
2667 // this problem, but this is not specified and could change. We
2668 // therefore use `-2147483647 - 1` as a precaution.
2669 crate::Literal::I32(value) if value == i32::MIN => {
2670 write!(self.out, "int({} - 1)", value + 1)?
2671 }
2672 // HLSL has no suffix for explicit i32 literals, but not using any suffix
2673 // makes the type ambiguous which prevents overload resolution from
2674 // working. So we explicitly use the int() constructor syntax.
2675 crate::Literal::I32(value) => write!(self.out, "int({value})")?,
2676 crate::Literal::U64(value) => write!(self.out, "{value}uL")?,
2677 // I64 version of the minimum I32 value issue described above.
2678 crate::Literal::I64(value) if value == i64::MIN => {
2679 write!(self.out, "({}L - 1L)", value + 1)?;
2680 }
2681 crate::Literal::I64(value) => write!(self.out, "{value}L")?,
2682 crate::Literal::Bool(value) => write!(self.out, "{value}")?,
2683 crate::Literal::AbstractInt(_) | crate::Literal::AbstractFloat(_) => {
2684 return Err(Error::Custom(
2685 "Abstract types should not appear in IR presented to backends".into(),
2686 ));
2687 }
2688 }
2689 Ok(())
2690 }
2691
2692 fn write_possibly_const_expression<E>(
2693 &mut self,
2694 module: &Module,
2695 expr: Handle<crate::Expression>,
2696 expressions: &crate::Arena<crate::Expression>,
2697 write_expression: E,
2698 ) -> BackendResult
2699 where
2700 E: Fn(&mut Self, Handle<crate::Expression>) -> BackendResult,
2701 {
2702 use crate::Expression;
2703
2704 match expressions[expr] {
2705 Expression::Literal(literal) => {
2706 self.write_literal(literal)?;
2707 }
2708 Expression::Constant(handle) => {
2709 let constant = &module.constants[handle];
2710 if constant.name.is_some() {
2711 write!(self.out, "{}", self.names[&NameKey::Constant(handle)])?;
2712 } else {
2713 self.write_const_expression(module, constant.init, &module.global_expressions)?;
2714 }
2715 }
2716 Expression::ZeroValue(ty) => {
2717 self.write_wrapped_zero_value_function_name(module, WrappedZeroValue { ty })?;
2718 write!(self.out, "()")?;
2719 }
2720 Expression::Compose { ty, ref components } => {
2721 match module.types[ty].inner {
2722 TypeInner::Struct { .. } | TypeInner::Array { .. } => {
2723 self.write_wrapped_constructor_function_name(
2724 module,
2725 WrappedConstructor { ty },
2726 )?;
2727 }
2728 _ => {
2729 self.write_type(module, ty)?;
2730 }
2731 };
2732 write!(self.out, "(")?;
2733 for (index, component) in components.iter().enumerate() {
2734 if index != 0 {
2735 write!(self.out, ", ")?;
2736 }
2737 write_expression(self, *component)?;
2738 }
2739 write!(self.out, ")")?;
2740 }
2741 Expression::Splat { size, value } => {
2742 // hlsl is not supported one value constructor
2743 // if we write, for example, int4(0), dxc returns error:
2744 // error: too few elements in vector initialization (expected 4 elements, have 1)
2745 let number_of_components = match size {
2746 crate::VectorSize::Bi => "xx",
2747 crate::VectorSize::Tri => "xxx",
2748 crate::VectorSize::Quad => "xxxx",
2749 };
2750 write!(self.out, "(")?;
2751 write_expression(self, value)?;
2752 write!(self.out, ").{number_of_components}")?
2753 }
2754 _ => {
2755 return Err(Error::Override);
2756 }
2757 }
2758
2759 Ok(())
2760 }
2761
2762 /// Helper method to write expressions
2763 ///
2764 /// # Notes
2765 /// Doesn't add any newlines or leading/trailing spaces
2766 pub(super) fn write_expr(
2767 &mut self,
2768 module: &Module,
2769 expr: Handle<crate::Expression>,
2770 func_ctx: &back::FunctionCtx<'_>,
2771 ) -> BackendResult {
2772 use crate::Expression;
2773
2774 // Handle the special semantics of vertex_index/instance_index
2775 let ff_input = if self.options.special_constants_binding.is_some() {
2776 func_ctx.is_fixed_function_input(expr, module)
2777 } else {
2778 None
2779 };
2780 let closing_bracket = match ff_input {
2781 Some(crate::BuiltIn::VertexIndex) => {
2782 write!(self.out, "({SPECIAL_CBUF_VAR}.{SPECIAL_FIRST_VERTEX} + ")?;
2783 ")"
2784 }
2785 Some(crate::BuiltIn::InstanceIndex) => {
2786 write!(self.out, "({SPECIAL_CBUF_VAR}.{SPECIAL_FIRST_INSTANCE} + ",)?;
2787 ")"
2788 }
2789 Some(crate::BuiltIn::NumWorkGroups) => {
2790 // Note: despite their names (`FIRST_VERTEX` and `FIRST_INSTANCE`),
2791 // in compute shaders the special constants contain the number
2792 // of workgroups, which we are using here.
2793 write!(
2794 self.out,
2795 "uint3({SPECIAL_CBUF_VAR}.{SPECIAL_FIRST_VERTEX}, {SPECIAL_CBUF_VAR}.{SPECIAL_FIRST_INSTANCE}, {SPECIAL_CBUF_VAR}.{SPECIAL_OTHER})",
2796 )?;
2797 return Ok(());
2798 }
2799 _ => "",
2800 };
2801
2802 if let Some(name) = self.named_expressions.get(&expr) {
2803 write!(self.out, "{name}{closing_bracket}")?;
2804 return Ok(());
2805 }
2806
2807 let expression = &func_ctx.expressions[expr];
2808
2809 match *expression {
2810 Expression::Literal(_)
2811 | Expression::Constant(_)
2812 | Expression::ZeroValue(_)
2813 | Expression::Compose { .. }
2814 | Expression::Splat { .. } => {
2815 self.write_possibly_const_expression(
2816 module,
2817 expr,
2818 func_ctx.expressions,
2819 |writer, expr| writer.write_expr(module, expr, func_ctx),
2820 )?;
2821 }
2822 Expression::Override(_) => return Err(Error::Override),
2823 // Avoid undefined behaviour for addition, subtraction, and
2824 // multiplication of signed integers by casting operands to
2825 // unsigned, performing the operation, then casting the result back
2826 // to signed.
2827 // TODO(#7109): This relies on the asint()/asuint() functions which only work
2828 // for 32-bit types, so we must find another solution for different bit widths.
2829 Expression::Binary {
2830 op:
2831 op @ crate::BinaryOperator::Add
2832 | op @ crate::BinaryOperator::Subtract
2833 | op @ crate::BinaryOperator::Multiply,
2834 left,
2835 right,
2836 } if matches!(
2837 func_ctx.resolve_type(expr, &module.types).scalar(),
2838 Some(Scalar::I32)
2839 ) =>
2840 {
2841 write!(self.out, "asint(asuint(",)?;
2842 self.write_expr(module, left, func_ctx)?;
2843 write!(self.out, ") {} asuint(", back::binary_operation_str(op))?;
2844 self.write_expr(module, right, func_ctx)?;
2845 write!(self.out, "))")?;
2846 }
2847 // All of the multiplication can be expressed as `mul`,
2848 // except vector * vector, which needs to use the "*" operator.
2849 Expression::Binary {
2850 op: crate::BinaryOperator::Multiply,
2851 left,
2852 right,
2853 } if func_ctx.resolve_type(left, &module.types).is_matrix()
2854 || func_ctx.resolve_type(right, &module.types).is_matrix() =>
2855 {
2856 // We intentionally flip the order of multiplication as our matrices are implicitly transposed.
2857 write!(self.out, "mul(")?;
2858 self.write_expr(module, right, func_ctx)?;
2859 write!(self.out, ", ")?;
2860 self.write_expr(module, left, func_ctx)?;
2861 write!(self.out, ")")?;
2862 }
2863
2864 // WGSL says that floating-point division by zero should return
2865 // infinity. Microsoft's Direct3D 11 functional specification
2866 // (https://microsoft.github.io/DirectX-Specs/d3d/archive/D3D11_3_FunctionalSpec.htm)
2867 // says:
2868 //
2869 // Divide by 0 produces +/- INF, except 0/0 which results in NaN.
2870 //
2871 // which is what we want. The DXIL specification for the FDiv
2872 // instruction corroborates this:
2873 //
2874 // https://github.com/microsoft/DirectXShaderCompiler/blob/main/docs/DXIL.rst#fdiv
2875 Expression::Binary {
2876 op: crate::BinaryOperator::Divide,
2877 left,
2878 right,
2879 } if matches!(
2880 func_ctx.resolve_type(expr, &module.types).scalar_kind(),
2881 Some(ScalarKind::Sint | ScalarKind::Uint)
2882 ) =>
2883 {
2884 write!(self.out, "{DIV_FUNCTION}(")?;
2885 self.write_expr(module, left, func_ctx)?;
2886 write!(self.out, ", ")?;
2887 self.write_expr(module, right, func_ctx)?;
2888 write!(self.out, ")")?;
2889 }
2890
2891 Expression::Binary {
2892 op: crate::BinaryOperator::Modulo,
2893 left,
2894 right,
2895 } if matches!(
2896 func_ctx.resolve_type(expr, &module.types).scalar_kind(),
2897 Some(ScalarKind::Sint | ScalarKind::Uint)
2898 ) =>
2899 {
2900 write!(self.out, "{MOD_FUNCTION}(")?;
2901 self.write_expr(module, left, func_ctx)?;
2902 write!(self.out, ", ")?;
2903 self.write_expr(module, right, func_ctx)?;
2904 write!(self.out, ")")?;
2905 }
2906
2907 // While HLSL supports float operands with the % operator it is only
2908 // defined in cases where both sides are either positive or negative.
2909 Expression::Binary {
2910 op: crate::BinaryOperator::Modulo,
2911 left,
2912 right,
2913 } if func_ctx.resolve_type(left, &module.types).scalar_kind()
2914 == Some(ScalarKind::Float) =>
2915 {
2916 write!(self.out, "fmod(")?;
2917 self.write_expr(module, left, func_ctx)?;
2918 write!(self.out, ", ")?;
2919 self.write_expr(module, right, func_ctx)?;
2920 write!(self.out, ")")?;
2921 }
2922 Expression::Binary { op, left, right } => {
2923 write!(self.out, "(")?;
2924 self.write_expr(module, left, func_ctx)?;
2925 write!(self.out, " {} ", back::binary_operation_str(op))?;
2926 self.write_expr(module, right, func_ctx)?;
2927 write!(self.out, ")")?;
2928 }
2929 Expression::Access { base, index } => {
2930 if let Some(crate::AddressSpace::Storage { .. }) =
2931 func_ctx.resolve_type(expr, &module.types).pointer_space()
2932 {
2933 // do nothing, the chain is written on `Load`/`Store`
2934 } else {
2935 // We use the function __get_col_of_matCx2 here in cases
2936 // where `base`s type resolves to a matCx2 and is part of a
2937 // struct member with type of (possibly nested) array of matCx2's.
2938 //
2939 // Note that this only works for `Load`s and we handle
2940 // `Store`s differently in `Statement::Store`.
2941 if let Some(MatrixType {
2942 columns,
2943 rows: crate::VectorSize::Bi,
2944 width: 4,
2945 }) = get_inner_matrix_of_struct_array_member(module, base, func_ctx, true)
2946 {
2947 write!(self.out, "__get_col_of_mat{}x2(", columns as u8)?;
2948 self.write_expr(module, base, func_ctx)?;
2949 write!(self.out, ", ")?;
2950 self.write_expr(module, index, func_ctx)?;
2951 write!(self.out, ")")?;
2952 return Ok(());
2953 }
2954
2955 let resolved = func_ctx.resolve_type(base, &module.types);
2956
2957 let (indexing_binding_array, non_uniform_qualifier) = match *resolved {
2958 TypeInner::BindingArray { .. } => {
2959 let uniformity = &func_ctx.info[index].uniformity;
2960
2961 (true, uniformity.non_uniform_result.is_some())
2962 }
2963 _ => (false, false),
2964 };
2965
2966 self.write_expr(module, base, func_ctx)?;
2967
2968 let array_sampler_info = self.sampler_binding_array_info_from_expression(
2969 module, func_ctx, base, resolved,
2970 );
2971
2972 if let Some(ref info) = array_sampler_info {
2973 write!(self.out, "{}[", info.sampler_heap_name)?;
2974 } else {
2975 write!(self.out, "[")?;
2976 }
2977
2978 let needs_bound_check = self.options.restrict_indexing
2979 && !indexing_binding_array
2980 && match resolved.pointer_space() {
2981 Some(
2982 crate::AddressSpace::Function
2983 | crate::AddressSpace::Private
2984 | crate::AddressSpace::WorkGroup
2985 | crate::AddressSpace::PushConstant,
2986 )
2987 | None => true,
2988 Some(crate::AddressSpace::Uniform) => {
2989 // check if BindTarget.restrict_indexing is set, this is used for dynamic buffers
2990 let var_handle = self.fill_access_chain(module, base, func_ctx)?;
2991 let bind_target = self
2992 .options
2993 .resolve_resource_binding(
2994 module.global_variables[var_handle]
2995 .binding
2996 .as_ref()
2997 .unwrap(),
2998 )
2999 .unwrap();
3000 bind_target.restrict_indexing
3001 }
3002 Some(
3003 crate::AddressSpace::Handle | crate::AddressSpace::Storage { .. },
3004 ) => unreachable!(),
3005 };
3006 // Decide whether this index needs to be clamped to fall within range.
3007 let restriction_needed = if needs_bound_check {
3008 index::access_needs_check(
3009 base,
3010 index::GuardedIndex::Expression(index),
3011 module,
3012 func_ctx.expressions,
3013 func_ctx.info,
3014 )
3015 } else {
3016 None
3017 };
3018 if let Some(limit) = restriction_needed {
3019 write!(self.out, "min(uint(")?;
3020 self.write_expr(module, index, func_ctx)?;
3021 write!(self.out, "), ")?;
3022 match limit {
3023 index::IndexableLength::Known(limit) => {
3024 write!(self.out, "{}u", limit - 1)?;
3025 }
3026 index::IndexableLength::Dynamic => unreachable!(),
3027 }
3028 write!(self.out, ")")?;
3029 } else {
3030 if non_uniform_qualifier {
3031 write!(self.out, "NonUniformResourceIndex(")?;
3032 }
3033 if let Some(ref info) = array_sampler_info {
3034 write!(
3035 self.out,
3036 "{}[{} + ",
3037 info.sampler_index_buffer_name, info.binding_array_base_index_name,
3038 )?;
3039 }
3040 self.write_expr(module, index, func_ctx)?;
3041 if array_sampler_info.is_some() {
3042 write!(self.out, "]")?;
3043 }
3044 if non_uniform_qualifier {
3045 write!(self.out, ")")?;
3046 }
3047 }
3048
3049 write!(self.out, "]")?;
3050 }
3051 }
3052 Expression::AccessIndex { base, index } => {
3053 if let Some(crate::AddressSpace::Storage { .. }) =
3054 func_ctx.resolve_type(expr, &module.types).pointer_space()
3055 {
3056 // do nothing, the chain is written on `Load`/`Store`
3057 } else {
3058 // We write the matrix column access in a special way since
3059 // the type of `base` is our special __matCx2 struct.
3060 if let Some(MatrixType {
3061 rows: crate::VectorSize::Bi,
3062 width: 4,
3063 ..
3064 }) = get_inner_matrix_of_struct_array_member(module, base, func_ctx, true)
3065 {
3066 self.write_expr(module, base, func_ctx)?;
3067 write!(self.out, "._{index}")?;
3068 return Ok(());
3069 }
3070
3071 let base_ty_res = &func_ctx.info[base].ty;
3072 let mut resolved = base_ty_res.inner_with(&module.types);
3073 let base_ty_handle = match *resolved {
3074 TypeInner::Pointer { base, .. } => {
3075 resolved = &module.types[base].inner;
3076 Some(base)
3077 }
3078 _ => base_ty_res.handle(),
3079 };
3080
3081 // We treat matrices of the form `matCx2` as a sequence of C `vec2`s.
3082 // See the module-level block comment in mod.rs for details.
3083 //
3084 // We handle matrix reconstruction here for Loads.
3085 // Stores are handled directly by `Statement::Store`.
3086 if let TypeInner::Struct { ref members, .. } = *resolved {
3087 let member = &members[index as usize];
3088
3089 match module.types[member.ty].inner {
3090 TypeInner::Matrix {
3091 rows: crate::VectorSize::Bi,
3092 ..
3093 } if member.binding.is_none() => {
3094 let ty = base_ty_handle.unwrap();
3095 self.write_wrapped_struct_matrix_get_function_name(
3096 WrappedStructMatrixAccess { ty, index },
3097 )?;
3098 write!(self.out, "(")?;
3099 self.write_expr(module, base, func_ctx)?;
3100 write!(self.out, ")")?;
3101 return Ok(());
3102 }
3103 _ => {}
3104 }
3105 }
3106
3107 let array_sampler_info = self.sampler_binding_array_info_from_expression(
3108 module, func_ctx, base, resolved,
3109 );
3110
3111 if let Some(ref info) = array_sampler_info {
3112 write!(
3113 self.out,
3114 "{}[{}",
3115 info.sampler_heap_name, info.sampler_index_buffer_name
3116 )?;
3117 }
3118
3119 self.write_expr(module, base, func_ctx)?;
3120
3121 match *resolved {
3122 // We specifically lift the ValuePointer to this case. While `[0]` is valid
3123 // HLSL for any vector behind a value pointer, FXC completely miscompiles
3124 // it and generates completely nonsensical DXBC.
3125 //
3126 // See https://github.com/gfx-rs/naga/issues/2095 for more details.
3127 TypeInner::Vector { .. } | TypeInner::ValuePointer { .. } => {
3128 // Write vector access as a swizzle
3129 write!(self.out, ".{}", back::COMPONENTS[index as usize])?
3130 }
3131 TypeInner::Matrix { .. }
3132 | TypeInner::Array { .. }
3133 | TypeInner::BindingArray { .. } => {
3134 if let Some(ref info) = array_sampler_info {
3135 write!(
3136 self.out,
3137 "[{} + {index}]",
3138 info.binding_array_base_index_name
3139 )?;
3140 } else {
3141 write!(self.out, "[{index}]")?;
3142 }
3143 }
3144 TypeInner::Struct { .. } => {
3145 // This will never panic in case the type is a `Struct`, this is not true
3146 // for other types so we can only check while inside this match arm
3147 let ty = base_ty_handle.unwrap();
3148
3149 write!(
3150 self.out,
3151 ".{}",
3152 &self.names[&NameKey::StructMember(ty, index)]
3153 )?
3154 }
3155 ref other => return Err(Error::Custom(format!("Cannot index {other:?}"))),
3156 }
3157
3158 if array_sampler_info.is_some() {
3159 write!(self.out, "]")?;
3160 }
3161 }
3162 }
3163 Expression::FunctionArgument(pos) => {
3164 let key = func_ctx.argument_key(pos);
3165 let name = &self.names[&key];
3166 write!(self.out, "{name}")?;
3167 }
3168 Expression::ImageSample {
3169 image,
3170 sampler,
3171 gather,
3172 coordinate,
3173 array_index,
3174 offset,
3175 level,
3176 depth_ref,
3177 } => {
3178 use crate::SampleLevel as Sl;
3179 const COMPONENTS: [&str; 4] = ["", "Green", "Blue", "Alpha"];
3180
3181 let (base_str, component_str) = match gather {
3182 Some(component) => ("Gather", COMPONENTS[component as usize]),
3183 None => ("Sample", ""),
3184 };
3185 let cmp_str = match depth_ref {
3186 Some(_) => "Cmp",
3187 None => "",
3188 };
3189 let level_str = match level {
3190 Sl::Zero if gather.is_none() => "LevelZero",
3191 Sl::Auto | Sl::Zero => "",
3192 Sl::Exact(_) => "Level",
3193 Sl::Bias(_) => "Bias",
3194 Sl::Gradient { .. } => "Grad",
3195 };
3196
3197 self.write_expr(module, image, func_ctx)?;
3198 write!(self.out, ".{base_str}{cmp_str}{component_str}{level_str}(")?;
3199 self.write_expr(module, sampler, func_ctx)?;
3200 write!(self.out, ", ")?;
3201 self.write_texture_coordinates(
3202 "float",
3203 coordinate,
3204 array_index,
3205 None,
3206 module,
3207 func_ctx,
3208 )?;
3209
3210 if let Some(depth_ref) = depth_ref {
3211 write!(self.out, ", ")?;
3212 self.write_expr(module, depth_ref, func_ctx)?;
3213 }
3214
3215 match level {
3216 Sl::Auto | Sl::Zero => {}
3217 Sl::Exact(expr) => {
3218 write!(self.out, ", ")?;
3219 self.write_expr(module, expr, func_ctx)?;
3220 }
3221 Sl::Bias(expr) => {
3222 write!(self.out, ", ")?;
3223 self.write_expr(module, expr, func_ctx)?;
3224 }
3225 Sl::Gradient { x, y } => {
3226 write!(self.out, ", ")?;
3227 self.write_expr(module, x, func_ctx)?;
3228 write!(self.out, ", ")?;
3229 self.write_expr(module, y, func_ctx)?;
3230 }
3231 }
3232
3233 if let Some(offset) = offset {
3234 write!(self.out, ", ")?;
3235 write!(self.out, "int2(")?; // work around https://github.com/microsoft/DirectXShaderCompiler/issues/5082#issuecomment-1540147807
3236 self.write_const_expression(module, offset, func_ctx.expressions)?;
3237 write!(self.out, ")")?;
3238 }
3239
3240 write!(self.out, ")")?;
3241 }
3242 Expression::ImageQuery { image, query } => {
3243 // use wrapped image query function
3244 if let TypeInner::Image {
3245 dim,
3246 arrayed,
3247 class,
3248 } = *func_ctx.resolve_type(image, &module.types)
3249 {
3250 let wrapped_image_query = WrappedImageQuery {
3251 dim,
3252 arrayed,
3253 class,
3254 query: query.into(),
3255 };
3256
3257 self.write_wrapped_image_query_function_name(wrapped_image_query)?;
3258 write!(self.out, "(")?;
3259 // Image always first param
3260 self.write_expr(module, image, func_ctx)?;
3261 if let crate::ImageQuery::Size { level: Some(level) } = query {
3262 write!(self.out, ", ")?;
3263 self.write_expr(module, level, func_ctx)?;
3264 }
3265 write!(self.out, ")")?;
3266 }
3267 }
3268 Expression::ImageLoad {
3269 image,
3270 coordinate,
3271 array_index,
3272 sample,
3273 level,
3274 } => self.write_image_load(
3275 &module,
3276 expr,
3277 func_ctx,
3278 image,
3279 coordinate,
3280 array_index,
3281 sample,
3282 level,
3283 )?,
3284 Expression::GlobalVariable(handle) => {
3285 let global_variable = &module.global_variables[handle];
3286 let ty = &module.types[global_variable.ty].inner;
3287
3288 // In the case of binding arrays of samplers, we need to not write anything
3289 // as the we are in the wrong position to fully write the expression.
3290 //
3291 // The entire writing is done by AccessIndex.
3292 let is_binding_array_of_samplers = match *ty {
3293 TypeInner::BindingArray { base, .. } => {
3294 let base_ty = &module.types[base].inner;
3295 matches!(*base_ty, TypeInner::Sampler { .. })
3296 }
3297 _ => false,
3298 };
3299
3300 let is_storage_space =
3301 matches!(global_variable.space, crate::AddressSpace::Storage { .. });
3302
3303 if !is_binding_array_of_samplers && !is_storage_space {
3304 let name = &self.names[&NameKey::GlobalVariable(handle)];
3305 write!(self.out, "{name}")?;
3306 }
3307 }
3308 Expression::LocalVariable(handle) => {
3309 write!(self.out, "{}", self.names[&func_ctx.name_key(handle)])?
3310 }
3311 Expression::Load { pointer } => {
3312 match func_ctx
3313 .resolve_type(pointer, &module.types)
3314 .pointer_space()
3315 {
3316 Some(crate::AddressSpace::Storage { .. }) => {
3317 let var_handle = self.fill_access_chain(module, pointer, func_ctx)?;
3318 let result_ty = func_ctx.info[expr].ty.clone();
3319 self.write_storage_load(module, var_handle, result_ty, func_ctx)?;
3320 }
3321 _ => {
3322 let mut close_paren = false;
3323
3324 // We cast the value loaded to a native HLSL floatCx2
3325 // in cases where it is of type:
3326 // - __matCx2 or
3327 // - a (possibly nested) array of __matCx2's
3328 if let Some(MatrixType {
3329 rows: crate::VectorSize::Bi,
3330 width: 4,
3331 ..
3332 }) = get_inner_matrix_of_struct_array_member(
3333 module, pointer, func_ctx, false,
3334 )
3335 .or_else(|| get_inner_matrix_of_global_uniform(module, pointer, func_ctx))
3336 {
3337 let mut resolved = func_ctx.resolve_type(pointer, &module.types);
3338 if let TypeInner::Pointer { base, .. } = *resolved {
3339 resolved = &module.types[base].inner;
3340 }
3341
3342 write!(self.out, "((")?;
3343 if let TypeInner::Array { base, size, .. } = *resolved {
3344 self.write_type(module, base)?;
3345 self.write_array_size(module, base, size)?;
3346 } else {
3347 self.write_value_type(module, resolved)?;
3348 }
3349 write!(self.out, ")")?;
3350 close_paren = true;
3351 }
3352
3353 self.write_expr(module, pointer, func_ctx)?;
3354
3355 if close_paren {
3356 write!(self.out, ")")?;
3357 }
3358 }
3359 }
3360 }
3361 Expression::Unary { op, expr } => {
3362 // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-operators#unary-operators
3363 let op_str = match op {
3364 crate::UnaryOperator::Negate => {
3365 match func_ctx.resolve_type(expr, &module.types).scalar() {
3366 Some(Scalar::I32) => NEG_FUNCTION,
3367 _ => "-",
3368 }
3369 }
3370 crate::UnaryOperator::LogicalNot => "!",
3371 crate::UnaryOperator::BitwiseNot => "~",
3372 };
3373 write!(self.out, "{op_str}(")?;
3374 self.write_expr(module, expr, func_ctx)?;
3375 write!(self.out, ")")?;
3376 }
3377 Expression::As {
3378 expr,
3379 kind,
3380 convert,
3381 } => {
3382 let inner = func_ctx.resolve_type(expr, &module.types);
3383 if inner.scalar_kind() == Some(ScalarKind::Float)
3384 && (kind == ScalarKind::Sint || kind == ScalarKind::Uint)
3385 && convert.is_some()
3386 {
3387 // Use helper functions for float to int casts in order to
3388 // avoid undefined behaviour when value is out of range for
3389 // the target type.
3390 let fun_name = match (kind, convert) {
3391 (ScalarKind::Sint, Some(4)) => F2I32_FUNCTION,
3392 (ScalarKind::Uint, Some(4)) => F2U32_FUNCTION,
3393 (ScalarKind::Sint, Some(8)) => F2I64_FUNCTION,
3394 (ScalarKind::Uint, Some(8)) => F2U64_FUNCTION,
3395 _ => unreachable!(),
3396 };
3397 write!(self.out, "{fun_name}(")?;
3398 self.write_expr(module, expr, func_ctx)?;
3399 write!(self.out, ")")?;
3400 } else {
3401 let close_paren = match convert {
3402 Some(dst_width) => {
3403 let scalar = Scalar {
3404 kind,
3405 width: dst_width,
3406 };
3407 match *inner {
3408 TypeInner::Vector { size, .. } => {
3409 write!(
3410 self.out,
3411 "{}{}(",
3412 scalar.to_hlsl_str()?,
3413 common::vector_size_str(size)
3414 )?;
3415 }
3416 TypeInner::Scalar(_) => {
3417 write!(self.out, "{}(", scalar.to_hlsl_str()?,)?;
3418 }
3419 TypeInner::Matrix { columns, rows, .. } => {
3420 write!(
3421 self.out,
3422 "{}{}x{}(",
3423 scalar.to_hlsl_str()?,
3424 common::vector_size_str(columns),
3425 common::vector_size_str(rows)
3426 )?;
3427 }
3428 _ => {
3429 return Err(Error::Unimplemented(format!(
3430 "write_expr expression::as {inner:?}"
3431 )));
3432 }
3433 };
3434 true
3435 }
3436 None => {
3437 if inner.scalar_width() == Some(8) {
3438 false
3439 } else {
3440 write!(self.out, "{}(", kind.to_hlsl_cast(),)?;
3441 true
3442 }
3443 }
3444 };
3445 self.write_expr(module, expr, func_ctx)?;
3446 if close_paren {
3447 write!(self.out, ")")?;
3448 }
3449 }
3450 }
3451 Expression::Math {
3452 fun,
3453 arg,
3454 arg1,
3455 arg2,
3456 arg3,
3457 } => {
3458 use crate::MathFunction as Mf;
3459
3460 enum Function {
3461 Asincosh { is_sin: bool },
3462 Atanh,
3463 Pack2x16float,
3464 Pack2x16snorm,
3465 Pack2x16unorm,
3466 Pack4x8snorm,
3467 Pack4x8unorm,
3468 Pack4xI8,
3469 Pack4xU8,
3470 Pack4xI8Clamp,
3471 Pack4xU8Clamp,
3472 Unpack2x16float,
3473 Unpack2x16snorm,
3474 Unpack2x16unorm,
3475 Unpack4x8snorm,
3476 Unpack4x8unorm,
3477 Unpack4xI8,
3478 Unpack4xU8,
3479 Dot4I8Packed,
3480 Dot4U8Packed,
3481 QuantizeToF16,
3482 Regular(&'static str),
3483 MissingIntOverload(&'static str),
3484 MissingIntReturnType(&'static str),
3485 CountTrailingZeros,
3486 CountLeadingZeros,
3487 }
3488
3489 let fun = match fun {
3490 // comparison
3491 Mf::Abs => match func_ctx.resolve_type(arg, &module.types).scalar() {
3492 Some(Scalar::I32) => Function::Regular(ABS_FUNCTION),
3493 _ => Function::Regular("abs"),
3494 },
3495 Mf::Min => Function::Regular("min"),
3496 Mf::Max => Function::Regular("max"),
3497 Mf::Clamp => Function::Regular("clamp"),
3498 Mf::Saturate => Function::Regular("saturate"),
3499 // trigonometry
3500 Mf::Cos => Function::Regular("cos"),
3501 Mf::Cosh => Function::Regular("cosh"),
3502 Mf::Sin => Function::Regular("sin"),
3503 Mf::Sinh => Function::Regular("sinh"),
3504 Mf::Tan => Function::Regular("tan"),
3505 Mf::Tanh => Function::Regular("tanh"),
3506 Mf::Acos => Function::Regular("acos"),
3507 Mf::Asin => Function::Regular("asin"),
3508 Mf::Atan => Function::Regular("atan"),
3509 Mf::Atan2 => Function::Regular("atan2"),
3510 Mf::Asinh => Function::Asincosh { is_sin: true },
3511 Mf::Acosh => Function::Asincosh { is_sin: false },
3512 Mf::Atanh => Function::Atanh,
3513 Mf::Radians => Function::Regular("radians"),
3514 Mf::Degrees => Function::Regular("degrees"),
3515 // decomposition
3516 Mf::Ceil => Function::Regular("ceil"),
3517 Mf::Floor => Function::Regular("floor"),
3518 Mf::Round => Function::Regular("round"),
3519 Mf::Fract => Function::Regular("frac"),
3520 Mf::Trunc => Function::Regular("trunc"),
3521 Mf::Modf => Function::Regular(MODF_FUNCTION),
3522 Mf::Frexp => Function::Regular(FREXP_FUNCTION),
3523 Mf::Ldexp => Function::Regular("ldexp"),
3524 // exponent
3525 Mf::Exp => Function::Regular("exp"),
3526 Mf::Exp2 => Function::Regular("exp2"),
3527 Mf::Log => Function::Regular("log"),
3528 Mf::Log2 => Function::Regular("log2"),
3529 Mf::Pow => Function::Regular("pow"),
3530 // geometry
3531 Mf::Dot => Function::Regular("dot"),
3532 Mf::Dot4I8Packed => Function::Dot4I8Packed,
3533 Mf::Dot4U8Packed => Function::Dot4U8Packed,
3534 //Mf::Outer => ,
3535 Mf::Cross => Function::Regular("cross"),
3536 Mf::Distance => Function::Regular("distance"),
3537 Mf::Length => Function::Regular("length"),
3538 Mf::Normalize => Function::Regular("normalize"),
3539 Mf::FaceForward => Function::Regular("faceforward"),
3540 Mf::Reflect => Function::Regular("reflect"),
3541 Mf::Refract => Function::Regular("refract"),
3542 // computational
3543 Mf::Sign => Function::Regular("sign"),
3544 Mf::Fma => Function::Regular("mad"),
3545 Mf::Mix => Function::Regular("lerp"),
3546 Mf::Step => Function::Regular("step"),
3547 Mf::SmoothStep => Function::Regular("smoothstep"),
3548 Mf::Sqrt => Function::Regular("sqrt"),
3549 Mf::InverseSqrt => Function::Regular("rsqrt"),
3550 //Mf::Inverse =>,
3551 Mf::Transpose => Function::Regular("transpose"),
3552 Mf::Determinant => Function::Regular("determinant"),
3553 Mf::QuantizeToF16 => Function::QuantizeToF16,
3554 // bits
3555 Mf::CountTrailingZeros => Function::CountTrailingZeros,
3556 Mf::CountLeadingZeros => Function::CountLeadingZeros,
3557 Mf::CountOneBits => Function::MissingIntOverload("countbits"),
3558 Mf::ReverseBits => Function::MissingIntOverload("reversebits"),
3559 Mf::FirstTrailingBit => Function::MissingIntReturnType("firstbitlow"),
3560 Mf::FirstLeadingBit => Function::MissingIntReturnType("firstbithigh"),
3561 Mf::ExtractBits => Function::Regular(EXTRACT_BITS_FUNCTION),
3562 Mf::InsertBits => Function::Regular(INSERT_BITS_FUNCTION),
3563 // Data Packing
3564 Mf::Pack2x16float => Function::Pack2x16float,
3565 Mf::Pack2x16snorm => Function::Pack2x16snorm,
3566 Mf::Pack2x16unorm => Function::Pack2x16unorm,
3567 Mf::Pack4x8snorm => Function::Pack4x8snorm,
3568 Mf::Pack4x8unorm => Function::Pack4x8unorm,
3569 Mf::Pack4xI8 => Function::Pack4xI8,
3570 Mf::Pack4xU8 => Function::Pack4xU8,
3571 Mf::Pack4xI8Clamp => Function::Pack4xI8Clamp,
3572 Mf::Pack4xU8Clamp => Function::Pack4xU8Clamp,
3573 // Data Unpacking
3574 Mf::Unpack2x16float => Function::Unpack2x16float,
3575 Mf::Unpack2x16snorm => Function::Unpack2x16snorm,
3576 Mf::Unpack2x16unorm => Function::Unpack2x16unorm,
3577 Mf::Unpack4x8snorm => Function::Unpack4x8snorm,
3578 Mf::Unpack4x8unorm => Function::Unpack4x8unorm,
3579 Mf::Unpack4xI8 => Function::Unpack4xI8,
3580 Mf::Unpack4xU8 => Function::Unpack4xU8,
3581 _ => return Err(Error::Unimplemented(format!("write_expr_math {fun:?}"))),
3582 };
3583
3584 match fun {
3585 Function::Asincosh { is_sin } => {
3586 write!(self.out, "log(")?;
3587 self.write_expr(module, arg, func_ctx)?;
3588 write!(self.out, " + sqrt(")?;
3589 self.write_expr(module, arg, func_ctx)?;
3590 write!(self.out, " * ")?;
3591 self.write_expr(module, arg, func_ctx)?;
3592 match is_sin {
3593 true => write!(self.out, " + 1.0))")?,
3594 false => write!(self.out, " - 1.0))")?,
3595 }
3596 }
3597 Function::Atanh => {
3598 write!(self.out, "0.5 * log((1.0 + ")?;
3599 self.write_expr(module, arg, func_ctx)?;
3600 write!(self.out, ") / (1.0 - ")?;
3601 self.write_expr(module, arg, func_ctx)?;
3602 write!(self.out, "))")?;
3603 }
3604 Function::Pack2x16float => {
3605 write!(self.out, "(f32tof16(")?;
3606 self.write_expr(module, arg, func_ctx)?;
3607 write!(self.out, "[0]) | f32tof16(")?;
3608 self.write_expr(module, arg, func_ctx)?;
3609 write!(self.out, "[1]) << 16)")?;
3610 }
3611 Function::Pack2x16snorm => {
3612 let scale = 32767;
3613
3614 write!(self.out, "uint((int(round(clamp(")?;
3615 self.write_expr(module, arg, func_ctx)?;
3616 write!(
3617 self.out,
3618 "[0], -1.0, 1.0) * {scale}.0)) & 0xFFFF) | ((int(round(clamp("
3619 )?;
3620 self.write_expr(module, arg, func_ctx)?;
3621 write!(self.out, "[1], -1.0, 1.0) * {scale}.0)) & 0xFFFF) << 16))",)?;
3622 }
3623 Function::Pack2x16unorm => {
3624 let scale = 65535;
3625
3626 write!(self.out, "(uint(round(clamp(")?;
3627 self.write_expr(module, arg, func_ctx)?;
3628 write!(self.out, "[0], 0.0, 1.0) * {scale}.0)) | uint(round(clamp(")?;
3629 self.write_expr(module, arg, func_ctx)?;
3630 write!(self.out, "[1], 0.0, 1.0) * {scale}.0)) << 16)")?;
3631 }
3632 Function::Pack4x8snorm => {
3633 let scale = 127;
3634
3635 write!(self.out, "uint((int(round(clamp(")?;
3636 self.write_expr(module, arg, func_ctx)?;
3637 write!(
3638 self.out,
3639 "[0], -1.0, 1.0) * {scale}.0)) & 0xFF) | ((int(round(clamp("
3640 )?;
3641 self.write_expr(module, arg, func_ctx)?;
3642 write!(
3643 self.out,
3644 "[1], -1.0, 1.0) * {scale}.0)) & 0xFF) << 8) | ((int(round(clamp("
3645 )?;
3646 self.write_expr(module, arg, func_ctx)?;
3647 write!(
3648 self.out,
3649 "[2], -1.0, 1.0) * {scale}.0)) & 0xFF) << 16) | ((int(round(clamp("
3650 )?;
3651 self.write_expr(module, arg, func_ctx)?;
3652 write!(self.out, "[3], -1.0, 1.0) * {scale}.0)) & 0xFF) << 24))",)?;
3653 }
3654 Function::Pack4x8unorm => {
3655 let scale = 255;
3656
3657 write!(self.out, "(uint(round(clamp(")?;
3658 self.write_expr(module, arg, func_ctx)?;
3659 write!(self.out, "[0], 0.0, 1.0) * {scale}.0)) | uint(round(clamp(")?;
3660 self.write_expr(module, arg, func_ctx)?;
3661 write!(
3662 self.out,
3663 "[1], 0.0, 1.0) * {scale}.0)) << 8 | uint(round(clamp("
3664 )?;
3665 self.write_expr(module, arg, func_ctx)?;
3666 write!(
3667 self.out,
3668 "[2], 0.0, 1.0) * {scale}.0)) << 16 | uint(round(clamp("
3669 )?;
3670 self.write_expr(module, arg, func_ctx)?;
3671 write!(self.out, "[3], 0.0, 1.0) * {scale}.0)) << 24)")?;
3672 }
3673 fun @ (Function::Pack4xI8
3674 | Function::Pack4xU8
3675 | Function::Pack4xI8Clamp
3676 | Function::Pack4xU8Clamp) => {
3677 let was_signed =
3678 matches!(fun, Function::Pack4xI8 | Function::Pack4xI8Clamp);
3679 let clamp_bounds = match fun {
3680 Function::Pack4xI8Clamp => Some(("-128", "127")),
3681 Function::Pack4xU8Clamp => Some(("0", "255")),
3682 _ => None,
3683 };
3684 if was_signed {
3685 write!(self.out, "uint(")?;
3686 }
3687 let write_arg = |this: &mut Self| -> BackendResult {
3688 if let Some((min, max)) = clamp_bounds {
3689 write!(this.out, "clamp(")?;
3690 this.write_expr(module, arg, func_ctx)?;
3691 write!(this.out, ", {min}, {max})")?;
3692 } else {
3693 this.write_expr(module, arg, func_ctx)?;
3694 }
3695 Ok(())
3696 };
3697 write!(self.out, "(")?;
3698 write_arg(self)?;
3699 write!(self.out, "[0] & 0xFF) | ((")?;
3700 write_arg(self)?;
3701 write!(self.out, "[1] & 0xFF) << 8) | ((")?;
3702 write_arg(self)?;
3703 write!(self.out, "[2] & 0xFF) << 16) | ((")?;
3704 write_arg(self)?;
3705 write!(self.out, "[3] & 0xFF) << 24)")?;
3706 if was_signed {
3707 write!(self.out, ")")?;
3708 }
3709 }
3710
3711 Function::Unpack2x16float => {
3712 write!(self.out, "float2(f16tof32(")?;
3713 self.write_expr(module, arg, func_ctx)?;
3714 write!(self.out, "), f16tof32((")?;
3715 self.write_expr(module, arg, func_ctx)?;
3716 write!(self.out, ") >> 16))")?;
3717 }
3718 Function::Unpack2x16snorm => {
3719 let scale = 32767;
3720
3721 write!(self.out, "(float2(int2(")?;
3722 self.write_expr(module, arg, func_ctx)?;
3723 write!(self.out, " << 16, ")?;
3724 self.write_expr(module, arg, func_ctx)?;
3725 write!(self.out, ") >> 16) / {scale}.0)")?;
3726 }
3727 Function::Unpack2x16unorm => {
3728 let scale = 65535;
3729
3730 write!(self.out, "(float2(")?;
3731 self.write_expr(module, arg, func_ctx)?;
3732 write!(self.out, " & 0xFFFF, ")?;
3733 self.write_expr(module, arg, func_ctx)?;
3734 write!(self.out, " >> 16) / {scale}.0)")?;
3735 }
3736 Function::Unpack4x8snorm => {
3737 let scale = 127;
3738
3739 write!(self.out, "(float4(int4(")?;
3740 self.write_expr(module, arg, func_ctx)?;
3741 write!(self.out, " << 24, ")?;
3742 self.write_expr(module, arg, func_ctx)?;
3743 write!(self.out, " << 16, ")?;
3744 self.write_expr(module, arg, func_ctx)?;
3745 write!(self.out, " << 8, ")?;
3746 self.write_expr(module, arg, func_ctx)?;
3747 write!(self.out, ") >> 24) / {scale}.0)")?;
3748 }
3749 Function::Unpack4x8unorm => {
3750 let scale = 255;
3751
3752 write!(self.out, "(float4(")?;
3753 self.write_expr(module, arg, func_ctx)?;
3754 write!(self.out, " & 0xFF, ")?;
3755 self.write_expr(module, arg, func_ctx)?;
3756 write!(self.out, " >> 8 & 0xFF, ")?;
3757 self.write_expr(module, arg, func_ctx)?;
3758 write!(self.out, " >> 16 & 0xFF, ")?;
3759 self.write_expr(module, arg, func_ctx)?;
3760 write!(self.out, " >> 24) / {scale}.0)")?;
3761 }
3762 fun @ (Function::Unpack4xI8 | Function::Unpack4xU8) => {
3763 write!(self.out, "(")?;
3764 if matches!(fun, Function::Unpack4xU8) {
3765 write!(self.out, "u")?;
3766 }
3767 write!(self.out, "int4(")?;
3768 self.write_expr(module, arg, func_ctx)?;
3769 write!(self.out, ", ")?;
3770 self.write_expr(module, arg, func_ctx)?;
3771 write!(self.out, " >> 8, ")?;
3772 self.write_expr(module, arg, func_ctx)?;
3773 write!(self.out, " >> 16, ")?;
3774 self.write_expr(module, arg, func_ctx)?;
3775 write!(self.out, " >> 24) << 24 >> 24)")?;
3776 }
3777 fun @ (Function::Dot4I8Packed | Function::Dot4U8Packed) => {
3778 let arg1 = arg1.unwrap();
3779
3780 if self.options.shader_model >= ShaderModel::V6_4 {
3781 // Intrinsics `dot4add_{i, u}8packed` are available in SM 6.4 and later.
3782 let function_name = match fun {
3783 Function::Dot4I8Packed => "dot4add_i8packed",
3784 Function::Dot4U8Packed => "dot4add_u8packed",
3785 _ => unreachable!(),
3786 };
3787 write!(self.out, "{function_name}(")?;
3788 self.write_expr(module, arg, func_ctx)?;
3789 write!(self.out, ", ")?;
3790 self.write_expr(module, arg1, func_ctx)?;
3791 write!(self.out, ", 0)")?;
3792 } else {
3793 // Fall back to a polyfill as `dot4add_u8packed` is not available.
3794 write!(self.out, "dot(")?;
3795
3796 if matches!(fun, Function::Dot4U8Packed) {
3797 write!(self.out, "u")?;
3798 }
3799 write!(self.out, "int4(")?;
3800 self.write_expr(module, arg, func_ctx)?;
3801 write!(self.out, ", ")?;
3802 self.write_expr(module, arg, func_ctx)?;
3803 write!(self.out, " >> 8, ")?;
3804 self.write_expr(module, arg, func_ctx)?;
3805 write!(self.out, " >> 16, ")?;
3806 self.write_expr(module, arg, func_ctx)?;
3807 write!(self.out, " >> 24) << 24 >> 24, ")?;
3808
3809 if matches!(fun, Function::Dot4U8Packed) {
3810 write!(self.out, "u")?;
3811 }
3812 write!(self.out, "int4(")?;
3813 self.write_expr(module, arg1, func_ctx)?;
3814 write!(self.out, ", ")?;
3815 self.write_expr(module, arg1, func_ctx)?;
3816 write!(self.out, " >> 8, ")?;
3817 self.write_expr(module, arg1, func_ctx)?;
3818 write!(self.out, " >> 16, ")?;
3819 self.write_expr(module, arg1, func_ctx)?;
3820 write!(self.out, " >> 24) << 24 >> 24)")?;
3821 }
3822 }
3823 Function::QuantizeToF16 => {
3824 write!(self.out, "f16tof32(f32tof16(")?;
3825 self.write_expr(module, arg, func_ctx)?;
3826 write!(self.out, "))")?;
3827 }
3828 Function::Regular(fun_name) => {
3829 write!(self.out, "{fun_name}(")?;
3830 self.write_expr(module, arg, func_ctx)?;
3831 if let Some(arg) = arg1 {
3832 write!(self.out, ", ")?;
3833 self.write_expr(module, arg, func_ctx)?;
3834 }
3835 if let Some(arg) = arg2 {
3836 write!(self.out, ", ")?;
3837 self.write_expr(module, arg, func_ctx)?;
3838 }
3839 if let Some(arg) = arg3 {
3840 write!(self.out, ", ")?;
3841 self.write_expr(module, arg, func_ctx)?;
3842 }
3843 write!(self.out, ")")?
3844 }
3845 // These overloads are only missing on FXC, so this is only needed for 32bit types,
3846 // as non-32bit types are DXC only.
3847 Function::MissingIntOverload(fun_name) => {
3848 let scalar_kind = func_ctx.resolve_type(arg, &module.types).scalar();
3849 if let Some(Scalar::I32) = scalar_kind {
3850 write!(self.out, "asint({fun_name}(asuint(")?;
3851 self.write_expr(module, arg, func_ctx)?;
3852 write!(self.out, ")))")?;
3853 } else {
3854 write!(self.out, "{fun_name}(")?;
3855 self.write_expr(module, arg, func_ctx)?;
3856 write!(self.out, ")")?;
3857 }
3858 }
3859 // These overloads are only missing on FXC, so this is only needed for 32bit types,
3860 // as non-32bit types are DXC only.
3861 Function::MissingIntReturnType(fun_name) => {
3862 let scalar_kind = func_ctx.resolve_type(arg, &module.types).scalar();
3863 if let Some(Scalar::I32) = scalar_kind {
3864 write!(self.out, "asint({fun_name}(")?;
3865 self.write_expr(module, arg, func_ctx)?;
3866 write!(self.out, "))")?;
3867 } else {
3868 write!(self.out, "{fun_name}(")?;
3869 self.write_expr(module, arg, func_ctx)?;
3870 write!(self.out, ")")?;
3871 }
3872 }
3873 Function::CountTrailingZeros => {
3874 match *func_ctx.resolve_type(arg, &module.types) {
3875 TypeInner::Vector { size, scalar } => {
3876 let s = match size {
3877 crate::VectorSize::Bi => ".xx",
3878 crate::VectorSize::Tri => ".xxx",
3879 crate::VectorSize::Quad => ".xxxx",
3880 };
3881
3882 let scalar_width_bits = scalar.width * 8;
3883
3884 if scalar.kind == ScalarKind::Uint || scalar.width != 4 {
3885 write!(
3886 self.out,
3887 "min(({scalar_width_bits}u){s}, firstbitlow("
3888 )?;
3889 self.write_expr(module, arg, func_ctx)?;
3890 write!(self.out, "))")?;
3891 } else {
3892 // This is only needed for the FXC path, on 32bit signed integers.
3893 write!(
3894 self.out,
3895 "asint(min(({scalar_width_bits}u){s}, firstbitlow("
3896 )?;
3897 self.write_expr(module, arg, func_ctx)?;
3898 write!(self.out, ")))")?;
3899 }
3900 }
3901 TypeInner::Scalar(scalar) => {
3902 let scalar_width_bits = scalar.width * 8;
3903
3904 if scalar.kind == ScalarKind::Uint || scalar.width != 4 {
3905 write!(self.out, "min({scalar_width_bits}u, firstbitlow(")?;
3906 self.write_expr(module, arg, func_ctx)?;
3907 write!(self.out, "))")?;
3908 } else {
3909 // This is only needed for the FXC path, on 32bit signed integers.
3910 write!(
3911 self.out,
3912 "asint(min({scalar_width_bits}u, firstbitlow("
3913 )?;
3914 self.write_expr(module, arg, func_ctx)?;
3915 write!(self.out, ")))")?;
3916 }
3917 }
3918 _ => unreachable!(),
3919 }
3920
3921 return Ok(());
3922 }
3923 Function::CountLeadingZeros => {
3924 match *func_ctx.resolve_type(arg, &module.types) {
3925 TypeInner::Vector { size, scalar } => {
3926 let s = match size {
3927 crate::VectorSize::Bi => ".xx",
3928 crate::VectorSize::Tri => ".xxx",
3929 crate::VectorSize::Quad => ".xxxx",
3930 };
3931
3932 // scalar width - 1
3933 let constant = scalar.width * 8 - 1;
3934
3935 if scalar.kind == ScalarKind::Uint {
3936 write!(self.out, "(({constant}u){s} - firstbithigh(")?;
3937 self.write_expr(module, arg, func_ctx)?;
3938 write!(self.out, "))")?;
3939 } else {
3940 let conversion_func = match scalar.width {
3941 4 => "asint",
3942 _ => "",
3943 };
3944 write!(self.out, "(")?;
3945 self.write_expr(module, arg, func_ctx)?;
3946 write!(
3947 self.out,
3948 " < (0){s} ? (0){s} : ({constant}){s} - {conversion_func}(firstbithigh("
3949 )?;
3950 self.write_expr(module, arg, func_ctx)?;
3951 write!(self.out, ")))")?;
3952 }
3953 }
3954 TypeInner::Scalar(scalar) => {
3955 // scalar width - 1
3956 let constant = scalar.width * 8 - 1;
3957
3958 if let ScalarKind::Uint = scalar.kind {
3959 write!(self.out, "({constant}u - firstbithigh(")?;
3960 self.write_expr(module, arg, func_ctx)?;
3961 write!(self.out, "))")?;
3962 } else {
3963 let conversion_func = match scalar.width {
3964 4 => "asint",
3965 _ => "",
3966 };
3967 write!(self.out, "(")?;
3968 self.write_expr(module, arg, func_ctx)?;
3969 write!(
3970 self.out,
3971 " < 0 ? 0 : {constant} - {conversion_func}(firstbithigh("
3972 )?;
3973 self.write_expr(module, arg, func_ctx)?;
3974 write!(self.out, ")))")?;
3975 }
3976 }
3977 _ => unreachable!(),
3978 }
3979
3980 return Ok(());
3981 }
3982 }
3983 }
3984 Expression::Swizzle {
3985 size,
3986 vector,
3987 pattern,
3988 } => {
3989 self.write_expr(module, vector, func_ctx)?;
3990 write!(self.out, ".")?;
3991 for &sc in pattern[..size as usize].iter() {
3992 self.out.write_char(back::COMPONENTS[sc as usize])?;
3993 }
3994 }
3995 Expression::ArrayLength(expr) => {
3996 let var_handle = match func_ctx.expressions[expr] {
3997 Expression::AccessIndex { base, index: _ } => {
3998 match func_ctx.expressions[base] {
3999 Expression::GlobalVariable(handle) => handle,
4000 _ => unreachable!(),
4001 }
4002 }
4003 Expression::GlobalVariable(handle) => handle,
4004 _ => unreachable!(),
4005 };
4006
4007 let var = &module.global_variables[var_handle];
4008 let (offset, stride) = match module.types[var.ty].inner {
4009 TypeInner::Array { stride, .. } => (0, stride),
4010 TypeInner::Struct { ref members, .. } => {
4011 let last = members.last().unwrap();
4012 let stride = match module.types[last.ty].inner {
4013 TypeInner::Array { stride, .. } => stride,
4014 _ => unreachable!(),
4015 };
4016 (last.offset, stride)
4017 }
4018 _ => unreachable!(),
4019 };
4020
4021 let storage_access = match var.space {
4022 crate::AddressSpace::Storage { access } => access,
4023 _ => crate::StorageAccess::default(),
4024 };
4025 let wrapped_array_length = WrappedArrayLength {
4026 writable: storage_access.contains(crate::StorageAccess::STORE),
4027 };
4028
4029 write!(self.out, "((")?;
4030 self.write_wrapped_array_length_function_name(wrapped_array_length)?;
4031 let var_name = &self.names[&NameKey::GlobalVariable(var_handle)];
4032 write!(self.out, "({var_name}) - {offset}) / {stride})")?
4033 }
4034 Expression::Derivative { axis, ctrl, expr } => {
4035 use crate::{DerivativeAxis as Axis, DerivativeControl as Ctrl};
4036 if axis == Axis::Width && (ctrl == Ctrl::Coarse || ctrl == Ctrl::Fine) {
4037 let tail = match ctrl {
4038 Ctrl::Coarse => "coarse",
4039 Ctrl::Fine => "fine",
4040 Ctrl::None => unreachable!(),
4041 };
4042 write!(self.out, "abs(ddx_{tail}(")?;
4043 self.write_expr(module, expr, func_ctx)?;
4044 write!(self.out, ")) + abs(ddy_{tail}(")?;
4045 self.write_expr(module, expr, func_ctx)?;
4046 write!(self.out, "))")?
4047 } else {
4048 let fun_str = match (axis, ctrl) {
4049 (Axis::X, Ctrl::Coarse) => "ddx_coarse",
4050 (Axis::X, Ctrl::Fine) => "ddx_fine",
4051 (Axis::X, Ctrl::None) => "ddx",
4052 (Axis::Y, Ctrl::Coarse) => "ddy_coarse",
4053 (Axis::Y, Ctrl::Fine) => "ddy_fine",
4054 (Axis::Y, Ctrl::None) => "ddy",
4055 (Axis::Width, Ctrl::Coarse | Ctrl::Fine) => unreachable!(),
4056 (Axis::Width, Ctrl::None) => "fwidth",
4057 };
4058 write!(self.out, "{fun_str}(")?;
4059 self.write_expr(module, expr, func_ctx)?;
4060 write!(self.out, ")")?
4061 }
4062 }
4063 Expression::Relational { fun, argument } => {
4064 use crate::RelationalFunction as Rf;
4065
4066 let fun_str = match fun {
4067 Rf::All => "all",
4068 Rf::Any => "any",
4069 Rf::IsNan => "isnan",
4070 Rf::IsInf => "isinf",
4071 };
4072 write!(self.out, "{fun_str}(")?;
4073 self.write_expr(module, argument, func_ctx)?;
4074 write!(self.out, ")")?
4075 }
4076 Expression::Select {
4077 condition,
4078 accept,
4079 reject,
4080 } => {
4081 write!(self.out, "(")?;
4082 self.write_expr(module, condition, func_ctx)?;
4083 write!(self.out, " ? ")?;
4084 self.write_expr(module, accept, func_ctx)?;
4085 write!(self.out, " : ")?;
4086 self.write_expr(module, reject, func_ctx)?;
4087 write!(self.out, ")")?
4088 }
4089 Expression::RayQueryGetIntersection { query, committed } => {
4090 if committed {
4091 write!(self.out, "GetCommittedIntersection(")?;
4092 self.write_expr(module, query, func_ctx)?;
4093 write!(self.out, ")")?;
4094 } else {
4095 write!(self.out, "GetCandidateIntersection(")?;
4096 self.write_expr(module, query, func_ctx)?;
4097 write!(self.out, ")")?;
4098 }
4099 }
4100 // Not supported yet
4101 Expression::RayQueryVertexPositions { .. } => unreachable!(),
4102 // Nothing to do here, since call expression already cached
4103 Expression::CallResult(_)
4104 | Expression::AtomicResult { .. }
4105 | Expression::WorkGroupUniformLoadResult { .. }
4106 | Expression::RayQueryProceedResult
4107 | Expression::SubgroupBallotResult
4108 | Expression::SubgroupOperationResult { .. } => {}
4109 }
4110
4111 if !closing_bracket.is_empty() {
4112 write!(self.out, "{closing_bracket}")?;
4113 }
4114 Ok(())
4115 }
4116
4117 #[allow(clippy::too_many_arguments)]
4118 fn write_image_load(
4119 &mut self,
4120 module: &&Module,
4121 expr: Handle<crate::Expression>,
4122 func_ctx: &back::FunctionCtx,
4123 image: Handle<crate::Expression>,
4124 coordinate: Handle<crate::Expression>,
4125 array_index: Option<Handle<crate::Expression>>,
4126 sample: Option<Handle<crate::Expression>>,
4127 level: Option<Handle<crate::Expression>>,
4128 ) -> Result<(), Error> {
4129 let mut wrapping_type = None;
4130 match *func_ctx.resolve_type(image, &module.types) {
4131 TypeInner::Image {
4132 class: crate::ImageClass::Storage { format, .. },
4133 ..
4134 } => {
4135 if format.single_component() {
4136 wrapping_type = Some(Scalar::from(format));
4137 }
4138 }
4139 _ => {}
4140 }
4141 if let Some(scalar) = wrapping_type {
4142 write!(
4143 self.out,
4144 "{}{}(",
4145 help::IMAGE_STORAGE_LOAD_SCALAR_WRAPPER,
4146 scalar.to_hlsl_str()?
4147 )?;
4148 }
4149 // https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-to-load
4150 self.write_expr(module, image, func_ctx)?;
4151 write!(self.out, ".Load(")?;
4152
4153 self.write_texture_coordinates("int", coordinate, array_index, level, module, func_ctx)?;
4154
4155 if let Some(sample) = sample {
4156 write!(self.out, ", ")?;
4157 self.write_expr(module, sample, func_ctx)?;
4158 }
4159
4160 // close bracket for Load function
4161 write!(self.out, ")")?;
4162
4163 if wrapping_type.is_some() {
4164 write!(self.out, ")")?;
4165 }
4166
4167 // return x component if return type is scalar
4168 if let TypeInner::Scalar(_) = *func_ctx.resolve_type(expr, &module.types) {
4169 write!(self.out, ".x")?;
4170 }
4171 Ok(())
4172 }
4173
4174 /// Find the [`BindingArraySamplerInfo`] from an expression so that such an access
4175 /// can be generated later.
4176 fn sampler_binding_array_info_from_expression(
4177 &mut self,
4178 module: &Module,
4179 func_ctx: &back::FunctionCtx<'_>,
4180 base: Handle<crate::Expression>,
4181 resolved: &TypeInner,
4182 ) -> Option<BindingArraySamplerInfo> {
4183 if let TypeInner::BindingArray {
4184 base: base_ty_handle,
4185 ..
4186 } = *resolved
4187 {
4188 let base_ty = &module.types[base_ty_handle].inner;
4189 if let TypeInner::Sampler { comparison, .. } = *base_ty {
4190 let base = &func_ctx.expressions[base];
4191
4192 if let crate::Expression::GlobalVariable(handle) = *base {
4193 let variable = &module.global_variables[handle];
4194
4195 let sampler_heap_name = match comparison {
4196 true => COMPARISON_SAMPLER_HEAP_VAR,
4197 false => SAMPLER_HEAP_VAR,
4198 };
4199
4200 return Some(BindingArraySamplerInfo {
4201 sampler_heap_name,
4202 sampler_index_buffer_name: self
4203 .wrapped
4204 .sampler_index_buffers
4205 .get(&super::SamplerIndexBufferKey {
4206 group: variable.binding.unwrap().group,
4207 })
4208 .unwrap()
4209 .clone(),
4210 binding_array_base_index_name: self.names[&NameKey::GlobalVariable(handle)]
4211 .clone(),
4212 });
4213 }
4214 }
4215 }
4216
4217 None
4218 }
4219
4220 fn write_named_expr(
4221 &mut self,
4222 module: &Module,
4223 handle: Handle<crate::Expression>,
4224 name: String,
4225 // The expression which is being named.
4226 // Generally, this is the same as handle, except in WorkGroupUniformLoad
4227 named: Handle<crate::Expression>,
4228 ctx: &back::FunctionCtx,
4229 ) -> BackendResult {
4230 match ctx.info[named].ty {
4231 proc::TypeResolution::Handle(ty_handle) => match module.types[ty_handle].inner {
4232 TypeInner::Struct { .. } => {
4233 let ty_name = &self.names[&NameKey::Type(ty_handle)];
4234 write!(self.out, "{ty_name}")?;
4235 }
4236 _ => {
4237 self.write_type(module, ty_handle)?;
4238 }
4239 },
4240 proc::TypeResolution::Value(ref inner) => {
4241 self.write_value_type(module, inner)?;
4242 }
4243 }
4244
4245 let resolved = ctx.resolve_type(named, &module.types);
4246
4247 write!(self.out, " {name}")?;
4248 // If rhs is a array type, we should write array size
4249 if let TypeInner::Array { base, size, .. } = *resolved {
4250 self.write_array_size(module, base, size)?;
4251 }
4252 write!(self.out, " = ")?;
4253 self.write_expr(module, handle, ctx)?;
4254 writeln!(self.out, ";")?;
4255 self.named_expressions.insert(named, name);
4256
4257 Ok(())
4258 }
4259
4260 /// Helper function that write default zero initialization
4261 pub(super) fn write_default_init(
4262 &mut self,
4263 module: &Module,
4264 ty: Handle<crate::Type>,
4265 ) -> BackendResult {
4266 write!(self.out, "(")?;
4267 self.write_type(module, ty)?;
4268 if let TypeInner::Array { base, size, .. } = module.types[ty].inner {
4269 self.write_array_size(module, base, size)?;
4270 }
4271 write!(self.out, ")0")?;
4272 Ok(())
4273 }
4274
4275 fn write_barrier(&mut self, barrier: crate::Barrier, level: back::Level) -> BackendResult {
4276 if barrier.contains(crate::Barrier::STORAGE) {
4277 writeln!(self.out, "{level}DeviceMemoryBarrierWithGroupSync();")?;
4278 }
4279 if barrier.contains(crate::Barrier::WORK_GROUP) {
4280 writeln!(self.out, "{level}GroupMemoryBarrierWithGroupSync();")?;
4281 }
4282 if barrier.contains(crate::Barrier::SUB_GROUP) {
4283 // Does not exist in DirectX
4284 }
4285 if barrier.contains(crate::Barrier::TEXTURE) {
4286 writeln!(self.out, "{level}DeviceMemoryBarrierWithGroupSync();")?;
4287 }
4288 Ok(())
4289 }
4290 }
4291
4292 pub(super) struct MatrixType {
4293 pub(super) columns: crate::VectorSize,
4294 pub(super) rows: crate::VectorSize,
4295 pub(super) width: crate::Bytes,
4296 }
4297
4298 pub(super) fn get_inner_matrix_data(
4299 module: &Module,
4300 handle: Handle<crate::Type>,
4301 ) -> Option<MatrixType> {
4302 match module.types[handle].inner {
4303 TypeInner::Matrix {
4304 columns,
4305 rows,
4306 scalar,
4307 } => Some(MatrixType {
4308 columns,
4309 rows,
4310 width: scalar.width,
4311 }),
4312 TypeInner::Array { base, .. } => get_inner_matrix_data(module, base),
4313 _ => None,
4314 }
4315 }
4316
4317 /// Returns the matrix data if the access chain starting at `base`:
4318 /// - starts with an expression with resolved type of [`TypeInner::Matrix`] if `direct = true`
4319 /// - contains one or more expressions with resolved type of [`TypeInner::Array`] of [`TypeInner::Matrix`]
4320 /// - ends at an expression with resolved type of [`TypeInner::Struct`]
4321 pub(super) fn get_inner_matrix_of_struct_array_member(
4322 module: &Module,
4323 base: Handle<crate::Expression>,
4324 func_ctx: &back::FunctionCtx<'_>,
4325 direct: bool,
4326 ) -> Option<MatrixType> {
4327 let mut mat_data = None;
4328 let mut array_base = None;
4329
4330 let mut current_base = base;
4331 loop {
4332 let mut resolved = func_ctx.resolve_type(current_base, &module.types);
4333 if let TypeInner::Pointer { base, .. } = *resolved {
4334 resolved = &module.types[base].inner;
4335 };
4336
4337 match *resolved {
4338 TypeInner::Matrix {
4339 columns,
4340 rows,
4341 scalar,
4342 } => {
4343 mat_data = Some(MatrixType {
4344 columns,
4345 rows,
4346 width: scalar.width,
4347 })
4348 }
4349 TypeInner::Array { base, .. } => {
4350 array_base = Some(base);
4351 }
4352 TypeInner::Struct { .. } => {
4353 if let Some(array_base) = array_base {
4354 if direct {
4355 return mat_data;
4356 } else {
4357 return get_inner_matrix_data(module, array_base);
4358 }
4359 }
4360
4361 break;
4362 }
4363 _ => break,
4364 }
4365
4366 current_base = match func_ctx.expressions[current_base] {
4367 crate::Expression::Access { base, .. } => base,
4368 crate::Expression::AccessIndex { base, .. } => base,
4369 _ => break,
4370 };
4371 }
4372 None
4373 }
4374
4375 /// Returns the matrix data if the access chain starting at `base`:
4376 /// - starts with an expression with resolved type of [`TypeInner::Matrix`]
4377 /// - contains zero or more expressions with resolved type of [`TypeInner::Array`] of [`TypeInner::Matrix`]
4378 /// - ends with an [`Expression::GlobalVariable`](crate::Expression::GlobalVariable) in [`AddressSpace::Uniform`](crate::AddressSpace::Uniform)
4379 fn get_inner_matrix_of_global_uniform(
4380 module: &Module,
4381 base: Handle<crate::Expression>,
4382 func_ctx: &back::FunctionCtx<'_>,
4383 ) -> Option<MatrixType> {
4384 let mut mat_data = None;
4385 let mut array_base = None;
4386
4387 let mut current_base = base;
4388 loop {
4389 let mut resolved = func_ctx.resolve_type(current_base, &module.types);
4390 if let TypeInner::Pointer { base, .. } = *resolved {
4391 resolved = &module.types[base].inner;
4392 };
4393
4394 match *resolved {
4395 TypeInner::Matrix {
4396 columns,
4397 rows,
4398 scalar,
4399 } => {
4400 mat_data = Some(MatrixType {
4401 columns,
4402 rows,
4403 width: scalar.width,
4404 })
4405 }
4406 TypeInner::Array { base, .. } => {
4407 array_base = Some(base);
4408 }
4409 _ => break,
4410 }
4411
4412 current_base = match func_ctx.expressions[current_base] {
4413 crate::Expression::Access { base, .. } => base,
4414 crate::Expression::AccessIndex { base, .. } => base,
4415 crate::Expression::GlobalVariable(handle)
4416 if module.global_variables[handle].space == crate::AddressSpace::Uniform =>
4417 {
4418 return mat_data.or_else(|| {
4419 array_base.and_then(|array_base| get_inner_matrix_data(module, array_base))
4420 })
4421 }
4422 _ => break,
4423 };
4424 }
4425 None
4426 }