Skip to content
Merged
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
34 changes: 33 additions & 1 deletion crates/celox-frontend-sv/src/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9732,6 +9732,7 @@ fn lower_ff_processes(
}
let sites_before = pm.runtime_event_sites.len();
let extern_calls_before = pm.extern_calls;
let clock = inferred_clock(pm, process);
let ff::FfProcessUnits {
eval: eval_only,
apply,
Expand All @@ -9744,7 +9745,7 @@ fn lower_ff_processes(
.with_shared_variables(shared_variables)
.with_sparse_candidates(&edge_memories)
.with_window_writes(&window_writes)
.with_inferred_clock(trigger_set.resets.is_empty())
.with_inferred_clock(clock)
.lower_process(process.body())?;
repeated_writes.extend(repeated_ff_writes(&eval_only, &staged));
// A process without writes still runs for its runtime events and
Expand Down Expand Up @@ -10462,6 +10463,37 @@ pub(crate) fn unsupported_sv_inout(path: String) -> ParserError {
)
}

/// The clock that the sampled value functions of an edge-triggered process
/// infer (IEEE 1800-2023 16.14.6): its event expression of the clock, when
/// it is the only one whose signal the body reads nowhere else. With an
/// asynchronous reset the body reads the reset, so the clock remains.
fn inferred_clock(
pm: &procedural::ProcModule<'_>,
process: &sv::ir::FfProcess,
) -> Option<ff::Clock> {
let clock = clock_event_from_ff_process(process)?;
let reads: HashSet<SourceVarId> = pm
.implicit_reads(process.body(), true)
.into_iter()
.map(|atom| atom.id)
.collect();
let unread: Vec<_> = process
.events()
.iter()
.filter(|event| pm.id(event.signal()).is_none_or(|id| !reads.contains(&id)))
.collect();
match unread.as_slice() {
[only] if only.signal() == clock.signal() && only.edge() == clock.edge() => {
Some(ff::Clock {
signal: clock.signal().to_owned(),
rising: clock.edge() == sv::ir::FfEdge::Pos,
alone: process.events().len() == 1,
})
}
_ => None,
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down
132 changes: 109 additions & 23 deletions crates/celox-frontend-sv/src/lowering/ff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,16 +102,23 @@ pub(super) struct Ff<'p, 'a> {
/// The flush-point site of a process with deferred assertions, whose
/// queue their actions wait in.
flush_site: Option<u32>,
/// A combinational process is being lowered.
combinational: bool,
/// The process has the one clock that sampled value functions infer
/// (IEEE 1800-2023 16.14.6): an edge-triggered process with a single
/// event, which runs at each tick of it.
inferred_clock: bool,
/// The clock that the sampled value functions of the process infer
/// (IEEE 1800-2023 16.14.6).
inferred_clock: Option<Clock>,
/// The `$past` histories of the process.
history: Vec<History>,
}

/// The clock of an edge-triggered process.
pub(super) struct Clock {
/// The clock signal.
pub signal: String,
/// Whether a tick is a rising edge.
pub rising: bool,
/// The clock is the only event of the process, so every run is a tick.
pub alone: bool,
}

/// The sampled values of variable `name` at the previous ticks of the clock
/// of a process: `chain[k - 1]` holds the value `k` ticks ago, counting
/// only the ticks at which the gate held.
Expand Down Expand Up @@ -181,31 +188,28 @@ impl<'p, 'a> Ff<'p, 'a> {
host_request_sites: Vec::new(),
nba_switches: Vec::new(),
flush_site: None,
combinational: false,
inferred_clock: false,
inferred_clock: None,
history: Vec::new(),
}
}

/// Lower an edge-triggered process whose single event is the clock of
/// its sampled value functions.
pub fn with_inferred_clock(mut self, inferred: bool) -> Self {
self.inferred_clock = inferred;
/// Lower an edge-triggered process with the clock its sampled value
/// functions infer, if any.
pub fn with_inferred_clock(mut self, clock: Option<Clock>) -> Self {
self.inferred_clock = clock;
self
}

/// The operand of `$sampled` (IEEE 1800-2023 16.9.3) with each static
/// variable read through its sampled copy. Automatic variables and the
/// lowering's own temporaries keep their current value (16.5.1). A
/// combinational process reruns when its inputs change, not when their
/// sampled values do, so it cannot read them.
/// combinational process stays sensitive to the variables themselves,
/// whose changes run it, not to their copies: it is lowered as a gated
/// unit that keeps the value it last computed.
fn sampled(
&mut self,
args: &[Option<sv::ir::Expr>],
) -> Result<sv::ir::Expr, sv::AnalyzerError> {
if self.combinational {
return Err(unsupported("$sampled in combinational logic"));
}
let [Some(operand)] = args else {
return Err(unsupported("operand of `$sampled`"));
};
Expand Down Expand Up @@ -249,14 +253,34 @@ impl<'p, 'a> Ff<'p, 'a> {
}

/// Declare the `$past` histories that the sampled value functions of
/// `body` read, as nonblocking targets of the process.
/// `body`, and of the subroutines it calls, read, as nonblocking targets
/// of the process. A subroutine's calls infer the clock of the process
/// that calls it.
fn declare_history(&mut self, body: &[sv::ir::Stmt]) -> Result<(), sv::AnalyzerError> {
use sv::ir::SystemFunction;
let mut calls = Vec::new();
for stmt in body {
stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls));
}
for (callee, args) in calls {
// The calls after these are in subroutines the body calls.
let body_calls = calls.len();
let mut visited = HashSet::default();
let mut index = 0;
while index < calls.len() {
if let (sv::ir::Callee::Subroutine(name), args) = calls[index].clone()
&& let Some(subroutine) = self.m.subroutine(&name).cloned()
{
// The defaults of omitted arguments run at the call.
default_calls(&subroutine, &args, &mut calls);
if visited.insert(name) {
for stmt in &subroutine.body {
stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls));
Comment thread
tignear marked this conversation as resolved.
Resolved
Comment thread
tignear marked this conversation as resolved.
Resolved
Comment thread
tignear marked this conversation as resolved.
Resolved
}
}
}
index += 1;
}
for (position, (callee, args)) in calls.into_iter().enumerate() {
let sv::ir::Callee::System(
function @ (SystemFunction::Past
| SystemFunction::Rose
Expand All @@ -267,15 +291,32 @@ impl<'p, 'a> Ff<'p, 'a> {
else {
continue;
};
if !self.inferred_clock {
if self.inferred_clock.is_none() {
return Err(unsupported(format!(
"`{function}` outside an edge-triggered process with one event, whose clock it infers"
"`{function}` outside an edge-triggered process whose clock it infers"
)));
}
let (depth, gate) = past_depth_and_gate(function, &args)?;
let Some(Some(operand)) = args.first() else {
return Err(unsupported(format!("operand of `{function}`")));
};
// The process evaluates the gate before its body runs, outside
// the subroutine: there the gate can read only module variables,
// not the subroutine's arguments or locals.
if position >= body_calls
&& let Some(gate) = &gate
{
let mut names = HashSet::default();
expr_idents(gate, &mut names);
if names
.iter()
.any(|name| self.m.id(name).is_none_or(|id| self.m.is_hidden(id)))
{
return Err(unsupported(format!(
"`{function}` in a subroutine with a gate that reads the subroutine's arguments or locals"
)));
}
}
// The history of a nested call would need its own chain.
let mut nested = Vec::new();
collect_calls(operand, &mut nested);
Expand Down Expand Up @@ -385,7 +426,7 @@ impl<'p, 'a> Ff<'p, 'a> {
})
.ok_or_else(|| {
unsupported(format!(
"`{function}` outside an edge-triggered process with one event, whose clock it infers"
"`{function}` outside an edge-triggered process whose clock it infers"
))
})?;
renames.insert(name, history.chain[depth - 1].clone());
Expand Down Expand Up @@ -454,6 +495,9 @@ impl<'p, 'a> Ff<'p, 'a> {
arg_order: Vec::new(),
};
let mut stmts = Vec::new();
if self.history.is_empty() {
return Ok(true);
}
for history in &self.history {
let mut updates: Vec<Stmt> = history
.chain
Expand All @@ -478,6 +522,49 @@ impl<'p, 'a> Ff<'p, 'a> {
}),
}
}
// A run for another event, such as an asynchronous reset, is no
// tick: the clock has kept the level it had before the slot.
let clock = self
.inferred_clock
.as_ref()
.expect("histories have a clock");
if !clock.alone {
use sv::ir::BinaryOp::{EqCase, LogicAnd, LogicOr, NeCase};
let to = Expr::Literal(if clock.rising { "1'b1" } else { "1'b0" }.into());
let from = Expr::Literal(if clock.rising { "1'b0" } else { "1'b1" }.into());
// Edge events inspect only the least significant bit (9.4.2).
let signal = Expr::Resize {
expr: Box::new(Expr::Ident(clock.signal.clone())),
width: 1,
signed: false,
};
let old = sampled(signal.clone());
let compare = |left: Expr, op, right: Expr| Expr::Binary {
left: Box::new(left),
op,
right: Box::new(right),
};
// Table 9-2: leaving the opposite known level for X/Z is an
// edge too, as is arriving at the target level from X/Z.
let tick = compare(
compare(
compare(old.clone(), EqCase, from.clone()),
LogicAnd,
compare(signal.clone(), NeCase, from),
),
LogicOr,
compare(
compare(old, NeCase, to.clone()),
LogicAnd,
compare(signal, EqCase, to),
),
);
stmts = vec![Stmt::If {
condition: tick,
then_body: stmts,
else_body: Vec::new(),
}];
}
self.exec_block(&stmts)
}

Expand Down Expand Up @@ -4475,7 +4562,6 @@ impl<'p, 'a> Ff<'p, 'a> {
// `initial` blocks, like `always_comb`, as Verilator settles them.
let runs_at_time_zero = always_comb || !self.m.four_state;
self.direct = true;
self.combinational = true;
let mut reads = self.m.implicit_reads(body, always_comb);
reads.extend(self.m.implicit_reads(sensitivity_body, always_comb));
for stmt in body {
Expand Down
22 changes: 22 additions & 0 deletions crates/celox-sv-analyzer/src/ast/lifetimes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,12 @@ fn keep_in<T>(
) -> Result<(), AnalyzerError> {
let mut index = 0;
while index < stmts.len() {
// A sampled value of a static local is its value from an earlier
// time slot (IEEE 1800-2023 16.5.1), which the local keeps.
if let Stmt::Local { name, init } = &stmts[index]
&& statics.contains_key(name)
&& (concurrent
|| sampled_reads(&stmts[index + 1..], name)
|| entry(
state,
name,
Expand Down Expand Up @@ -839,6 +842,25 @@ pub(super) fn stmt_exprs(stmt: &Stmt) -> Vec<&Expr> {
}
}

/// Whether a sampled value function in `stmts` reads `name`.
fn sampled_reads(stmts: &[Stmt], name: &str) -> bool {
let mut found = false;
for stmt in stmts {
stmt.walk(&mut |stmt| {
for expr in stmt_exprs(stmt) {
visit_calls(expr, &mut |callee, args| {
if let Callee::System(function) = callee
&& function.reads_sampled_values()
{
found |= args.iter().flatten().any(|arg| expr_reads(arg, name));
}
});
}
});
}
found
}

/// Call `f` with the callee and arguments of every call in `expr`.
pub(super) fn visit_calls<'e>(expr: &'e Expr, f: &mut impl FnMut(&'e Callee, &'e [Option<Expr>])) {
match expr {
Expand Down
14 changes: 14 additions & 0 deletions crates/celox-sv-analyzer/src/ast/procedural/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,20 @@ impl BodyBuilder<'_, '_, '_> {
unreachable!("matched an immediate header");
};
let statement = native.statement(id);
// The action of a deferred assertion is one
// subroutine call (IEEE 1800-2023 16.4), not a block.
if deferred.is_some()
&& success.iter().chain(failure).any(|&action| {
!matches!(
native.statement(action).kind,
StatementKind::Empty | StatementKind::Expression(_)
)
})
{
return Err(unsupported(
"deferred assertion action other than one display or severity task call",
));
}
jobs.push(Job::AssertionThen {
condition,
keyword: keyword.clone(),
Expand Down
9 changes: 9 additions & 0 deletions crates/celox-sv-analyzer/src/system_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -371,6 +371,15 @@ impl SystemFunction {
/// Whether a call reads the state of the simulation: it has an effect,
/// or it returns the simulation time. Such a call is not a constant
/// expression, and a process evaluates it where it runs.
/// Whether the function reads the sampled values of its operand
/// (IEEE 1800-2023 16.9.3), which are those of earlier time slots.
pub fn reads_sampled_values(self) -> bool {
matches!(
self,
Self::Sampled | Self::Past | Self::Rose | Self::Fell | Self::Stable | Self::Changed
)
}

pub fn reads_simulation_state(self) -> bool {
self.is_effectful()
|| matches!(
Expand Down
27 changes: 18 additions & 9 deletions crates/celox/tests/sv_deferred_assertions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,8 @@ macro_rules! deferred {
}

deferred!(interpreter, build_interpreter);
deferred!(cranelift, build);
#[cfg(feature = "cranelift")]
deferred!(cranelift, build_cranelift);
#[cfg(target_arch = "x86_64")]
deferred!(native, build_native);
deferred!(wasm, build_wasm);
Expand Down Expand Up @@ -526,14 +527,22 @@ fn a_first_drain_returns_actions_of_the_initial_settle() {

#[test]
fn deferred_actions_are_one_display_or_severity_task_call() {
let source = "module Top; bit a;\n \
initial assert #0 (a) else begin $error(\"x\"); $error(\"y\"); end\n\
endmodule";
let error = celox::Simulation::from_sv_sources(vec![(source, Path::new("deferred.sv"))], "Top")
for action in [
"begin $error(\"x\"); $error(\"y\"); end",
"begin $error(\"x\"); end",
"a = 1;",
] {
let source =
format!("module Top; bit a;\n initial assert #0 (a) else {action}\nendmodule");
let error = celox::Simulation::from_sv_sources(
vec![(source.as_str(), Path::new("deferred.sv"))],
"Top",
)
.build()
.unwrap_err();
assert!(
error.to_string().contains("deferred assertion action"),
"{error}"
);
assert!(
error.to_string().contains("deferred assertion action"),
"{action}: {error}"
);
}
}
Loading
Loading