Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions crates/celox-sv-analyzer/src/ast/procedural/timing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,15 @@ impl BodyBuilder<'_, '_, '_> {
parenthesized,
} => {
self.allow_timing("delay control")?;
let literal = expression_binding::ungroup(*value, self.tree.declarations());
if let ExprKind::Literal(text) = &self.tree.declarations().expression(literal).kind
&& let Some(ticks) = timescales::delay_literal(literal, text, self.tree)?
{
return Ok(Stmt::Delay {
amount: Expr::Literal(format!("64'd{ticks}")),
ticks_per_unit: 1,
});
}
Ok(Stmt::Delay {
amount: self.native_delay(*value, *parenthesized)?,
ticks_per_unit: timescales::time_divisor(*value, self.tree)?,
Expand Down
57 changes: 57 additions & 0 deletions crates/celox-sv-analyzer/src/ast/timescales.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1021,6 +1021,63 @@ pub(super) fn time_divisor(
}
}

/// A standalone time literal used as a delay: round at the declaring
/// scope's precision before converting to global scheduler ticks (3.14.1).
pub(super) fn delay_literal(
node: celox_sv_syntax::ExprId,
text: &str,
tree: &AnalysisContext<'_>,
) -> Converted<Option<u64>> {
let Some((number, exponent)) = [
("fs", -15),
("ps", -12),
("ns", -9),
("us", -6),
("ms", -3),
("s", 0),
]
.into_iter()
.find_map(|(suffix, exponent)| text.strip_suffix(suffix).map(|n| (n, exponent))) else {
return Ok(None);
};
let context = tree.state.timescales.design.borrow();
let source = key(tree);
let extended = (!context.design.units.contains_key(&source))
.then(|| context.design.including_tree(tree))
.transpose()?;
let design = extended.as_ref().unwrap_or(&context.design);
let unit = &design.units[&source];
let at = tree.declarations().expression(node).tokens.start;
let scale =
scope_at(&unit.scopes, &unit.parents, at).map_or(unit.scale, |i| unit.scopes[i].scale);
let global_precision = design
.precision
.unwrap_or(DEFAULT.precision)
.min(scale.precision);
let number = number.replace('_', "");
let fraction = number
.split_once('.')
.map_or(0, |(_, fraction)| fraction.len());
let digits = number.replace('.', "");
let coefficient = digits
.parse::<num_bigint::BigUint>()
.map_err(|_| unsupported("time literal delay"))?;
let power = exponent
- scale.precision
- i32::try_from(fraction).map_err(|_| unsupported("time literal delay"))?;
let precision_units = if power >= 0 {
coefficient * num_bigint::BigUint::from(10u8).pow(power as u32)
} else {
let divisor = num_bigint::BigUint::from(10u8).pow(power.unsigned_abs());
(coefficient + (&divisor / 2u8)) / divisor
};
let ticks = precision_units
* num_bigint::BigUint::from(10u8).pow((scale.precision - global_precision) as u32);
Ok(Some(u64::try_from(ticks).map_err(|_| {
unsupported("time literal delay exceeds scheduler range")
})?))
}

#[cfg(test)]
mod tests {
#[test]
Expand Down
25 changes: 25 additions & 0 deletions crates/celox-sv-analyzer/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6201,3 +6201,28 @@ fn unpacked_constant_function_bounds_survive_analysis_without_losing_the_contrac
// contracts, even though lowering no longer owns their function bodies.
assert!(typecheck::eval_const_expr(range.right(), &HashMap::default()).is_none());
}

#[test]
fn time_literal_delays_reject_scheduler_overflow() {
let error = analyze_source(
"module Top; timeunit 1s / 1fs; initial #18446744073709551616s; endmodule",
Path::new("overflow_delay.sv"),
)
.unwrap_err();
assert!(error.to_string().contains("scheduler range"), "{error}");
}

#[test]
fn time_literal_delays_accept_numeric_separators() {
let source = "module Top; timeunit 1ns / 1ps; initial #1_000ps; endmodule";
let ir = analyze_source(source, Path::new("separated_time.sv")).unwrap();
let ir::Stmt::Delay {
amount,
ticks_per_unit,
} = &ir.modules()[0].initial_processes()[0].body()[0]
else {
panic!("delay");
};
assert_eq!(*ticks_per_unit, 1);
assert!(matches!(amount, ir::Expr::Literal(value) if value == "64'd1000"));
}
21 changes: 21 additions & 0 deletions crates/celox-test-suite/src/sv/cases/timing.vtest
Original file line number Diff line number Diff line change
Expand Up @@ -1035,3 +1035,24 @@ module Top(input bit clk,output bit[7:0]seen);bit q;Child c(clk,q);initial forev
(run_until 2) (assert_eq a 10) (assert_eq b 20)
(run_until 3) (assert_eq a 11) (assert_eq b 21)
(run_until 6) (assert_eq a 12) (assert_eq b 21))

(case time_literal_delays_accept_all_units
(source "time_literal_units.sv" #"
module Top(output int count);
initial begin
count = 0;
#5ns; count++;
#(2.5ns); count++;
#40ps; count++;
#1fs; count++;
#1000ps; count++;
#2.5us; count++;
#1ms; count++;
#0.001s; count++;
$finish;
end
endmodule
"#)
(top Top)
(run_to_finish)
(assert_eq count 8))
37 changes: 37 additions & 0 deletions crates/celox/tests/frontends/systemverilog/timing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ timed_cases! {
fn timed_task_in_edge_always_rearms_after_return = "timing::timed_task_in_edge_always_rearms_after_return";
fn time_calls_in_child_port_subroutines = "timing::time_calls_in_child_port_subroutines";
fn time_calls_in_child_port_actuals = "timing::time_calls_in_child_port_actuals";
fn time_literal_delays_accept_all_units = "timing::time_literal_delays_accept_all_units";
fn delays_resume_initial_blocks_at_later_times = "timing::delays_resume_initial_blocks_at_later_times";
fn always_with_a_delay_generates_a_clock = "timing::always_with_a_delay_generates_a_clock";
fn edge_waits_resume_before_the_registers_of_that_edge_update = "timing::edge_waits_resume_before_the_registers_of_that_edge_update";
Expand Down Expand Up @@ -186,3 +187,39 @@ fn timed_task_activations_survive_each_optimization_level() {
}
}
}

#[test]
fn time_literal_delays_round_at_scope_precision() {
let source = r#"
module Fine(output bit done);
timeunit 1ns / 1ps;
initial begin #2.75ns; done = 1; end
endmodule
module Coarse(output bit done);
timeunit 1ns / 100ps;
initial begin #(2.75ns); done = 1; end
endmodule
module Top(output bit fine, coarse);
timeunit 1ns / 1ps;
Fine f(fine); Coarse c(coarse);
endmodule
"#;
let mut sim = celox::Simulation::from_sv_sources(
vec![(source, std::path::Path::new("scope_precision.sv"))],
"Top",
)
.build()
.unwrap();
let fine = sim.signal("fine");
let coarse = sim.signal("coarse");
sim.run_until(2749).unwrap();
assert_eq!(sim.get(fine), 0u8.into());
assert_eq!(sim.get(coarse), 0u8.into());
sim.run_until(2750).unwrap();
assert_eq!(sim.get(fine), 1u8.into());
assert_eq!(sim.get(coarse), 0u8.into());
sim.run_until(2799).unwrap();
assert_eq!(sim.get(coarse), 0u8.into());
sim.run_until(2800).unwrap();
assert_eq!(sim.get(coarse), 1u8.into());
}
7 changes: 7 additions & 0 deletions docs/guide/systemverilog-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,13 @@ until shared argument storage and its change notifications are supported.
Event expressions have the same restrictions
as waits written directly in a process.

### Time literal delays

Standalone delay controls accept time literals such as `#5ns`, `#(2.75ns)` and
`#40ps`, with all six units from `fs` to `s`. Values round at the declaring
scope's precision before conversion to scheduler ticks (5.8, 3.14.1). Real-valued
arithmetic expressions remain unsupported.

### Built-in functions and tasks

| Area | Supported |
Expand Down
6 changes: 6 additions & 0 deletions docs/ja/guide/systemverilog-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,12 @@ package/`$unit` の static 引数を持つ時間待ち task と、static task
共有ストレージと変更通知に対応するまで拒否します。
イベント式の制約は、プロセスに直接記述するイベント待ちと同じです。

### 時間リテラルによる遅延

遅延制御の時間リテラルは `#5ns`、`#(2.75ns)`、`#40ps` など、`fs` から `s` の6単位に
対応します。宣言スコープの時間精度で丸めてから scheduler の tick に変換します
(5.8、3.14.1)。実数の算術式は引き続き未対応です。

### 組み込み関数とタスク

| 領域 | サポート内容 |
Expand Down
14 changes: 7 additions & 7 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading