Debian Codegraph @

third_party/rust/naga/src/front/spv/function.rs

raw
1 use alloc::{format, vec, vec::Vec};
2
3 use super::{Error, Instruction, LookupExpression, LookupHelper as _};
4 use crate::proc::Emitter;
5 use crate::{
6 arena::{Arena, Handle},
7 front::spv::{BlockContext, BodyIndex},
8 };
9
10 pub type BlockId = u32;
11
12 impl<I: Iterator<Item = u32>> super::Frontend<I> {
13 // Registers a function call. It will generate a dummy handle to call, which
14 // gets resolved after all the functions are processed.
15 pub(super) fn add_call(
16 &mut self,
17 from: spirv::Word,
18 to: spirv::Word,
19 ) -> Handle<crate::Function> {
20 let dummy_handle = self
21 .dummy_functions
22 .append(crate::Function::default(), Default::default());
23 self.deferred_function_calls.push(to);
24 self.function_call_graph.add_edge(from, to, ());
25 dummy_handle
26 }
27
28 pub(super) fn parse_function(&mut self, module: &mut crate::Module) -> Result<(), Error> {
29 let start = self.data_offset;
30 self.lookup_expression.clear();
31 self.lookup_load_override.clear();
32 self.lookup_sampled_image.clear();
33
34 let result_type_id = self.next()?;
35 let fun_id = self.next()?;
36 let _fun_control = self.next()?;
37 let fun_type_id = self.next()?;
38
39 let mut fun = {
40 let ft = self.lookup_function_type.lookup(fun_type_id)?;
41 if ft.return_type_id != result_type_id {
42 return Err(Error::WrongFunctionResultType(result_type_id));
43 }
44 crate::Function {
45 name: self.future_decor.remove(&fun_id).and_then(|dec| dec.name),
46 arguments: Vec::with_capacity(ft.parameter_type_ids.len()),
47 result: if self.lookup_void_type == Some(result_type_id) {
48 None
49 } else {
50 let lookup_result_ty = self.lookup_type.lookup(result_type_id)?;
51 Some(crate::FunctionResult {
52 ty: lookup_result_ty.handle,
53 binding: None,
54 })
55 },
56 local_variables: Arena::new(),
57 expressions: self.make_expression_storage(
58 &module.global_variables,
59 &module.constants,
60 &module.overrides,
61 ),
62 named_expressions: crate::NamedExpressions::default(),
63 body: crate::Block::new(),
64 diagnostic_filter_leaf: None,
65 }
66 };
67
68 // read parameters
69 for i in 0..fun.arguments.capacity() {
70 let start = self.data_offset;
71 match self.next_inst()? {
72 Instruction {
73 op: spirv::Op::FunctionParameter,
74 wc: 3,
75 } => {
76 let type_id = self.next()?;
77 let id = self.next()?;
78 let handle = fun.expressions.append(
79 crate::Expression::FunctionArgument(i as u32),
80 self.span_from(start),
81 );
82 self.lookup_expression.insert(
83 id,
84 LookupExpression {
85 handle,
86 type_id,
87 // Setting this to an invalid id will cause get_expr_handle
88 // to default to the main body making sure no load/stores
89 // are added.
90 block_id: 0,
91 },
92 );
93 //Note: we redo the lookup in order to work around `self` borrowing
94
95 if type_id
96 != self
97 .lookup_function_type
98 .lookup(fun_type_id)?
99 .parameter_type_ids[i]
100 {
101 return Err(Error::WrongFunctionArgumentType(type_id));
102 }
103 let ty = self.lookup_type.lookup(type_id)?.handle;
104 let decor = self.future_decor.remove(&id).unwrap_or_default();
105 fun.arguments.push(crate::FunctionArgument {
106 name: decor.name,
107 ty,
108 binding: None,
109 });
110 }
111 Instruction { op, .. } => return Err(Error::InvalidParameter(op)),
112 }
113 }
114
115 // Note the index this function's handle will be assigned, for tracing.
116 let function_index = module.functions.len();
117
118 // Read body
119 self.function_call_graph.add_node(fun_id);
120 let mut parameters_sampling =
121 vec![super::image::SamplingFlags::empty(); fun.arguments.len()];
122
123 let mut block_ctx = BlockContext {
124 phis: Default::default(),
125 blocks: Default::default(),
126 body_for_label: Default::default(),
127 mergers: Default::default(),
128 bodies: Default::default(),
129 module,
130 function_id: fun_id,
131 expressions: &mut fun.expressions,
132 local_arena: &mut fun.local_variables,
133 arguments: &fun.arguments,
134 parameter_sampling: &mut parameters_sampling,
135 };
136 // Insert the main body whose parent is also himself
137 block_ctx.bodies.push(super::Body::with_parent(0));
138
139 // Scan the blocks and add them as nodes
140 loop {
141 let fun_inst = self.next_inst()?;
142 log::debug!("{:?}", fun_inst.op);
143 match fun_inst.op {
144 spirv::Op::Line => {
145 fun_inst.expect(4)?;
146 let _file_id = self.next()?;
147 let _row_id = self.next()?;
148 let _col_id = self.next()?;
149 }
150 spirv::Op::Label => {
151 // Read the label ID
152 fun_inst.expect(2)?;
153 let block_id = self.next()?;
154
155 self.next_block(block_id, &mut block_ctx)?;
156 }
157 spirv::Op::FunctionEnd => {
158 fun_inst.expect(1)?;
159 break;
160 }
161 _ => {
162 return Err(Error::UnsupportedInstruction(self.state, fun_inst.op));
163 }
164 }
165 }
166
167 if let Some(ref prefix) = self.options.block_ctx_dump_prefix {
168 let dump_suffix = match self.lookup_entry_point.get(&fun_id) {
169 Some(ep) => format!("block_ctx.{:?}-{}.txt", ep.stage, ep.name),
170 None => format!("block_ctx.Fun-{}.txt", function_index),
171 };
172 let dest = prefix.join(dump_suffix);
173 let dump = format!("{block_ctx:#?}");
174 if let Err(e) = std::fs::write(&dest, dump) {
175 log::error!("Unable to dump the block context into {:?}: {}", dest, e);
176 }
177 }
178
179 // Emit `Store` statements to properly initialize all the local variables we
180 // created for `phi` expressions.
181 //
182 // Note that get_expr_handle also contributes slightly odd entries to this table,
183 // to get the spill.
184 for phi in block_ctx.phis.iter() {
185 // Get a pointer to the local variable for the phi's value.
186 let phi_pointer = block_ctx.expressions.append(
187 crate::Expression::LocalVariable(phi.local),
188 crate::Span::default(),
189 );
190
191 // At the end of each of `phi`'s predecessor blocks, store the corresponding
192 // source value in the phi's local variable.
193 for &(source, predecessor) in phi.expressions.iter() {
194 let source_lexp = &self.lookup_expression[&source];
195 let predecessor_body_idx = block_ctx.body_for_label[&predecessor];
196 // If the expression is a global/argument it will have a 0 block
197 // id so we must use a default value instead of panicking
198 let source_body_idx = block_ctx
199 .body_for_label
200 .get(&source_lexp.block_id)
201 .copied()
202 .unwrap_or(0);
203
204 // If the Naga `Expression` generated for `source` is in scope, then we
205 // can simply store that in the phi's local variable.
206 //
207 // Otherwise, spill the source value to a local variable in the block that
208 // defines it. (We know this store dominates the predecessor; otherwise,
209 // the phi wouldn't have been able to refer to that source expression in
210 // the first place.) Then, the predecessor block can count on finding the
211 // source's value in that local variable.
212 let value = if super::is_parent(predecessor_body_idx, source_body_idx, &block_ctx) {
213 source_lexp.handle
214 } else {
215 // The source SPIR-V expression is not defined in the phi's
216 // predecessor block, nor is it a globally available expression. So it
217 // must be defined off in some other block that merely dominates the
218 // predecessor. This means that the corresponding Naga `Expression`
219 // may not be in scope in the predecessor block.
220 //
221 // In the block that defines `source`, spill it to a fresh local
222 // variable, to ensure we can still use it at the end of the
223 // predecessor.
224 let ty = self.lookup_type[&source_lexp.type_id].handle;
225 let local = block_ctx.local_arena.append(
226 crate::LocalVariable {
227 name: None,
228 ty,
229 init: None,
230 },
231 crate::Span::default(),
232 );
233
234 let pointer = block_ctx.expressions.append(
235 crate::Expression::LocalVariable(local),
236 crate::Span::default(),
237 );
238
239 // Get the spilled value of the source expression.
240 let start = block_ctx.expressions.len();
241 let expr = block_ctx
242 .expressions
243 .append(crate::Expression::Load { pointer }, crate::Span::default());
244 let range = block_ctx.expressions.range_from(start);
245
246 block_ctx
247 .blocks
248 .get_mut(&predecessor)
249 .unwrap()
250 .push(crate::Statement::Emit(range), crate::Span::default());
251
252 // At the end of the block that defines it, spill the source
253 // expression's value.
254 block_ctx
255 .blocks
256 .get_mut(&source_lexp.block_id)
257 .unwrap()
258 .push(
259 crate::Statement::Store {
260 pointer,
261 value: source_lexp.handle,
262 },
263 crate::Span::default(),
264 );
265
266 expr
267 };
268
269 // At the end of the phi predecessor block, store the source
270 // value in the phi's value.
271 block_ctx.blocks.get_mut(&predecessor).unwrap().push(
272 crate::Statement::Store {
273 pointer: phi_pointer,
274 value,
275 },
276 crate::Span::default(),
277 )
278 }
279 }
280
281 fun.body = block_ctx.lower();
282
283 // done
284 let fun_handle = module.functions.append(fun, self.span_from_with_op(start));
285 self.lookup_function.insert(
286 fun_id,
287 super::LookupFunction {
288 handle: fun_handle,
289 parameters_sampling,
290 },
291 );
292
293 if let Some(ep) = self.lookup_entry_point.remove(&fun_id) {
294 self.deferred_entry_points.push((ep, fun_id));
295 }
296
297 Ok(())
298 }
299
300 pub(super) fn process_entry_point(
301 &mut self,
302 module: &mut crate::Module,
303 ep: super::EntryPoint,
304 fun_id: u32,
305 ) -> Result<(), Error> {
306 // create a wrapping function
307 let mut function = crate::Function {
308 name: Some(format!("{}_wrap", ep.name)),
309 arguments: Vec::new(),
310 result: None,
311 local_variables: Arena::new(),
312 expressions: Arena::new(),
313 named_expressions: crate::NamedExpressions::default(),
314 body: crate::Block::new(),
315 diagnostic_filter_leaf: None,
316 };
317
318 // 1. copy the inputs from arguments to privates
319 for &v_id in ep.variable_ids.iter() {
320 let lvar = self.lookup_variable.lookup(v_id)?;
321 if let super::Variable::Input(ref arg) = lvar.inner {
322 let span = module.global_variables.get_span(lvar.handle);
323 let arg_expr = function.expressions.append(
324 crate::Expression::FunctionArgument(function.arguments.len() as u32),
325 span,
326 );
327 let load_expr = if arg.ty == module.global_variables[lvar.handle].ty {
328 arg_expr
329 } else {
330 // The only case where the type is different is if we need to treat
331 // unsigned integer as signed.
332 let mut emitter = Emitter::default();
333 emitter.start(&function.expressions);
334 let handle = function.expressions.append(
335 crate::Expression::As {
336 expr: arg_expr,
337 kind: crate::ScalarKind::Sint,
338 convert: Some(4),
339 },
340 span,
341 );
342 function.body.extend(emitter.finish(&function.expressions));
343 handle
344 };
345 function.body.push(
346 crate::Statement::Store {
347 pointer: function
348 .expressions
349 .append(crate::Expression::GlobalVariable(lvar.handle), span),
350 value: load_expr,
351 },
352 span,
353 );
354
355 let mut arg = arg.clone();
356 if ep.stage == crate::ShaderStage::Fragment {
357 if let Some(ref mut binding) = arg.binding {
358 binding.apply_default_interpolation(&module.types[arg.ty].inner);
359 }
360 }
361 function.arguments.push(arg);
362 }
363 }
364 // 2. call the wrapped function
365 let fake_id = !(module.entry_points.len() as u32); // doesn't matter, as long as it's not a collision
366 let dummy_handle = self.add_call(fake_id, fun_id);
367 function.body.push(
368 crate::Statement::Call {
369 function: dummy_handle,
370 arguments: Vec::new(),
371 result: None,
372 },
373 crate::Span::default(),
374 );
375
376 // 3. copy the outputs from privates to the result
377 let mut members = Vec::new();
378 let mut components = Vec::new();
379 for &v_id in ep.variable_ids.iter() {
380 let lvar = self.lookup_variable.lookup(v_id)?;
381 if let super::Variable::Output(ref result) = lvar.inner {
382 let span = module.global_variables.get_span(lvar.handle);
383 let expr_handle = function
384 .expressions
385 .append(crate::Expression::GlobalVariable(lvar.handle), span);
386
387 // Cull problematic builtins of gl_PerVertex.
388 // See the docs for `Frontend::gl_per_vertex_builtin_access`.
389 {
390 let ty = &module.types[result.ty];
391 if let crate::TypeInner::Struct {
392 members: ref original_members,
393 span,
394 } = ty.inner
395 {
396 let mut new_members = None;
397 for (idx, member) in original_members.iter().enumerate() {
398 if let Some(crate::Binding::BuiltIn(built_in)) = member.binding {
399 if !self.gl_per_vertex_builtin_access.contains(&built_in) {
400 new_members.get_or_insert_with(|| original_members.clone())
401 [idx]
402 .binding = None;
403 }
404 }
405 }
406 if let Some(new_members) = new_members {
407 module.types.replace(
408 result.ty,
409 crate::Type {
410 name: ty.name.clone(),
411 inner: crate::TypeInner::Struct {
412 members: new_members,
413 span,
414 },
415 },
416 );
417 }
418 }
419 }
420
421 match module.types[result.ty].inner {
422 crate::TypeInner::Struct {
423 members: ref sub_members,
424 ..
425 } => {
426 for (index, sm) in sub_members.iter().enumerate() {
427 if sm.binding.is_none() {
428 continue;
429 }
430 let mut sm = sm.clone();
431
432 if let Some(ref mut binding) = sm.binding {
433 if ep.stage == crate::ShaderStage::Vertex {
434 binding.apply_default_interpolation(&module.types[sm.ty].inner);
435 }
436 }
437
438 members.push(sm);
439
440 components.push(function.expressions.append(
441 crate::Expression::AccessIndex {
442 base: expr_handle,
443 index: index as u32,
444 },
445 span,
446 ));
447 }
448 }
449 ref inner => {
450 let mut binding = result.binding.clone();
451 if let Some(ref mut binding) = binding {
452 if ep.stage == crate::ShaderStage::Vertex {
453 binding.apply_default_interpolation(inner);
454 }
455 }
456
457 members.push(crate::StructMember {
458 name: None,
459 ty: result.ty,
460 binding,
461 offset: 0,
462 });
463 // populate just the globals first, then do `Load` in a
464 // separate step, so that we can get a range.
465 components.push(expr_handle);
466 }
467 }
468 }
469 }
470
471 for (member_index, member) in members.iter().enumerate() {
472 match member.binding {
473 Some(crate::Binding::BuiltIn(crate::BuiltIn::Position { .. }))
474 if self.options.adjust_coordinate_space =>
475 {
476 let mut emitter = Emitter::default();
477 emitter.start(&function.expressions);
478 let global_expr = components[member_index];
479 let span = function.expressions.get_span(global_expr);
480 let access_expr = function.expressions.append(
481 crate::Expression::AccessIndex {
482 base: global_expr,
483 index: 1,
484 },
485 span,
486 );
487 let load_expr = function.expressions.append(
488 crate::Expression::Load {
489 pointer: access_expr,
490 },
491 span,
492 );
493 let neg_expr = function.expressions.append(
494 crate::Expression::Unary {
495 op: crate::UnaryOperator::Negate,
496 expr: load_expr,
497 },
498 span,
499 );
500 function.body.extend(emitter.finish(&function.expressions));
501 function.body.push(
502 crate::Statement::Store {
503 pointer: access_expr,
504 value: neg_expr,
505 },
506 span,
507 );
508 }
509 _ => {}
510 }
511 }
512
513 let mut emitter = Emitter::default();
514 emitter.start(&function.expressions);
515 for component in components.iter_mut() {
516 let load_expr = crate::Expression::Load {
517 pointer: *component,
518 };
519 let span = function.expressions.get_span(*component);
520 *component = function.expressions.append(load_expr, span);
521 }
522
523 match members[..] {
524 [] => {}
525 [ref member] => {
526 function.body.extend(emitter.finish(&function.expressions));
527 let span = function.expressions.get_span(components[0]);
528 function.body.push(
529 crate::Statement::Return {
530 value: components.first().cloned(),
531 },
532 span,
533 );
534 function.result = Some(crate::FunctionResult {
535 ty: member.ty,
536 binding: member.binding.clone(),
537 });
538 }
539 _ => {
540 let span = crate::Span::total_span(
541 components.iter().map(|h| function.expressions.get_span(*h)),
542 );
543 let ty = module.types.insert(
544 crate::Type {
545 name: None,
546 inner: crate::TypeInner::Struct {
547 members,
548 span: 0xFFFF, // shouldn't matter
549 },
550 },
551 span,
552 );
553 let result_expr = function
554 .expressions
555 .append(crate::Expression::Compose { ty, components }, span);
556 function.body.extend(emitter.finish(&function.expressions));
557 function.body.push(
558 crate::Statement::Return {
559 value: Some(result_expr),
560 },
561 span,
562 );
563 function.result = Some(crate::FunctionResult { ty, binding: None });
564 }
565 }
566
567 module.entry_points.push(crate::EntryPoint {
568 name: ep.name,
569 stage: ep.stage,
570 early_depth_test: ep.early_depth_test,
571 workgroup_size: ep.workgroup_size,
572 workgroup_size_overrides: None,
573 function,
574 });
575
576 Ok(())
577 }
578 }
579
580 impl BlockContext<'_> {
581 pub(super) fn gctx(&self) -> crate::proc::GlobalCtx {
582 crate::proc::GlobalCtx {
583 types: &self.module.types,
584 constants: &self.module.constants,
585 overrides: &self.module.overrides,
586 global_expressions: &self.module.global_expressions,
587 }
588 }
589
590 /// Consumes the `BlockContext` producing a Ir [`Block`](crate::Block)
591 fn lower(mut self) -> crate::Block {
592 fn lower_impl(
593 blocks: &mut crate::FastHashMap<spirv::Word, crate::Block>,
594 bodies: &[super::Body],
595 body_idx: BodyIndex,
596 ) -> crate::Block {
597 let mut block = crate::Block::new();
598
599 for item in bodies[body_idx].data.iter() {
600 match *item {
601 super::BodyFragment::BlockId(id) => block.append(blocks.get_mut(&id).unwrap()),
602 super::BodyFragment::If {
603 condition,
604 accept,
605 reject,
606 } => {
607 let accept = lower_impl(blocks, bodies, accept);
608 let reject = lower_impl(blocks, bodies, reject);
609
610 block.push(
611 crate::Statement::If {
612 condition,
613 accept,
614 reject,
615 },
616 crate::Span::default(),
617 )
618 }
619 super::BodyFragment::Loop {
620 body,
621 continuing,
622 break_if,
623 } => {
624 let body = lower_impl(blocks, bodies, body);
625 let continuing = lower_impl(blocks, bodies, continuing);
626
627 block.push(
628 crate::Statement::Loop {
629 body,
630 continuing,
631 break_if,
632 },
633 crate::Span::default(),
634 )
635 }
636 super::BodyFragment::Switch {
637 selector,
638 ref cases,
639 default,
640 } => {
641 let mut ir_cases: Vec<_> = cases
642 .iter()
643 .map(|&(value, body_idx)| {
644 let body = lower_impl(blocks, bodies, body_idx);
645
646 // Handle simple cases that would make a fallthrough statement unreachable code
647 let fall_through = body.last().is_none_or(|s| !s.is_terminator());
648
649 crate::SwitchCase {
650 value: crate::SwitchValue::I32(value),
651 body,
652 fall_through,
653 }
654 })
655 .collect();
656 ir_cases.push(crate::SwitchCase {
657 value: crate::SwitchValue::Default,
658 body: lower_impl(blocks, bodies, default),
659 fall_through: false,
660 });
661
662 block.push(
663 crate::Statement::Switch {
664 selector,
665 cases: ir_cases,
666 },
667 crate::Span::default(),
668 )
669 }
670 super::BodyFragment::Break => {
671 block.push(crate::Statement::Break, crate::Span::default())
672 }
673 super::BodyFragment::Continue => {
674 block.push(crate::Statement::Continue, crate::Span::default())
675 }
676 }
677 }
678
679 block
680 }
681
682 lower_impl(&mut self.blocks, &self.bodies, 0)
683 }
684 }