Skip to content

Commit

Permalink
debug_printf: wgsl-in, wgsl-out, spv-out
Browse files Browse the repository at this point in the history
  • Loading branch information
exrook committed Oct 16, 2023
1 parent b5654cf commit c6aac9b
Show file tree
Hide file tree
Showing 23 changed files with 185 additions and 16 deletions.
6 changes: 6 additions & 0 deletions src/back/dot/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,12 @@ impl StatementGraph {
crate::RayQueryFunction::Terminate => "RayQueryTerminate",
}
}
S::DebugPrintf { ref arguments, .. } => {
for &arg in arguments {
self.dependencies.push((id, arg, "arg"));
}
"DebugPrintf"
}
};
// Set the last node to the merge node
last_node = merge_id;
Expand Down
3 changes: 3 additions & 0 deletions src/back/glsl/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2238,6 +2238,9 @@ impl<'a, W: Write> Writer<'a, W> {
writeln!(self.out, ");")?;
}
Statement::RayQuery { .. } => unreachable!(),
Statement::DebugPrintf { .. } => {
return Err(Error::Custom("debugPrintf is not implemented".to_string()));
}
}

Ok(())
Expand Down
3 changes: 3 additions & 0 deletions src/back/hlsl/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2008,6 +2008,9 @@ impl<'a, W: fmt::Write> super::Writer<'a, W> {
writeln!(self.out, "{level}}}")?
}
Statement::RayQuery { .. } => unreachable!(),
Statement::DebugPrint { .. } => {
return Err(Error::Unimplemented("debug printf".to_string()));
}
}

Ok(())
Expand Down
3 changes: 3 additions & 0 deletions src/back/msl/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2994,6 +2994,9 @@ impl<W: Write> Writer<W> {
}
}
}
crate::Statement::DebugPrintf { .. } => {
return Err(Error::FeatureNotImplemented("debug printf".to_string()));
}
}
}

Expand Down
40 changes: 33 additions & 7 deletions src/back/spv/block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ impl Writer {

let clamp_id = self.id_gen.next();

body.push(Instruction::ext_inst(
body.push(Instruction::ext_inst_glsl_std(
self.extension_inst_import("GLSL.std.450"),
spirv::GLOp::FClamp,
float_type_id,
Expand Down Expand Up @@ -776,7 +776,7 @@ impl<'w> BlockContext<'w> {
arg2_id = self.writer.get_constant_composite(ty, &self.temp_list);
}

MathOp::Custom(Instruction::ext_inst(
MathOp::Custom(Instruction::ext_inst_glsl_std(
self.writer.extension_inst_import("GLSL.std.450"),
spirv::GLOp::FClamp,
result_type_id,
Expand Down Expand Up @@ -892,7 +892,7 @@ impl<'w> BlockContext<'w> {
&self.temp_list,
));

MathOp::Custom(Instruction::ext_inst(
MathOp::Custom(Instruction::ext_inst_glsl_std(
self.writer.extension_inst_import("GLSL.std.450"),
spirv::GLOp::FMix,
result_type_id,
Expand Down Expand Up @@ -949,15 +949,15 @@ impl<'w> BlockContext<'w> {
};

let lsb_id = self.gen_id();
block.body.push(Instruction::ext_inst(
block.body.push(Instruction::ext_inst_glsl_std(
self.writer.extension_inst_import("GLSL.std.450"),
spirv::GLOp::FindILsb,
result_type_id,
lsb_id,
&[arg0_id],
));

MathOp::Custom(Instruction::ext_inst(
MathOp::Custom(Instruction::ext_inst_glsl_std(
self.writer.extension_inst_import("GLSL.std.450"),
spirv::GLOp::UMin,
result_type_id,
Expand Down Expand Up @@ -1002,7 +1002,7 @@ impl<'w> BlockContext<'w> {
};

let msb_id = self.gen_id();
block.body.push(Instruction::ext_inst(
block.body.push(Instruction::ext_inst_glsl_std(
self.writer.extension_inst_import("GLSL.std.450"),
spirv::GLOp::FindUMsb,
int_type_id,
Expand Down Expand Up @@ -1067,7 +1067,7 @@ impl<'w> BlockContext<'w> {
};

block.body.push(match math_op {
MathOp::Ext(op) => Instruction::ext_inst(
MathOp::Ext(op) => Instruction::ext_inst_glsl_std(
self.writer.extension_inst_import("GLSL.std.450"),
op,
result_type_id,
Expand Down Expand Up @@ -2349,6 +2349,32 @@ impl<'w> BlockContext<'w> {
crate::Statement::RayQuery { query, ref fun } => {
self.write_ray_query_function(query, fun, &mut block);
}
crate::Statement::DebugPrintf {
ref format,
ref arguments,
} => {
self.writer.use_extension("SPV_KHR_non_semantic_info");
let format_id = self.gen_id();
self.writer
.strings
.push(Instruction::string(format, format_id));
let id = self.gen_id();

self.temp_list.clear();
self.temp_list.push(format_id);
for &argument in arguments {
self.temp_list.push(self.cached[argument]);
}

let set_id = self.writer.extension_inst_import("NonSemantic.DebugPrintf");
block.body.push(Instruction::ext_inst(
set_id,
1,
self.writer.void_type,
id,
&self.temp_list,
));
}
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/back/spv/image.rs
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ impl<'w> BlockContext<'w> {
// and negative values in a single instruction: negative values of
// `input_id` get treated as very large positive values.
let restricted_id = self.gen_id();
block.body.push(Instruction::ext_inst(
block.body.push(Instruction::ext_inst_glsl_std(
self.writer.extension_inst_import("GLSL.std.450"),
spirv::GLOp::UMin,
type_id,
Expand Down Expand Up @@ -592,7 +592,7 @@ impl<'w> BlockContext<'w> {
// and negative values in a single instruction: negative values of
// `coordinates` get treated as very large positive values.
let restricted_coordinates_id = self.gen_id();
block.body.push(Instruction::ext_inst(
block.body.push(Instruction::ext_inst_glsl_std(
self.writer.extension_inst_import("GLSL.std.450"),
spirv::GLOp::UMin,
coordinates.type_id,
Expand Down
2 changes: 1 addition & 1 deletion src/back/spv/index.rs
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ impl<'w> BlockContext<'w> {
// One or the other of the index or length is dynamic, so emit code for
// BoundsCheckPolicy::Restrict.
let restricted_index_id = self.gen_id();
block.body.push(Instruction::ext_inst(
block.body.push(Instruction::ext_inst_glsl_std(
self.writer.extension_inst_import("GLSL.std.450"),
spirv::GLOp::UMin,
self.writer.get_uint_type_id(),
Expand Down
14 changes: 12 additions & 2 deletions src/back/spv/instructions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,18 +121,28 @@ impl super::Instruction {
instruction
}

pub(super) fn ext_inst(
pub(super) fn ext_inst_glsl_std(
set_id: Word,
op: spirv::GLOp,
result_type_id: Word,
id: Word,
operands: &[Word],
) -> Self {
Self::ext_inst(set_id, op as Word, result_type_id, id, operands)
}

pub(super) fn ext_inst(
set_id: Word,
op: Word,
result_type_id: Word,
id: Word,
operands: &[Word],
) -> Self {
let mut instruction = Self::new(Op::ExtInst);
instruction.set_type(result_type_id);
instruction.set_result(id);
instruction.add_operand(set_id);
instruction.add_operand(op as u32);
instruction.add_operand(op);
for operand in operands {
instruction.add_operand(*operand)
}
Expand Down
1 change: 1 addition & 0 deletions src/back/spv/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -610,6 +610,7 @@ pub struct Writer {
/// The set of spirv extensions used.
extensions_used: crate::FastIndexSet<&'static str>,

strings: Vec<Instruction>,
debugs: Vec<Instruction>,
annotations: Vec<Instruction>,
flags: WriterFlags,
Expand Down
7 changes: 7 additions & 0 deletions src/back/spv/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ impl Writer {
capabilities_available: options.capabilities.clone(),
capabilities_used,
extensions_used: crate::FastIndexSet::default(),
strings: vec![],
debugs: vec![],
annotations: vec![],
flags: options.flags,
Expand Down Expand Up @@ -119,6 +120,7 @@ impl Writer {
extensions_used: take(&mut self.extensions_used).recycle(),
physical_layout: self.physical_layout.clone().recycle(),
logical_layout: take(&mut self.logical_layout).recycle(),
strings: take(&mut self.strings).recycle(),
debugs: take(&mut self.debugs).recycle(),
annotations: take(&mut self.annotations).recycle(),
lookup_type: take(&mut self.lookup_type).recycle(),
Expand Down Expand Up @@ -2001,6 +2003,11 @@ impl Writer {
Instruction::memory_model(addressing_model, memory_model)
.to_words(&mut self.logical_layout.memory_model);

// Strings come before other debug instructions
for string in self.strings.iter() {
string.to_words(&mut self.logical_layout.debugs);
}

if self.flags.contains(WriterFlags::DEBUG) {
for debug in self.debugs.iter() {
debug.to_words(&mut self.logical_layout.debugs);
Expand Down
14 changes: 14 additions & 0 deletions src/back/wgsl/writer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -921,6 +921,20 @@ impl<W: Write> Writer<W> {
}
}
Statement::RayQuery { .. } => unreachable!(),
Statement::DebugPrintf {
ref format,
ref arguments,
} => {
write!(self.out, "{level}")?;
write!(self.out, "debugPrintf(\"{format}\",")?;
for (index, &argument) in arguments.iter().enumerate() {
if index != 0 {
write!(self.out, ", ")?;
}
self.write_expr(module, argument, func_ctx)?;
}
writeln!(self.out, ");")?
}
}

Ok(())
Expand Down
16 changes: 16 additions & 0 deletions src/compact/statements.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,14 @@ impl FunctionTracer<'_> {
self.trace_expression(query);
self.trace_ray_query_function(fun);
}
St::DebugPrintf {
format: _,
ref arguments,
} => {
for expr in arguments {
self.trace_expression(*expr);
}
}

// Trivial statements.
St::Break
Expand Down Expand Up @@ -244,6 +252,14 @@ impl FunctionMap {
adjust(query);
self.adjust_ray_query_function(fun);
}
St::DebugPrintf {
format: _,
ref mut arguments,
} => {
for expr in arguments {
adjust(expr);
}
}

// Trivial statements.
St::Break
Expand Down
3 changes: 2 additions & 1 deletion src/front/spv/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3692,7 +3692,8 @@ impl<I: Iterator<Item = u32>> Frontend<I> {
| S::Store { .. }
| S::ImageStore { .. }
| S::Atomic { .. }
| S::RayQuery { .. } => {}
| S::RayQuery { .. }
| S::DebugPrintf { .. } => {}
S::Call {
function: ref mut callee,
ref arguments,
Expand Down
11 changes: 11 additions & 0 deletions src/front/wgsl/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,8 @@ pub enum Error<'a> {
ExpectedPositiveArrayLength(Span),
MissingWorkgroupSize(Span),
ConstantEvaluatorError(ConstantEvaluatorError, Span),
/// String literals are only used with debugPrintf
UnexpectedStringLiteral(Span),
}

impl<'a> Error<'a> {
Expand All @@ -253,6 +255,7 @@ impl<'a> Error<'a> {
Token::Attribute => "@".to_string(),
Token::Number(_) => "number".to_string(),
Token::Word(s) => s.to_string(),
Token::String(_) => "string".to_string(),
Token::Operation(c) => format!("operation ('{c}')"),
Token::LogicalOperation(c) => format!("logical operation ('{c}')"),
Token::ShiftOperation(c) => format!("bitshift ('{c}{c}')"),
Expand Down Expand Up @@ -700,6 +703,14 @@ impl<'a> Error<'a> {
)],
notes: vec![],
},
Error::UnexpectedStringLiteral(span) => ParseError {
message: "unexpected string literal".to_string(),
labels: vec![(
span,
"string literals can only be used as the first argument to debugPrintf".into(),
)],
notes: vec![],
},
}
}
}
32 changes: 32 additions & 0 deletions src/front/wgsl/lower/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1485,6 +1485,9 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
unreachable!("got abstract numeric type when not expected");
}
ast::Literal::Bool(b) => crate::Literal::Bool(b),
ast::Literal::String(_) => {
return Err(Error::UnexpectedStringLiteral(span));
}
};
let handle = ctx.interrupt_emitter(crate::Expression::Literal(literal), span)?;
return Ok(TypedExpression::non_reference(handle));
Expand Down Expand Up @@ -2256,6 +2259,35 @@ impl<'source, 'temp> Lowerer<'source, 'temp> {
)?;
return Ok(Some(handle));
}
"debugPrintf" => {
let format = arguments.first().ok_or(Error::WrongArgumentCount {
span,
expected: 1..16,
found: 0,
})?;

let format = match ctx.ast_expressions[*format] {
ast::Expression::Literal(ast::Literal::String(format)) => {
format.to_string()
}
_ => return Err(Error::Other),
};

let arguments = arguments
.iter()
.skip(1)
.map(|&arg| self.expression(arg, ctx.reborrow()))
.collect::<Result<Vec<_>, _>>()?;
let rctx = ctx.runtime_expression_ctx(span)?;
rctx.block
.extend(rctx.emitter.finish(rctx.naga_expressions));

rctx.emitter.start(rctx.naga_expressions);
rctx.block
.push(crate::Statement::DebugPrintf { format, arguments }, span);

return Ok(None);
}
_ => return Err(Error::UnknownIdent(function.span, function.name)),
}
};
Expand Down
5 changes: 3 additions & 2 deletions src/front/wgsl/parse/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -395,17 +395,18 @@ pub enum ConstructorType<'a> {
}

#[derive(Debug, Copy, Clone)]
pub enum Literal {
pub enum Literal<'a> {
Bool(bool),
Number(Number),
String(&'a str),
}

#[cfg(doc)]
use crate::front::wgsl::lower::Lowerer;

#[derive(Debug)]
pub enum Expression<'a> {
Literal(Literal),
Literal(Literal<'a>),
Ident(IdentExpr<'a>),

/// A type constructor expression.
Expand Down
Loading

0 comments on commit c6aac9b

Please sign in to comment.