diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index cc10985fc16..1bafc3c0126 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -3469,7 +3469,8 @@ impl<'p, 'a> Comb<'p, 'a> { } else { None }; - let (template, values) = system_task_template(self.m, &kind, args); + let (template, mut values) = system_task_template(self.m, &kind, args); + prepare_time_operands(self.m, template.as_deref(), &mut values)?; let mut captured = Vec::with_capacity(values.len()); let mut arg_widths = Vec::with_capacity(values.len()); let mut arg_signed = Vec::with_capacity(values.len()); diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index ad0ca48546b..b0c45b5c12a 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -2894,7 +2894,8 @@ impl<'p, 'a> Ff<'p, 'a> { } else { None }; - let (template, values) = system_task_template(self.m, &kind, args); + let (template, mut values) = system_task_template(self.m, &kind, args); + prepare_time_operands(self.m, template.as_deref(), &mut values)?; let mut regs = Vec::with_capacity(values.len()); let mut arg_widths = Vec::with_capacity(values.len()); let mut arg_signed = Vec::with_capacity(values.len()); diff --git a/crates/celox-frontend-sv/src/lowering/ff/file_io.rs b/crates/celox-frontend-sv/src/lowering/ff/file_io.rs index a84aed372a4..5cfba9fda9b 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/file_io.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/file_io.rs @@ -186,7 +186,8 @@ impl Ff<'_, '_> { SystemTask::Fdisplay(radix) | SystemTask::Fwrite(radix) => { let descriptor = self.file_io_arg(&args[0])?; let kind = SystemTaskKind::Print(RuntimeEventKind::Write, radix.letter()); - let (template, args) = system_task_template(self.m, &kind, &args[1..]); + let (template, mut args) = system_task_template(self.m, &kind, &args[1..]); + prepare_time_operands(self.m, template.as_deref(), &mut args)?; let mut values = vec![descriptor]; for arg in &args { values.push(self.file_io_arg(arg)?); diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 54a49321b97..bdaaeac36df 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -1250,6 +1250,79 @@ fn template_arguments(template: &str) -> usize { count } +/// Prepare each value that a `%t` of `template` converts. A system task +/// argument is self-determined (IEEE 1800-2023 11.6.1, 21.2.1), so the +/// operand of the analyzer's scaling `value * factor` keeps its own width +/// and signedness. A `string` value has no time value, and Celox would print +/// its storage handle: it is rejected, as Verilator rejects it, while Icarus +/// prints the conversion unformatted. +pub(super) fn prepare_time_operands( + module: &ProcModule<'_>, + template: Option<&str>, + values: &mut [sv::ir::SystemTaskArg], +) -> Result<(), sv::AnalyzerError> { + let Some(template) = template else { + return Ok(()); + }; + let mut chars = template.chars().peekable(); + let mut index = 0; + while let Some(ch) = chars.next() { + if ch != '%' { + continue; + } + while chars + .next_if(|ch| matches!(ch, '-' | '+' | ' ' | '#' | '0')) + .is_some() + {} + while chars.next_if(char::is_ascii_digit).is_some() {} + if chars.next_if_eq(&'.').is_some() { + while chars.next_if(char::is_ascii_digit).is_some() {} + } + let Some(spec) = chars.next() else { + break; + }; + if !"bBoOhHxXdDiIcCsStTeEfFgG".contains(spec) { + continue; + } + if matches!(spec, 't' | 'T') + && let Some(sv::ir::SystemTaskArg::Expr(expr)) = values.get_mut(index) + { + if module.expr_is_string(expr) { + return Err(unsupported("string operand of a %t conversion")); + } + // The analyzer scales a %t value as `value * factor`. + if let sv::ir::Expr::Binary { + left, + op: sv::ir::BinaryOp::Mul, + .. + } = expr + { + if module.expr_is_string(left) { + return Err(unsupported("string operand of a %t conversion")); + } + if module.expr_float_precision(left).is_none() + && let Some(width) = sv_expr_natural_width( + &module.typed_calls(left), + module.variables, + module.name_to_id, + module.constants, + module.parameter_types, + ) + { + let signed = module.expr_signed(left); + **left = sv::ir::Expr::Resize { + expr: left.clone(), + width, + signed, + }; + } + } + } + index += 1; + } + Ok(()) +} + /// The message template and value arguments of a system task: a leading /// string literal is the template. `$fatal` first takes a finish number. /// A `$display` or `$write` argument without a conversion of its own is diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 47c102a0582..f3eee42895d 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -1327,6 +1327,24 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { Ok(SystemTaskArg::Expr(value)) }) .collect::, AnalyzerError>>()?; + let mut args = args; + // A string literal that %t converts is bound as a value: the binder + // handles every literal form, triple quotes and escapes included. + let mut bind = |index: usize| -> Result, AnalyzerError> { + let Some(id) = arguments.get(index).and_then(|arg| arg.value) else { + return Ok(None); + }; + let mut value = + expression_binding::bind_value(id, declarations, self.tree, &self.dims, None)?; + self.rename_expr(&mut value); + Ok(Some(value)) + }; + scale_time_conversions( + task, + &mut args, + timescales::time_divisor(root, self.tree)?, + &mut bind, + )?; // Keep Veryl's assertion calls as calls: their message arguments // execute even on success, unlike an SV assertion's fail action. Ok(vec![Stmt::SystemTask { @@ -2866,6 +2884,78 @@ pub(super) fn process_site( }) } +/// `%t` reports a time value in the units of `$timeformat`, by default the +/// smallest time precision of the design (IEEE 1800-2023 20.4.3, Table 20-3), +/// in which the simulation counts its time. The value is in the time unit of +/// the calling scope, of which `ticks_per_unit` simulation time units make +/// one, so each value a `%t` of the template converts is scaled by it. +fn scale_time_conversions( + task: SystemTask, + args: &mut [SystemTaskArg], + ticks_per_unit: u64, + bind: &mut impl FnMut(usize) -> Result, AnalyzerError>, +) -> Result<(), AnalyzerError> { + if ticks_per_unit == 1 { + return Ok(()); + } + let template = match task { + SystemTask::Display(_) | SystemTask::Write(_) | SystemTask::Severity(_) => 0, + SystemTask::Fatal => usize::from(matches!(args.first(), Some(SystemTaskArg::Expr(_)))), + SystemTask::Fdisplay(_) + | SystemTask::Fwrite(_) + | SystemTask::Assert + | SystemTask::AssertContinue => 1, + _ => return Ok(()), + }; + let Some(SystemTaskArg::Str(text)) = args.get(template) else { + return Ok(()); + }; + // The conversions of the template, in the order they take arguments + // (21.2.1.2): flags, a width and a precision may precede each. + let mut conversions = Vec::new(); + let mut chars = text.chars().peekable(); + while let Some(ch) = chars.next() { + if ch != '%' { + continue; + } + while chars + .next_if(|ch| matches!(ch, '-' | '+' | ' ' | '#' | '0')) + .is_some() + {} + while chars.next_if(char::is_ascii_digit).is_some() {} + if chars.next_if_eq(&'.').is_some() { + while chars.next_if(char::is_ascii_digit).is_some() {} + } + if let Some(spec) = chars.next() + && "bBoOhHxXdDiIcCsStTeEfFgG".contains(spec) + { + conversions.push(spec); + } + } + for (offset, spec) in conversions.into_iter().enumerate() { + if !matches!(spec, 't' | 'T') { + continue; + } + let index = template + 1 + offset; + // A string literal converts as its packed bytes (5.9). The factor is + // signed, so the product keeps the signedness of the value (11.8.1). + let value = match args.get(index) { + Some(SystemTaskArg::Expr(value)) => value.clone(), + Some(SystemTaskArg::Str(_)) => match bind(index)? { + Some(value) => value, + None => continue, + }, + Some(SystemTaskArg::Empty) | None => continue, + }; + args[index] = SystemTaskArg::Expr(Expr::Binary { + left: Box::new(value), + op: BinaryOp::Mul, + right: Box::new(Expr::Literal(format!("64'sd{ticks_per_unit}"))), + }); + } + Ok(()) +} + /// Original invocation span of a native token range, when it belongs to one file. pub(super) fn source_span( tokens: celox_sv_syntax::TokenRange, diff --git a/crates/celox-test-suite/src/sv/cases/system_functions.vtest b/crates/celox-test-suite/src/sv/cases/system_functions.vtest index 961efccc184..0990ccf7e9f 100644 --- a/crates/celox-test-suite/src/sv/cases/system_functions.vtest +++ b/crates/celox-test-suite/src/sv/cases/system_functions.vtest @@ -2386,6 +2386,7 @@ endmodule (case time_format_consumes_its_expression_argument (source "time_format.sv" #" +`timescale 1ns/1ns module Top(input logic clk); always_ff @(posedge clk) begin $display("t:[%t] d:[%d]", 32'd7, 8'shfe); @@ -2397,6 +2398,72 @@ endmodule (tick clk) (expect_output "t:[ 7] d:[ -2]\nsmall:[17] padded:[ 9] next:[af] %t\n")) +; Without `$timeformat`, %t reports a time in the smallest time precision of +; the design, in a field of 20 columns (IEEE 1800-2023 20.4.3, Table 20-3): +; a value in the time unit of its scope is scaled to it. Timed cases run at +; 1 ns / 1 ps. +(case time_format_defaults_to_the_smallest_precision + (source "time_format_default.sv" #" +module Top; + int n = 7; + initial begin + #1.5; + $display("[%t] [%0t] [%0t] [%0t] [%0d]", $time, $time, $realtime, n, $time); + $write("w=%0t\n", $realtime); + $finish; + end +endmodule +"#) + (top Top) + (run_to_finish) + (expect_output "[ 2000] [2000] [1500] [7000] [2]\nw=1500\n")) + +; The smallest precision of all the design's time scales sets the unit of +; %t in every scope. +(case time_format_scales_each_scope_to_the_smallest_precision + (source "time_format_scopes.sv" #" +`timescale 1ns/1ps +module Top(input logic clk); + Child child(.clk); + always_ff @(posedge clk) $display("top [%0t] [%t]", 32'd7, 8'd3); +endmodule +`timescale 1us/1us +module Child(input logic clk); + always_ff @(posedge clk) $display("child [%0t]", 32'd2); +endmodule +"#) + (top Top) + (tick clk) + (expect_output "top [7000] [ 3000]\nchild [2000000]\n")) + +; A string literal that %t converts is its packed bytes (IEEE 1800-2023 5.9), +; scaled like any other value. +(case time_format_scales_string_literals + (source "time_format_strings.sv" #" +`timescale 1ns/1ps +module Top(input logic clk); + always_ff @(posedge clk) $display("[%0t] [%t]", "A", "AB"); +endmodule +"#) + (top Top) + (tick clk) + (expect_output "[65000] [ 16706000]\n")) + +; A value that %t converts is self-determined (IEEE 1800-2023 11.6.1, 21.2.1): +; it is evaluated at its own width before it is scaled. +(case time_format_values_are_self_determined + (source "time_format_self_determined.sv" #" +`timescale 1ns/1ps +module Top(input logic clk); + logic [7:0] a = 8'hff; + logic [3:0] b = 4'd9, c = 4'd8; + always_ff @(posedge clk) $display("[%0t] [%0t] [%0t]", a + 8'd1, b + c, {b, c}); +endmodule +"#) + (top Top) + (tick clk) + (expect_output "[0] [1000] [152000]\n")) + (case string_literals_follow_numeric_format_specifiers (source "string_format.sv" #" module Top(input logic clk); diff --git a/crates/celox-test-suite/verification/sv/icarus/system_functions.json b/crates/celox-test-suite/verification/sv/icarus/system_functions.json index 341ab3ef479..eacfdc15b69 100644 --- a/crates/celox-test-suite/verification/sv/icarus/system_functions.json +++ b/crates/celox-test-suite/verification/sv/icarus/system_functions.json @@ -1575,6 +1575,50 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "system_functions::time_format_defaults_to_the_smallest_precision", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "system_functions::time_format_scales_each_scope_to_the_smallest_precision", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "system_functions::time_format_scales_string_literals", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "system_functions::time_format_values_are_self_determined", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox-test-suite/verification/sv/verilator/system_functions.json b/crates/celox-test-suite/verification/sv/verilator/system_functions.json index 5f54ad2fe17..697545e7c70 100644 --- a/crates/celox-test-suite/verification/sv/verilator/system_functions.json +++ b/crates/celox-test-suite/verification/sv/verilator/system_functions.json @@ -876,6 +876,50 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "system_functions::time_format_defaults_to_the_smallest_precision", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "system_functions::time_format_scales_each_scope_to_the_smallest_precision", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "system_functions::time_format_scales_string_literals", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "system_functions::time_format_values_are_self_determined", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index d7f08c6624c..280d9aebc2f 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -513,6 +513,10 @@ sv_backends! { fn character_formats_preserve_non_utf8_bytes(sim) { @case "system_functions::character_formats_preserve_non_utf8_bytes"; } fn time_format_consumes_its_expression_argument(sim) { @case "system_functions::time_format_consumes_its_expression_argument"; } + fn time_format_defaults_to_the_smallest_precision(sim) { @case "system_functions::time_format_defaults_to_the_smallest_precision"; } + fn time_format_scales_each_scope_to_the_smallest_precision(sim) { @case "system_functions::time_format_scales_each_scope_to_the_smallest_precision"; } + fn time_format_scales_string_literals(sim) { @case "system_functions::time_format_scales_string_literals"; } + fn time_format_values_are_self_determined(sim) { @case "system_functions::time_format_values_are_self_determined"; } fn string_literals_follow_numeric_format_specifiers(sim) { @case "system_functions::string_literals_follow_numeric_format_specifiers"; } // Veryl extension calls emitted unchanged into SV, not SV assert statements. fn veryl_assert_continue_ff_captures_arguments_before_reporting(sim) { @@ -3134,3 +3138,91 @@ fn scope_randomize_survives_all_optimization_levels() { } } } + +/// A signed value that %t converts keeps its sign when it is scaled to the +/// smallest time precision, as Icarus 13.0 prints it. Verilator 5.052 prints +/// the 32-bit pattern of an `int` as unsigned (4294967294000 for -2), so +/// this is no suite case. +#[test] +fn time_format_keeps_the_sign_of_signed_values() { + let source = r#" + `timescale 1ns/1ps + module Top(input logic go); + int n; + logic signed [7:0] s; + always_comb begin + n = -2; + s = -8'sd3; + if (go) $display("[%0t] [%0t]", n, s); + end + endmodule + "#; + let mut sim = Simulator::from_sv_sources(vec![(source, Path::new("signed_time.sv"))], "Top") + .build_cranelift() + .unwrap(); + let go = sim.signal("go"); + sim.modify(|io| io.set(go, 0u8)).unwrap(); + sim.drain_runtime_events(); + sim.modify(|io| io.set(go, 1u8)).unwrap(); + let messages: Vec<_> = sim + .drain_runtime_events() + .into_iter() + .map(|event| match event { + celox::RuntimeEvent::Display { message } => message, + event => panic!("unexpected event: {event:?}"), + }) + .collect(); + assert_eq!(messages, vec![b"[-2000] [-3000]".to_vec()]); +} + +/// A triple-quoted string literal that %t converts is its packed bytes too +/// (IEEE 1800-2023 5.9), scaled like any other value. Verilator 5.052 prints +/// 65000; Icarus 13.0 cannot parse triple-quoted literals, so this is no +/// suite case. +#[test] +fn time_format_scales_triple_quoted_literals() { + let source = r#" + `timescale 1ns/1ps + module Top(input logic go); + always_comb if (go) $display("[%0t]", """A"""); + endmodule + "#; + let mut sim = Simulator::from_sv_sources(vec![(source, Path::new("triple_time.sv"))], "Top") + .build_cranelift() + .unwrap(); + let go = sim.signal("go"); + sim.modify(|io| io.set(go, 0u8)).unwrap(); + sim.drain_runtime_events(); + sim.modify(|io| io.set(go, 1u8)).unwrap(); + let messages: Vec<_> = sim + .drain_runtime_events() + .into_iter() + .map(|event| match event { + celox::RuntimeEvent::Display { message } => message, + event => panic!("unexpected event: {event:?}"), + }) + .collect(); + assert_eq!(messages, vec![b"[65000]".to_vec()]); +} + +/// A `string` value has no time to report: %t of one is rejected rather than +/// printing its storage handle. Verilator 5.052 rejects it too ("format of +/// '%t' illegal with non-numeric argument"); Icarus 13.0 prints the +/// conversion unformatted. +#[test] +fn time_format_rejects_string_operands() { + for timescale in ["`timescale 1ns/1ps", "`timescale 1ns/1ns"] { + let source = format!( + "{timescale}\nmodule Top(input logic go); string s = \"A\"; always_comb if (go) $display(\"[%0t]\", s); endmodule" + ); + let error = + Simulator::from_sv_sources(vec![(source.as_str(), Path::new("string_time.sv"))], "Top") + .build_cranelift() + .expect_err("a string %t operand must be rejected") + .to_string(); + assert!( + error.contains("string operand of a %t conversion"), + "{timescale}: {error}" + ); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index af7fea78edf..f97975a8043 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -646,6 +646,13 @@ precision includes all declared precisions and directive precisions, even in uninstantiated definitions (3.14.3). Selected instance arrays and generate paths require elaborated hierarchy lookup and are currently rejected. +`%t` reports a time in the smallest time precision of the design, in a field +of 20 columns (IEEE 1800-2023 20.4.3): `$display("%0t", $realtime)` after +`#1.5` under `` `timescale 1ns/1ps`` prints `1500`. A design without time scales +uses the 1 ns / 1 ps defaults, so `%t` reports picoseconds there too. +`%t` of a `string` value, which has no time to report, is rejected, and +`$timeformat` is not supported. + `$printtimescale` displays the selected time scope in the IEEE 1800-2023 20.4.2 form, for example `Time scale of (Top.child) is 100ns / 10ps`. It accepts the current scope, a design-element argument, `$unit`, or `$root`, diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index c10c355185b..73c64b82611 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -520,6 +520,11 @@ interface型から解決します。generic interfaceポートとgenerate内の 変換時に精度を失う場合があります。checkpoint の復元後は復元した時刻を参照します。 +`%t` は時刻を設計全体で最も細かい時間精度の単位で、20 桁の欄に表示します(IEEE 1800-2023 20.4.3)。 +`` `timescale 1ns/1ps`` のもとで `#1.5` の後に `$display("%0t", $realtime)` を実行すると `1500` を表示します。 +時間スケールのない設計は既定の 1 ns / 1 ps を使うため、`%t` はやはりピコ秒で表示します。 +報告する時刻を持たない `string` の値に対する `%t` は拒否します。`$timeformat` には対応していません。 + `$printtimescale` は IEEE1800-2023 20.4.2 の形式で時刻スコープを表示します。 例: `Time scale of (Top.child) is 100ns / 10ps`。 引数なしの現在スコープ、design element、`$unit`、`$root` を指定でき、