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
29 changes: 18 additions & 11 deletions crates/celox-frontend-sv/src/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ use std::path::Path;

use celox_design::{
BinaryOp, BitAccess, DisplaySizing, DomainKind, ExternFunction, ExternSignature, ExternType,
InitialStateData, InitialStateValue, ModuleId, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH,
PortTypeKind, ProcessSlots, RegionedVarAddrBase, RuntimeErrorInfo, RuntimeEventKind,
RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, WORKING_REGION, WaitSite,
InitialStateData, InitialStateValue, ModuleId, NbaSite, PROCESS_DELAY_WIDTH,
PROCESS_STATUS_WIDTH, PortTypeKind, ProcessSlots, RegionedVarAddrBase, RuntimeErrorInfo,
RuntimeEventKind, RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase,
WORKING_REGION, WaitSite,
};
use celox_frontend_core::process::PROCESS_RESUME_WIDTH;
use celox_frontend_core::symbolic::artifact::{
Expand Down Expand Up @@ -2004,7 +2005,7 @@ fn lower_module_with_overrides(
)
};
mark_ff_event_domains(&event_vars, &mut variables);
let (initial_values, processes, wait_sites) = lower_initial_processes(
let (initial_values, processes, wait_sites, nba_sites) = lower_initial_processes(
module,
&mut variables,
&mut name_to_id,
Expand Down Expand Up @@ -2113,7 +2114,7 @@ fn lower_module_with_overrides(
package_bindings: HashMap::default(),
counter_slots: Vec::new(),
wait_sites,
nba_sites: Vec::new(),
nba_sites,
},
variables,
port_order,
Expand Down Expand Up @@ -2775,11 +2776,12 @@ fn lower_initial_processes(
Vec<InitialStateValue<SourceVarId>>,
Vec<SymbolicProcess>,
Vec<WaitSite<SourceVarId>>,
Vec<NbaSite<SourceVarId>>,
),
sv::AnalyzerError,
> {
if module.initial_processes().is_empty() {
return Ok((Vec::new(), Vec::new(), Vec::new()));
return Ok((Vec::new(), Vec::new(), Vec::new(), Vec::new()));
}
let mut values = Vec::new();
let mut runtime = Vec::new();
Expand Down Expand Up @@ -2833,7 +2835,7 @@ fn lower_initial_processes(
}
}
if runtime.is_empty() {
return Ok((values, Vec::new(), Vec::new()));
return Ok((values, Vec::new(), Vec::new(), Vec::new()));
}

let mut next_id = SourceVarId(
Expand Down Expand Up @@ -2888,24 +2890,29 @@ fn lower_initial_processes(
pm.runtime_errors = std::mem::take(runtime_errors);
pm.extern_functions = std::mem::take(extern_functions);
let mut wait_sites = Vec::new();
let mut nba_sites = Vec::new();
let processes = runtime
.into_iter()
.zip(slots)
.enumerate()
.map(|(index, ((process, random_seed), slots))| {
let (kernel, sites) = ff::Ff::new(&mut pm, random_seed).lower_initial_kernel(
let kernel = ff::Ff::new(&mut pm, random_seed).lower_initial_kernel(
process.body(),
slots,
index,
)?;
wait_sites.extend(sites);
Ok(SymbolicProcess { kernel, slots })
wait_sites.extend(kernel.wait_sites);
nba_sites.extend(kernel.nba_sites);
Ok(SymbolicProcess {
kernel: kernel.unit,
slots,
})
})
.collect::<Result<Vec<_>, sv::AnalyzerError>>();
*runtime_event_sites = std::mem::take(&mut pm.runtime_event_sites);
*runtime_errors = std::mem::take(&mut pm.runtime_errors);
*extern_functions = std::mem::take(&mut pm.extern_functions);
Ok((values, processes?, wait_sites))
Ok((values, processes?, wait_sites, nba_sites))
}

fn lower_comb_processes(
Expand Down
172 changes: 147 additions & 25 deletions crates/celox-frontend-sv/src/lowering/ff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@

use super::procedural::*;
use super::*;
use celox_design::{CounterKind, WaitSite};
use celox_design::{CounterKind, NbaSite, WaitSite};
use celox_frontend_core::process::{ProcessKernelBuilder, ProcessKernelError};
use celox_sir::{RegisterId, RegisterType};
use celox_slt::SLTToSIRLowerer;
Expand Down Expand Up @@ -64,6 +64,8 @@ pub(super) struct Ff<'p, 'a> {
process: usize,
/// The wait sites of the process, by local index.
wait_sites: Vec<WaitSite<SourceVarId>>,
/// The nonblocking assignment sites of the process, by local index.
nba_sites: Vec<NbaSite<SourceVarId>>,
direct: bool,
}

Expand Down Expand Up @@ -111,6 +113,7 @@ impl<'p, 'a> Ff<'p, 'a> {
direct: false,
process: 0,
wait_sites: Vec::new(),
nba_sites: Vec::new(),
}
}

Expand Down Expand Up @@ -1815,6 +1818,22 @@ impl<'p, 'a> Ff<'p, 'a> {

fn exec(&mut self, stmt: &sv::ir::Stmt) -> Result<bool, sv::AnalyzerError> {
match stmt {
sv::ir::Stmt::Assign {
lhs,
rhs,
nonblocking: true,
} if self.kernel.is_some() => {
self.nonblocking(std::slice::from_ref(lhs), rhs)?;
Ok(true)
}
sv::ir::Stmt::AssignConcat {
parts,
rhs,
nonblocking: true,
} if self.kernel.is_some() => {
self.nonblocking(parts, rhs)?;
Ok(true)
}
sv::ir::Stmt::Assign { lhs, rhs, .. } => {
self.assign(lhs, rhs)?;
Ok(true)
Expand Down Expand Up @@ -3172,30 +3191,8 @@ impl Ff<'_, '_> {
body: &[sv::ir::Stmt],
slots: ProcessSlots<SourceVarId>,
process: usize,
) -> Result<(ExecutionUnit<Addr>, Vec<WaitSite<SourceVarId>>), sv::AnalyzerError> {
) -> Result<KernelUnit, sv::AnalyzerError> {
self.process = process;
// A nonblocking update would take effect in a later region of the
// time step, after the process has run on.
for stmt in body {
let mut nonblocking = false;
stmt.walk(&mut |stmt| {
nonblocking |= matches!(
stmt,
sv::ir::Stmt::Assign {
nonblocking: true,
..
} | sv::ir::Stmt::AssignConcat {
nonblocking: true,
..
}
);
});
if nonblocking {
return Err(unsupported(
"nonblocking assignment in an initial block that runs as a process",
));
}
}
let mut kernel = ProcessKernelBuilder::new(slots);
std::mem::swap(&mut self.b, kernel.builder());
self.kernel = Some(kernel);
Expand All @@ -3204,7 +3201,125 @@ impl Ff<'_, '_> {
std::mem::swap(&mut self.b, kernel.builder());
let mut unit = kernel.build();
prune_unreachable_blocks(&mut unit);
Ok((unit, self.wait_sites))
Ok(KernelUnit {
unit,
wait_sites: self.wait_sites,
nba_sites: self.nba_sites,
})
}

/// A nonblocking assignment in a process (IEEE 1800-2023 10.4.2): the
/// right-hand side is evaluated now, once, and each target part becomes
/// an update the runtime queues for the NBA region.
fn nonblocking(
&mut self,
parts: &[sv::ir::LValue],
rhs: &sv::ir::Expr,
) -> Result<(), sv::AnalyzerError> {
let mut targets = Vec::with_capacity(parts.len());
for part in parts {
targets.push(self.nba_target(part)?);
Comment on lines +3220 to +3221

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Propagate unrolled loop indices before classifying NBA targets

When a timed process contains a constant-bound loop such as for (int i = 0; i < 4; i++) q[i] <= 1'b1;, exec_loop unrolls the loop and records each i value in self.overlay, but this path passes the original lvalue directly to nba_target. Consequently, eval_const_expr_with_types cannot resolve i and rejects the assignment as having a run-time position, even though each unrolled target is constant. Apply propagate_lvalue before resolving the NBA target, as the blocking assignment path already does.

Useful? React with 👍 / 👎.

}
let total: usize = targets.iter().map(|(_, _, width)| width).sum();
let four_state = targets.iter().any(|(id, _, _)| self.m.var(*id).is_4state);
let (_, value_name) = self.m.temp("nba", total, false, four_state);
self.assign(&sv::ir::LValue::Ident(value_name.clone()), rhs)?;
// The parts, most significant first, take consecutive bits of the
// value.
let mut high = total;
for (id, lsb, width) in targets {
let low = high - width;
let (staged, staged_name) =
self.m
.temp("nba_part", width, false, self.m.var(id).is_4state);
self.assign(
&sv::ir::LValue::Ident(staged_name),
&sv::ir::Expr::Select {
expr: Box::new(sv::ir::Expr::Ident(value_name.clone())),
msb: sv::ir::ConstExpr::Literal((high - 1).to_string()),
lsb: sv::ir::ConstExpr::Literal(low.to_string()),
signed: false,
},
)?;
high = low;
let site = NbaSite {
process: self.process,
target: id,
lsb,
width,
value: staged,
offset: None,
pending: None,
};
let index = self.nba_sites.len() as u32;
let staged_four_state = self.m.var(staged).is_4state;
self.with_kernel(|kernel| {
kernel.nonblocking(index, &site, |builder| {
let value = if staged_four_state {
builder.alloc_logic(width)
} else {
builder.alloc_bit(width, false)
};
builder.emit(SIRInstruction::Load(
value,
stable(staged),
SIROffset::Static(0),
width,
));
Ok::<_, ProcessKernelError>((value, None))
})
})
.map_err(kernel_error)?;
self.nba_sites.push(site);
}
Ok(())
}

/// The variable and the constant bit range a nonblocking assignment in
/// a process writes.
fn nba_target(
&self,
lvalue: &sv::ir::LValue,
) -> Result<(SourceVarId, usize, usize), sv::AnalyzerError> {
let id = self
.m
.id(lvalue.name())
.ok_or_else(|| unsupported(format!("assignment target `{}`", lvalue.name())))?;
let variable = self.m.var(id);
if !variable.array_dims.is_empty() {
return Err(unsupported(
"nonblocking assignment to an unpacked array in a process",
));
}
match lvalue {
sv::ir::LValue::Ident(_) => Ok((id, 0, variable.width)),
sv::ir::LValue::Select { msb, lsb, .. } => {
let constant = |expr| {
sv::typecheck::eval_const_expr_with_types(
expr,
self.m.constants,
self.m.parameter_types,
)
};
let (Some(msb), Some(lsb)) = (constant(msb), constant(lsb)) else {
return Err(unsupported(
"nonblocking assignment with a run-time position in a process",
));
};
let (Some(msb), Some(lsb)) = (
packed_index_offset(variable, msb),
packed_index_offset(variable, lsb),
) else {
return Err(unsupported("nonblocking assignment outside its target"));
Comment on lines +3309 to +3313

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Treat out-of-range constant NBA targets as no-ops

For a timed process containing a constant out-of-range bit select such as logic [7:0] q; initial #1 q[8] <= side_effect();, the select is a constant target but packed_index_offset returns None and this path rejects the entire design. SystemVerilog writes through an out-of-range bit select have no effect, while the RHS must still be evaluated; the existing blocking process path likewise returns successfully without storing. Preserve RHS evaluation and omit the corresponding update instead of reporting an unsupported target.

Useful? React with 👍 / 👎.

};
if msb < lsb {
return Err(unsupported(
"nonblocking assignment to a reversed part select in a process",
));
}
Ok((id, lsb, msb - lsb + 1))
}
}
}

/// `#amount` (IEEE 1800-2023 9.4.1). The amount is self-determined and
Expand Down Expand Up @@ -3401,6 +3516,13 @@ impl Ff<'_, '_> {
}
}

/// The kernel of a process and its wait and nonblocking assignment sites.
pub(super) struct KernelUnit {
pub unit: ExecutionUnit<Addr>,
pub wait_sites: Vec<WaitSite<SourceVarId>>,
pub nba_sites: Vec<NbaSite<SourceVarId>>,
}

/// Iterations, as a power of two, between the yields of a kernel loop that
/// may not suspend.
const LOOP_YIELD_BITS: usize = 16;
Expand Down
36 changes: 36 additions & 0 deletions crates/celox-test-suite/src/sv/cases/timing.vtest
Original file line number Diff line number Diff line change
Expand Up @@ -429,6 +429,42 @@
(assert_eq cnt_gated 3 "so does a clock computed from it")
(assert_eq cnt_derived 3 "and a falling one through an inverter"))

(case nonblocking_assignments_in_processes_update_in_the_nba_region
(source "process_nba.sv" #"
module Top(output logic [7:0] q, early, late, bus, hi, lo, d, sampled);
logic clk = 1'b0;
always #5 clk = ~clk;
initial begin
q = 8'd0;
bus = 8'd0;
#1;
q <= 8'd1;
q <= 8'd2;
#0 early = q;
bus[7:4] <= 4'ha;
{hi, lo} <= 16'h1234;
#1 late = q;
end
// A stimulus process and a register sampling it at the same edge.
initial begin
d = 8'd0;
forever @(posedge clk) d <= d + 8'd1;
end
always_ff @(posedge clk) sampled <= d;
endmodule"#)
(top Top)
(run_until 1)
(assert_eq early 0 "a nonblocking update lands after the inactive region")
(assert_eq q 2 "the last update of a time slot wins")
(assert_eq bus 0xa0)
(assert_eq hi 0x12)
(assert_eq lo 0x34)
(run_until 2)
(assert_eq late 2)
(run_until 26)
(assert_eq d 3)
(assert_eq sampled 2 "the register samples the value before the edge's update"))

(case nonblocking_ff_stores_remain_pending_during_inactive_work
(source "nonblocking.sv" #"module Top(output bit [7:0] q, observed, derived_seen);
bit clk; wire [7:0] derived=q+1;
Expand Down
20 changes: 20 additions & 0 deletions crates/celox/tests/frontends/systemverilog/review_regressions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -899,6 +899,26 @@ fn applies_unsigned_coercion_to_typed_parameter_comparisons() {
assert_eq!(sim.get(sim.signal("all_ones")), 1u8.into());
}

/// Nonblocking assignments in processes whose target bits are not known at
/// compile time are not lowered yet; they are rejected by name.
#[test]
fn rejects_process_nonblocking_assignments_without_a_constant_target() {
for (body, construct) in [
(
"logic [7:0] q; logic [2:0] i; initial #1 q[i] <= 1'b1;",
"nonblocking assignment with a run-time position in a process",
),
(
"logic [7:0] mem [4]; initial #1 mem[1] <= 8'd1;",
"nonblocking assignment to an unpacked array in a process",
),
] {
let source = format!("module Top; {body} endmodule");
let error = cranelift_build_error(&source);
assert!(error.contains(construct), "`{body}`: {error}");
}
}

#[test]
fn compile_sv_to_sir_forwards_parameter_overrides() {
let source = r#"
Expand Down
Loading
Loading