diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs
index 385e71c53f8..317862aa516 100644
--- a/crates/celox-design/src/lib.rs
+++ b/crates/celox-design/src/lib.rs
@@ -613,12 +613,13 @@ pub struct NbaSite {
/// Two-state staging object holding a bit offset added to `lsb`, for an
/// assignment whose position is computed at run time.
pub offset: Option,
- /// One-bit flag of a site whose destination receives no other
- /// nonblocking assignment: a variable of the module with no other
- /// nonblocking site in the module and no writer outside it (not a port,
- /// not bound to a package variable, not the target of a hierarchical
- /// reference). A frontend that cannot tell leaves it `None`, so the
- /// assignment goes through the ordered queue.
+ /// One-bit flag of a site whose destination has no other writer in the
+ /// design (no other nonblocking site, no store of any unit, not a
+ /// top-level port) and whose update order nothing observes (no wait,
+ /// counter, event domain or combinational observer reads it, directly
+ /// or through combinational logic): publication places flagged updates
+ /// after the queued ones. Without the flag the assignment goes through
+ /// the ordered queue.
///
/// The kernel stages the value and sets the flag without returning;
/// publication commits flagged sites and clears the flags. A kernel
diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs
index 4c9fa3cfe8e..a34363cb372 100644
--- a/crates/celox-frontend-core/src/process.rs
+++ b/crates/celox-frontend-core/src/process.rs
@@ -287,6 +287,55 @@ impl ProcessKernelBuilder {
Ok(())
}
+ /// A nonblocking update of `site` with two paths that a load of the
+ /// one-bit variable `switch` selects. With the switch set, the value
+ /// `lower` computes is staged as [`Self::nonblocking`] does for a site
+ /// with a `pending` flag. Otherwise the kernel returns
+ /// [`ProcessStatus::Nba`] at once, for a site whose value object already
+ /// holds the value. A frontend emits both before the whole design shows
+ /// which one may be used; assembly keeps one
+ /// (`crate::symbolic::artifact::NbaSwitch`).
+ pub fn nonblocking_switched>(
+ &mut self,
+ index: u32,
+ site: &NbaSite,
+ switch: SourceVarId,
+ lower: impl FnOnce(
+ &mut SIRBuilder,
+ ) -> Result<(RegisterId, Option), E>,
+ ) -> Result<(), E> {
+ assert!(
+ site.pending.is_some(),
+ "a switched nonblocking site has a pending flag"
+ );
+ let on = self.builder.alloc_bit(1, false);
+ self.builder.emit(SIRInstruction::Load(
+ on,
+ stable(switch),
+ SIROffset::Static(0),
+ 1,
+ ));
+ let staged = self.builder.new_block();
+ let queued = self.builder.new_block();
+ let join = self.builder.new_block();
+ self.builder.seal_block(SIRTerminator::Branch {
+ cond: on,
+ true_block: (staged, Vec::new()),
+ false_block: (queued, Vec::new()),
+ });
+ self.builder.switch_to_block(staged);
+ self.nonblocking(index, site, lower)?;
+ self.builder
+ .seal_block(SIRTerminator::Jump(join, Vec::new()));
+ self.builder.switch_to_block(queued);
+ self.store_delay_constant(u64::from(index));
+ self.suspend(ProcessStatus::Nba)?;
+ self.builder
+ .seal_block(SIRTerminator::Jump(join, Vec::new()));
+ self.builder.switch_to_block(join);
+ Ok(())
+ }
+
/// End the simulation. No block is open afterwards.
pub fn finish(&mut self) {
self.wait_site = None;
diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs
index 6c6f6e61d6a..6b78ba0c17c 100644
--- a/crates/celox-frontend-core/src/sdk.rs
+++ b/crates/celox-frontend-core/src/sdk.rs
@@ -1936,6 +1936,7 @@ pub fn lower_frontend_artifact(
counter_slots,
wait_sites,
nba_sites,
+ nba_switches: Vec::new(),
host_request_sites: Vec::new(),
time_slot: None,
};
diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs
index d190ccf2758..d1e7231593b 100644
--- a/crates/celox-frontend-core/src/symbolic/artifact.rs
+++ b/crates/celox-frontend-core/src/symbolic/artifact.rs
@@ -122,6 +122,8 @@ pub struct SimModule {
/// Nonblocking sites of the module's processes; `process` indexes
/// [`Self::processes`].
pub nba_sites: Vec>,
+ /// Nonblocking sites whose kernel has both a staged and a queued path.
+ pub nba_switches: Vec>,
/// Synchronous host operations of the module processes.
pub host_request_sites: Vec>,
/// The variable through which the module's code reads the simulation
@@ -129,6 +131,34 @@ pub struct SimModule {
pub time_slot: Option,
}
+/// A nonblocking site whose kernel has two paths, as
+/// `ProcessKernelBuilder::nonblocking_switched` builds them. The staged path
+/// stages the value in the site's `value` and sets its `pending` flag; the
+/// queued path leaves the value in `queued` and returns to the runtime.
+/// Assembly keeps one path: the staged one only if nothing else writes the
+/// site's target and nothing can observe when the target is updated. For the
+/// queued path it makes `queued` the site's value and drops the flag.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct NbaSwitch {
+ /// The site's `value` object, which identifies the site.
+ pub value: A,
+ /// The one-bit variable whose load selects the path. It holds no state:
+ /// assembly replaces the selection by a jump.
+ pub switch: A,
+ /// The value object of the queued path.
+ pub queued: A,
+}
+
+impl NbaSwitch {
+ pub fn map(&self, mut map: impl FnMut(&A) -> B) -> NbaSwitch {
+ NbaSwitch {
+ value: map(&self.value),
+ switch: map(&self.switch),
+ queued: map(&self.queued),
+ }
+ }
+}
+
/// The package variable a module variable denotes.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct PackageBinding {
diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs
index 450145040e9..c851603fe8c 100644
--- a/crates/celox-frontend-core/src/symbolic/assembly.rs
+++ b/crates/celox-frontend-core/src/symbolic/assembly.rs
@@ -2,7 +2,8 @@ use num_bigint::BigUint;
use std::collections::{BTreeMap, BTreeSet};
use crate::symbolic::artifact::{
- FfPart, RelocationModule, SimModule, SplitCommit, SymbolicGlueAddr as GlueAddr, SymbolicRtl,
+ FfPart, NbaSwitch, RelocationModule, SimModule, SplitCommit, SymbolicGlueAddr as GlueAddr,
+ SymbolicRtl,
};
use crate::{
FrontendLookup, FrontendTrace, FrontendTraceOptions, FusedSirOptimizationHints, HashMap,
@@ -18,8 +19,8 @@ use celox_design::{
VariableMetadata, WaitSite,
};
use celox_sir::{
- BasicBlock, ExecutionUnit, LaneUnit, ParallelSirProgram, SIRInstruction, SIRTerminator,
- SirProgram,
+ BasicBlock, ExecutionUnit, LaneUnit, ParallelSirProgram, SIRInstruction, SIROffset,
+ SIRTerminator, SirProgram,
};
use celox_slt::{
CombObserver, FfAccessSummary, LogicPath, LogicPathId, LogicPathTarget, NodeId, SLTNodeArena,
@@ -680,7 +681,7 @@ pub fn schedule_symbolic_rtl(
&mut trace,
)
)?;
- let timing = relocate_timing(bindings, &instance_modules, &modules, &processes);
+ let mut timing = relocate_timing(bindings, &instance_modules, &modules, &processes);
let variables: HashMap = instance_modules
.iter()
.flat_map(|(&instance, module)| {
@@ -1575,6 +1576,73 @@ pub fn schedule_symbolic_rtl(
written_inputs: observer.written_inputs.clone(),
})
.collect();
+ // Nonblocking sites that can stage their value instead of queueing it
+ // (`NbaSite::pending`). Staged values are published after the queue,
+ // so a staged target must be one whose update order nothing observes:
+ // no wait, counter, event domain or comb observer reads it, directly or
+ // through combinational logic.
+ if !timing.nba_switches.is_empty() {
+ let observed = {
+ let mut observed: HashSet = timing
+ .wait_sites
+ .iter()
+ .flat_map(|site| site.terms.iter().map(|(signal, _)| *signal))
+ .chain(timing.counter_slots.iter().map(|slots| slots.signal))
+ .chain(
+ clock_domains
+ .iter()
+ .flat_map(|(&alias, &canonical)| [alias, canonical]),
+ )
+ .chain(topological_clocks.iter().copied())
+ .chain(
+ runtime_comb_observers
+ .iter()
+ .flat_map(|observer| observer.sensitivity.iter().map(|atom| atom.id)),
+ )
+ .collect();
+ for ffs in [
+ &eval_apply_ffs,
+ &eval_comb_apply_ffs,
+ &eval_only_ffs,
+ &apply_ffs,
+ ] {
+ observed.extend(ffs.keys().copied());
+ }
+ through_comb(observed, &comb_sources)
+ };
+ // The ports of the top module, which the host drives.
+ let top_ports: HashSet = expanded
+ .get(&InstancePath(Vec::new()))
+ .map(|&root| {
+ modules[&instance_modules[&root]]
+ .variables
+ .iter()
+ .filter(|(_, variable)| {
+ matches!(
+ variable.kind,
+ crate::VariableKind::Input
+ | crate::VariableKind::Output
+ | crate::VariableKind::Inout
+ )
+ })
+ .map(|(&var_id, _)| bindings.locate(root, var_id))
+ .collect()
+ })
+ .unwrap_or_default();
+ let staged = staged_nba_sites(
+ &timing,
+ eval_comb
+ .iter()
+ .chain(eval_apply_ffs.values().flatten())
+ .chain(eval_comb_apply_ffs.values().flatten())
+ .chain(eval_only_ffs.values().flatten())
+ .chain(apply_ffs.values().flatten())
+ .chain(processes.iter().map(|process| &process.kernel)),
+ &top_ports,
+ &observed,
+ );
+ select_nba_paths(&mut timing, &staged, &mut processes);
+ }
let (process_kernels, process_slots): (Vec<_>, Vec<_>) = processes
.into_iter()
.map(|process| (process.kernel, process.slots))
@@ -3104,6 +3172,7 @@ struct TimingMetadata {
nba_sites: Vec>,
host_request_sites: Vec>,
time_slots: Vec,
+ nba_switches: Vec>,
}
/// For every combinational value, the variables it is computed from.
@@ -3239,6 +3308,156 @@ fn split_observed_commits<'k>(
split
}
+/// The switches of the switched nonblocking sites that may stage their
+/// value: the site's target has no other writer (no store or commit of any
+/// unit, no other nonblocking site, not a top-level port the host drives)
+/// and is not in `observed`.
+fn staged_nba_sites<'u>(
+ timing: &TimingMetadata,
+ units: impl Iterator- >,
+ top_ports: &HashSet,
+ observed: &HashSet,
+) -> HashSet {
+ let mut written = HashSet::default();
+ for unit in units {
+ for block in unit.blocks.values() {
+ for instruction in &block.instructions {
+ match instruction {
+ SIRInstruction::Store(dst, ..) | SIRInstruction::Commit(_, dst, ..) => {
+ written.insert(dst.absolute_addr());
+ }
+ _ => {}
+ }
+ }
+ }
+ }
+ let mut sites_per_target: HashMap = HashMap::default();
+ for site in &timing.nba_sites {
+ *sites_per_target.entry(site.target).or_default() += 1;
+ }
+ let targets: HashMap = timing
+ .nba_sites
+ .iter()
+ .map(|site| (site.value, site.target))
+ .collect();
+ timing
+ .nba_switches
+ .iter()
+ .filter(|switch| {
+ let target = targets[&switch.value];
+ sites_per_target[&target] == 1
+ && !written.contains(&target)
+ && !top_ports.contains(&target)
+ && !observed.contains(&target)
+ })
+ .map(|switch| switch.switch)
+ .collect()
+}
+
+/// Keep one path of every switched nonblocking site: the staged one if its
+/// switch is in `staged`, otherwise the queued one, whose value object
+/// becomes the site's and which has no `pending` flag. The kernels select
+/// the path by a jump; the other path is removed.
+fn select_nba_paths(
+ timing: &mut TimingMetadata,
+ staged: &HashSet,
+ processes: &mut [RelocatedProcess],
+) {
+ let switches: HashMap> = timing
+ .nba_switches
+ .iter()
+ .map(|switch| (switch.value, *switch))
+ .collect();
+ for site in &mut timing.nba_sites {
+ let Some(switch) = switches.get(&site.value) else {
+ continue;
+ };
+ if !staged.contains(&switch.switch) {
+ site.value = switch.queued;
+ site.pending = None;
+ }
+ }
+ let selections: HashMap = switches
+ .values()
+ .map(|switch| (switch.switch, staged.contains(&switch.switch)))
+ .collect();
+ let mut folded = 0;
+ for process in processes {
+ folded += fold_nba_switches(&mut process.kernel, &selections);
+ }
+ assert_eq!(
+ folded,
+ selections.len(),
+ "every nonblocking switch selects its path once"
+ );
+}
+
+/// Replace each branch on a load of a switch in `selections` by a jump to
+/// the selected path and remove the blocks no longer reachable. Returns the
+/// number of branches replaced.
+fn fold_nba_switches(
+ unit: &mut ExecutionUnit,
+ selections: &HashMap,
+) -> usize {
+ let mut folded = 0;
+ for block in unit.blocks.values_mut() {
+ let SIRTerminator::Branch {
+ cond,
+ true_block,
+ false_block,
+ } = &block.terminator
+ else {
+ continue;
+ };
+ let Some((position, staged)) =
+ block
+ .instructions
+ .iter()
+ .enumerate()
+ .find_map(|(position, instruction)| match instruction {
+ SIRInstruction::Load(register, addr, SIROffset::Static(0), 1)
+ if register == cond =>
+ {
+ selections
+ .get(&addr.absolute_addr())
+ .map(|&staged| (position, staged))
+ }
+ _ => None,
+ })
+ else {
+ continue;
+ };
+ let (target, args) = if staged { true_block } else { false_block };
+ block.terminator = SIRTerminator::Jump(*target, args.clone());
+ block.instructions.remove(position);
+ folded += 1;
+ }
+ if folded > 0 {
+ let mut reachable = HashSet::default();
+ let mut pending = vec![unit.entry_block_id];
+ while let Some(id) = pending.pop() {
+ if !reachable.insert(id) {
+ continue;
+ }
+ match &unit.blocks[&id].terminator {
+ SIRTerminator::Jump(next, _) => pending.push(*next),
+ SIRTerminator::Branch {
+ true_block,
+ false_block,
+ ..
+ } => pending.extend([true_block.0, false_block.0]),
+ SIRTerminator::Switch { cases, default, .. } => {
+ pending.extend(cases.iter().map(|case| case.target));
+ pending.push(*default);
+ }
+ SIRTerminator::Return | SIRTerminator::Error(_) => {}
+ }
+ }
+ unit.blocks.retain(|id, _| reachable.contains(id));
+ }
+ folded
+}
+
/// Place the timing metadata of every instance. Sites name the global index
/// of their process; a kernel numbers its sites in the order they appear
/// here, which is the module's order.
@@ -3261,6 +3480,7 @@ fn relocate_timing(
nba_sites: Vec::new(),
host_request_sites: Vec::new(),
time_slots: Vec::new(),
+ nba_switches: Vec::new(),
};
for (&instance, module) in instances {
let module = &modules[module];
@@ -3292,6 +3512,12 @@ fn relocate_timing(
}),
);
metadata.time_slots.extend(module.time_slot.map(locate));
+ metadata.nba_switches.extend(
+ module
+ .nba_switches
+ .iter()
+ .map(|switch| switch.map(|&var| locate(var))),
+ );
}
metadata
}
diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs
index 908fa9d4863..a110471a6e4 100644
--- a/crates/celox-frontend-sv/src/lowering.rs
+++ b/crates/celox-frontend-sv/src/lowering.rs
@@ -18,8 +18,8 @@ use celox_design::{
};
use celox_frontend_core::process::PROCESS_RESUME_WIDTH;
use celox_frontend_core::symbolic::artifact::{
- ExternalHierarchy, ExternalModule, PackageBinding, SimModule, SymbolicGlueAddr as GlueAddr,
- SymbolicProcess, SymbolicRtl, SymbolicVariable,
+ ExternalHierarchy, ExternalModule, NbaSwitch, PackageBinding, SimModule,
+ SymbolicGlueAddr as GlueAddr, SymbolicProcess, SymbolicRtl, SymbolicVariable,
};
use celox_frontend_core::{
FrontendTrace, FrontendTraceOptions, LoweringPhase, ParserError, ScheduledRtlOutput,
@@ -2892,6 +2892,7 @@ fn lower_module_with_overrides(
processes,
wait_sites,
nba_sites,
+ nba_switches,
host_request_sites,
event_assignments,
) = lower_initial_processes(
@@ -3010,6 +3011,7 @@ fn lower_module_with_overrides(
counter_slots: Vec::new(),
wait_sites,
nba_sites,
+ nba_switches,
host_request_sites,
time_slot: name_to_id.get(TIME_SLOT).copied(),
},
@@ -3751,6 +3753,7 @@ fn lower_initial_processes(
Vec,
Vec>,
Vec>,
+ Vec>,
Vec>,
Vec<(SourceVarId, Vec)>,
),
@@ -3826,6 +3829,7 @@ fn lower_initial_processes(
Vec::new(),
Vec::new(),
Vec::new(),
+ Vec::new(),
));
}
@@ -3890,6 +3894,7 @@ fn lower_initial_processes(
pm.extern_functions = std::mem::take(extern_functions);
let mut wait_sites = Vec::new();
let mut nba_sites = Vec::new();
+ let mut nba_switches = Vec::new();
let mut host_request_sites = Vec::new();
let processes = runtime
.into_iter()
@@ -3903,6 +3908,7 @@ fn lower_initial_processes(
)?;
wait_sites.extend(kernel.wait_sites);
nba_sites.extend(kernel.nba_sites);
+ nba_switches.extend(kernel.nba_switches);
host_request_sites.extend(kernel.host_request_sites.into_iter().map(|mut site| {
site.process = index;
// Repeating ordinary always processes also execute only in
@@ -3927,6 +3933,7 @@ fn lower_initial_processes(
processes?,
wait_sites,
nba_sites,
+ nba_switches,
host_request_sites,
std::mem::take(&mut pm.event_assignments),
))
diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs
index 860fdbc1da6..be88d48e7c8 100644
--- a/crates/celox-frontend-sv/src/lowering/ff.rs
+++ b/crates/celox-frontend-sv/src/lowering/ff.rs
@@ -72,6 +72,8 @@ pub(super) struct Ff<'p, 'a> {
/// The nonblocking assignment sites of the process, by local index.
nba_sites: Vec>,
host_request_sites: Vec>,
+ /// The nonblocking sites with a staged and a queued path.
+ nba_switches: Vec>,
direct: bool,
}
@@ -122,6 +124,7 @@ impl<'p, 'a> Ff<'p, 'a> {
wait_sites: Vec::new(),
nba_sites: Vec::new(),
host_request_sites: Vec::new(),
+ nba_switches: Vec::new(),
}
}
@@ -2600,8 +2603,9 @@ impl<'p, 'a> Ff<'p, 'a> {
sv::ir::Stmt::Delay {
amount,
ticks_per_unit,
+ ticks_per_precision,
} => {
- self.delay(amount, *ticks_per_unit)?;
+ self.delay(amount, *ticks_per_unit, *ticks_per_precision)?;
Ok(true)
}
sv::ir::Stmt::WaitEvent(items) => {
@@ -4239,6 +4243,7 @@ impl Ff<'_, '_> {
wait_sites: self.wait_sites,
nba_sites: self.nba_sites,
host_request_sites: self.host_request_sites,
+ nba_switches: self.nba_switches,
})
}
@@ -4276,19 +4281,25 @@ impl Ff<'_, '_> {
},
)?;
high = low;
+ // The staged value has an object of its own: a value still
+ // staged from earlier in the time slot is queued before it is
+ // replaced. Assembly keeps the staged or the queued path.
+ let staged_four_state = self.m.var(staged).is_4state;
+ let (value, _) = self.m.temp("nba_value", width, false, staged_four_state);
+ let (pending, _) = self.m.temp("nba_pending", 1, false, false);
+ let (switch, _) = self.m.temp("nba_staged", 1, false, false);
let site = NbaSite {
process: self.process,
target: id,
lsb,
width,
- value: staged,
+ value,
offset: None,
- pending: None,
+ pending: Some(pending),
};
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| {
+ kernel.nonblocking_switched(index, &site, switch, |builder| {
let value = if staged_four_state {
builder.alloc_logic(width)
} else {
@@ -4304,6 +4315,11 @@ impl Ff<'_, '_> {
})
})
.map_err(kernel_error)?;
+ self.nba_switches.push(NbaSwitch {
+ value,
+ switch,
+ queued: staged,
+ });
self.nba_sites.push(site);
}
Ok(())
@@ -4364,21 +4380,30 @@ impl Ff<'_, '_> {
&mut self,
amount: &sv::ir::Expr,
ticks_per_unit: u64,
+ ticks_per_precision: u64,
) -> Result<(), sv::AnalyzerError> {
- let signed = self.expr_signed(amount);
- let mut arena = SLTNodeArena::new();
- let node = self.expr_slt(amount, None, &mut arena)?;
- let original = self.lower_slt(&arena, node)?;
- let node = coerce_node_width(&mut arena, node, Some(PROCESS_DELAY_WIDTH), signed)
- .map_err(slt_error)?;
- let delay = self.lower_slt(&arena, node)?;
- let mut delay = self.zero_if_unknown(delay, original);
- if ticks_per_unit > 1 {
+ let (mut delay, ticks_per_step) = match self.m.expr_float_precision(amount) {
+ Some(precision) => (
+ self.real_delay(amount, precision, ticks_per_unit / ticks_per_precision)?,
+ ticks_per_precision,
+ ),
+ None => {
+ let signed = self.expr_signed(amount);
+ let mut arena = SLTNodeArena::new();
+ let node = self.expr_slt(amount, None, &mut arena)?;
+ let original = self.lower_slt(&arena, node)?;
+ let node = coerce_node_width(&mut arena, node, Some(PROCESS_DELAY_WIDTH), signed)
+ .map_err(slt_error)?;
+ let delay = self.lower_slt(&arena, node)?;
+ (self.zero_if_unknown(delay, original), ticks_per_unit)
+ }
+ };
+ if ticks_per_step > 1 {
// Check before multiplying so the 64-bit delay slot cannot wrap.
let limit = self.b.alloc_bit(PROCESS_DELAY_WIDTH, false);
self.b.emit(SIRInstruction::Imm(
limit,
- SIRValue::new(u64::MAX / ticks_per_unit),
+ SIRValue::new(u64::MAX / ticks_per_step),
));
let overflow = self.b.alloc_bit(1, false);
self.b.emit(SIRInstruction::Binary(
@@ -4402,7 +4427,7 @@ impl Ff<'_, '_> {
self.b.switch_to_block(scaled);
let factor = self.b.alloc_bit(PROCESS_DELAY_WIDTH, false);
self.b
- .emit(SIRInstruction::Imm(factor, SIRValue::new(ticks_per_unit)));
+ .emit(SIRInstruction::Imm(factor, SIRValue::new(ticks_per_step)));
let product = self.b.alloc_bit(PROCESS_DELAY_WIDTH, false);
self.b.emit(SIRInstruction::Binary(
product,
@@ -4416,6 +4441,42 @@ impl Ff<'_, '_> {
.map_err(kernel_error)
}
+ /// A real delay `amount` in precision steps of the declaring scope:
+ /// scaled from time units by `steps_per_unit`, rounded to the nearest
+ /// step with ties away from zero (3.14.1, 6.12.1), and read as an
+ /// unsigned 64-bit time like an integral delay (9.4.1). A NaN or
+ /// infinite delay is zero, as an unknown integral one is.
+ fn real_delay(
+ &mut self,
+ amount: &sv::ir::Expr,
+ precision: celox_sir::FloatPrecision,
+ steps_per_unit: u64,
+ ) -> Result {
+ let scaled = if steps_per_unit > 1 {
+ sv::ir::Expr::Binary {
+ left: Box::new(amount.clone()),
+ op: sv::ir::BinaryOp::Mul,
+ right: Box::new(sv::ir::Expr::Literal(format!("{steps_per_unit}.0"))),
+ }
+ } else {
+ amount.clone()
+ };
+ let precision = self.m.expr_float_precision(&scaled).unwrap_or(precision);
+ let mut arena = SLTNodeArena::new();
+ let node = self.expr_slt(&scaled, None, &mut arena)?;
+ let node = floating::convert(
+ &mut arena,
+ node,
+ Some(precision),
+ None,
+ PROCESS_DELAY_WIDTH,
+ true,
+ true,
+ )
+ .ok_or_else(|| unsupported("real delay conversion"))?;
+ self.lower_slt(&arena, node)
+ }
+
/// `value` as a two-state register that is zero when `source` has an
/// unknown bit.
fn zero_if_unknown(&mut self, value: RegisterId, source: RegisterId) -> RegisterId {
@@ -4738,6 +4799,7 @@ pub(super) struct KernelUnit {
pub wait_sites: Vec>,
pub nba_sites: Vec>,
pub host_request_sites: Vec>,
+ pub nba_switches: Vec>,
}
/// Iterations, as a power of two, between the yields of a kernel loop that
diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs
index 216018f79ad..f4fce2b13c3 100644
--- a/crates/celox-frontend-veryl/src/artifact.rs
+++ b/crates/celox-frontend-veryl/src/artifact.rs
@@ -666,6 +666,7 @@ pub(crate) fn project_module_with_ids(
counter_slots: Vec::new(),
wait_sites: Vec::new(),
nba_sites: Vec::new(),
+ nba_switches: Vec::new(),
host_request_sites: Vec::new(),
time_slot: None,
},
diff --git a/crates/celox-runtime/src/simulation/nba.rs b/crates/celox-runtime/src/simulation/nba.rs
index 5db8c839eda..7110263524e 100644
--- a/crates/celox-runtime/src/simulation/nba.rs
+++ b/crates/celox-runtime/src/simulation/nba.rs
@@ -42,7 +42,8 @@ impl SimulationState {
}
/// Publish the queued and flagged nonblocking assignments of process
- /// kernels (the NBA region, IEEE 1800-2023 4.5).
+ /// kernels (the NBA region, IEEE 1800-2023 4.5): the queued ones in
+ /// issue order, then the flagged ones.
pub(super) fn publish_nba(&mut self, executor: &mut E, round: &mut Round) -> bool
where
E: SimulationExecutor,
@@ -51,15 +52,44 @@ impl SimulationState {
return false;
}
round.nba_published = true;
- let flagged = round.kernels_ran && self.model.has_pending_nba_sites;
- if self.process_state.nba_queue.is_empty() && !flagged {
+ let flagged = if round.kernels_ran && self.model.has_pending_nba_sites {
+ let backend = executor.backend();
+ self.model
+ .processes
+ .iter()
+ .flat_map(|process| &process.nba_sites)
+ .filter_map(|site| site.pending)
+ .filter(|&pending| backend.get_as::(pending) != 0)
+ .count()
+ } else {
+ 0
+ };
+ let mut queued = std::mem::take(&mut self.process_state.nba_queue);
+ if queued.is_empty() && flagged == 0 {
+ self.process_state.nba_queue = queued;
return false;
}
- let mut updates = std::mem::take(&mut self.process_state.nba_queue);
- if flagged {
- let backend = executor.backend_mut();
- for process in &self.model.processes {
- for site in &process.nba_sites {
+ // Several updates may pulse an event signal: each is an update the
+ // event domains see, not only the final value.
+ let several = queued.len() + flagged > 1;
+ if several {
+ self.event_values(executor.backend(), &mut round.before);
+ round.transitions.clear();
+ }
+ for update in queued.drain(..) {
+ let new = NbaValue::Queued(&update.value);
+ self.publish_update(executor.backend_mut(), &update, new);
+ if several {
+ self.record_transitions(executor.backend(), round);
+ }
+ }
+ // Keep the queue's storage for the next time slot.
+ self.process_state.nba_queue = queued;
+ if flagged > 0 {
+ for process in 0..self.model.processes.len() {
+ for site in 0..self.model.processes[process].nba_sites.len() {
+ let site = self.model.processes[process].nba_sites[site];
+ let backend = executor.backend_mut();
let Some(pending) = site.pending else {
continue;
};
@@ -70,40 +100,19 @@ impl SimulationState {
let offset = site
.offset
.map_or(0, |offset| backend.get_as::(offset) as usize);
- updates.push(NbaUpdate {
+ let update = NbaUpdate {
target: site.target,
lsb: site.lsb + offset,
width: site.width,
- value: read(backend, site.value),
- });
+ value: Value::default(),
+ };
+ self.publish_update(backend, &update, NbaValue::Staged(site.value));
+ if several {
+ self.record_transitions(executor.backend(), round);
+ }
}
}
}
- if updates.is_empty() {
- return false;
- }
- // Several updates may pulse an event signal: each is an update the
- // event domains see, not only the final value.
- let several = updates.len() > 1;
- if several {
- self.event_values(executor.backend(), &mut round.before);
- round.transitions.clear();
- }
- for update in updates {
- let backend = executor.backend_mut();
- let merged = update.merge_into(&read(backend, update.target));
- let target = update.target;
- self.write_signal(backend, target, |backend| {
- if target.is_4state {
- backend.set_four_state(target, merged.0, merged.1);
- } else {
- backend.set_wide(target, merged.0);
- }
- });
- if several {
- self.record_transitions(executor.backend(), round);
- }
- }
if several {
let transitions = std::mem::take(&mut round.transitions);
self.mark_occurrences(executor.backend_mut(), round, &transitions);
@@ -113,6 +122,55 @@ impl SimulationState {
round.track_stable_edges = true;
true
}
+
+ /// Write `update`, whose value is `new`, into its target. An update
+ /// inside a target of at most 64 bits with one state plane is merged as
+ /// `u64`; any other as [`Value`].
+ fn publish_update(&mut self, backend: &mut B, update: &NbaUpdate, new: NbaValue<'_>) {
+ let target = update.target;
+ let narrow = |signal: SignalRef| {
+ signal.width <= 64
+ && signal.array_layout.is_none()
+ && !(self.four_state && signal.is_4state)
+ };
+ let inside = update.lsb + update.width <= target.width && narrow(target);
+ let new = match new {
+ NbaValue::Queued(value) if inside => Ok(value.0.iter_u64_digits().next().unwrap_or(0)),
+ NbaValue::Staged(value) if inside && narrow(value) => Ok(backend.get_as::(value)),
+ NbaValue::Queued(value) => Err(value.clone()),
+ NbaValue::Staged(value) => Err(read(backend, value)),
+ };
+ match new {
+ Ok(new) => {
+ let all = low_bits(target.width);
+ let old = backend.get_as::(target) & all;
+ let merged = update.merge_narrow(old, new);
+ self.write_signal(backend, target, |backend| backend.set(target, merged));
+ }
+ Err(value) => {
+ let merged = NbaUpdate { value, ..*update }.merge_into(&read(backend, target));
+ self.write_signal(backend, target, |backend| {
+ if target.is_4state {
+ backend.set_four_state(target, merged.0, merged.1);
+ } else {
+ backend.set_wide(target, merged.0);
+ }
+ });
+ }
+ }
+ }
+}
+
+/// The value of a nonblocking update: queued, or staged in a site's value
+/// object.
+enum NbaValue<'a> {
+ Queued(&'a Value),
+ Staged(SignalRef),
+}
+
+/// The low `width` bits of a `u64`, for `width` up to 64.
+fn low_bits(width: usize) -> u64 {
+ u64::MAX >> (64 - width)
}
/// The working and sparse working state: the next-state values of
@@ -156,4 +214,49 @@ impl NbaUpdate {
place(&target.1, &self.value.1),
)
}
+
+ /// [`Self::merge_into`] for a target of at most 64 bits with one state
+ /// plane: the bits of the target's value `old` with `new` written in.
+ fn merge_narrow(&self, old: u64, new: u64) -> u64 {
+ let all = low_bits(self.target.width);
+ let range = (low_bits(self.width) << self.lsb) & all;
+ ((old & !range) | ((new << self.lsb) & range)) & all
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn narrow_merges_match_wide_merges() {
+ let patterns = [0u64, u64::MAX, 0xa5a5_5a5a_0f0f_f0f0, 0x8000_0000_0000_0001];
+ for target_width in [1, 7, 8, 9, 16, 33, 63, 64] {
+ for lsb in 0..target_width {
+ for width in 1..=target_width - lsb {
+ for (old, new) in patterns.iter().zip(patterns.iter().rev()) {
+ let all = low_bits(target_width);
+ let update = NbaUpdate {
+ target: SignalRef {
+ offset: 0,
+ width: target_width,
+ is_4state: false,
+ array_layout: None,
+ },
+ lsb,
+ width,
+ value: (BigUint::from(new & low_bits(width)), BigUint::default()),
+ };
+ let wide =
+ update.merge_into(&(BigUint::from(old & all), BigUint::default()));
+ assert_eq!(
+ BigUint::from(update.merge_narrow(old & all, *new)),
+ wide.0,
+ "target {target_width}, lsb {lsb}, width {width}"
+ );
+ }
+ }
+ }
+ }
+ }
}
diff --git a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs
index 70494ce65d2..1389fa550f7 100644
--- a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs
+++ b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs
@@ -20,11 +20,13 @@ impl BodyBuilder<'_, '_, '_> {
return Ok(Stmt::Delay {
amount: Expr::Literal(format!("64'd{ticks}")),
ticks_per_unit: 1,
+ ticks_per_precision: 1,
});
}
Ok(Stmt::Delay {
amount: self.native_delay(*value, *parenthesized)?,
ticks_per_unit: timescales::time_divisor(*value, self.tree)?,
+ ticks_per_precision: timescales::precision_divisor(*value, self.tree)?,
})
}
TimingControlKind::Event(event) => {
@@ -87,6 +89,13 @@ impl BodyBuilder<'_, '_, '_> {
ExprKind::Literal(text) if text.chars().all(|c| c.is_ascii_digit() || c == '_') => {
Ok(Expr::Literal(text.replace('_', "")))
}
+ // A real_number delay value such as `#1.5` (A.2.2.3).
+ ExprKind::Literal(text)
+ if text.contains(['.', 'e', 'E'])
+ && text.replace('_', "").parse::().is_ok() =>
+ {
+ Ok(Expr::Literal(text.replace('_', "")))
+ }
ExprKind::Name(name) => {
let mut result = Expr::Ident(instances::normalize_identifier(&name.spelling));
self.rename_expr(&mut result);
diff --git a/crates/celox-sv-analyzer/src/ast/timescales.rs b/crates/celox-sv-analyzer/src/ast/timescales.rs
index 6a2096d3e65..7399cb91030 100644
--- a/crates/celox-sv-analyzer/src/ast/timescales.rs
+++ b/crates/celox-sv-analyzer/src/ast/timescales.rs
@@ -794,12 +794,24 @@ impl Timescales {
/// The time units of the simulation, which counts the global time
/// precision (3.14.3), in one time unit of the scope of `node`.
fn time_divisor_in_unit(&self, at: usize, unit: &Unit) -> u64 {
+ self.ticks_in(at, unit, |scale| scale.unit)
+ }
+
+ /// The time units of the simulation in one time precision step of the
+ /// scope of `node` (3.14.1).
+ fn precision_divisor_in_unit(&self, at: usize, unit: &Unit) -> u64 {
+ self.ticks_in(at, unit, |scale| scale.precision)
+ }
+
+ /// The time units of the simulation in `10^exponent(scale)` seconds,
+ /// where `scale` is the time scale of the scope at `at`.
+ fn ticks_in(&self, at: usize, unit: &Unit, exponent: impl Fn(&Scale) -> i32) -> u64 {
let scale =
scope_at(&unit.scopes, &unit.parents, at).map_or(unit.scale, |i| unit.scopes[i].scale);
let precision = self.precision.unwrap_or(DEFAULT.precision);
// A scope's precision is not coarser than its unit, and no unit is
// longer than 100 s or precision finer than 1 fs.
- 10u64.pow((scale.unit - precision.min(scale.precision)) as u32)
+ 10u64.pow((exponent(&scale) - precision.min(scale.precision)) as u32)
}
fn resolve(
@@ -1009,27 +1021,37 @@ pub(super) fn time_divisor(
node: celox_sv_syntax::ExprId,
tree: &AnalysisContext<'_>,
) -> Converted {
+ divisor(node, tree, Timescales::time_divisor_in_unit)
+}
+
+/// The simulation's time units in one time precision step of the scope of
+/// `node`, at which a real delay is rounded (3.14.1).
+pub(super) fn precision_divisor(
+ node: celox_sv_syntax::ExprId,
+ tree: &AnalysisContext<'_>,
+) -> Converted {
+ divisor(node, tree, Timescales::precision_divisor_in_unit)
+}
+
+fn divisor(
+ node: celox_sv_syntax::ExprId,
+ tree: &AnalysisContext<'_>,
+ in_unit: fn(&Timescales, usize, &Unit) -> u64,
+) -> Converted {
+ let context = tree.state.timescales.design.borrow();
+ let at = tree.declarations().expression(node).tokens.start;
+ if let Some(prepared) = &context.prepared
+ && prepared.address == tree.syntax_tree as *const SyntaxTree as usize
{
- let context = tree.state.timescales.design.borrow();
- if let Some(prepared) = &context.prepared
- && prepared.address == tree.syntax_tree as *const SyntaxTree as usize
- {
- return Ok(context.design.time_divisor_in_unit(
- tree.declarations().expression(node).tokens.start,
- &prepared.unit,
- ));
- }
- let design = &context.design;
- let source = key(tree);
- let extended = (!design.units.contains_key(&source))
- .then(|| design.including_tree(tree))
- .transpose()?;
- let design = extended.as_ref().unwrap_or(design);
- Ok(design.time_divisor_in_unit(
- tree.declarations().expression(node).tokens.start,
- &design.units[&source],
- ))
+ return Ok(in_unit(&context.design, at, &prepared.unit));
}
+ let design = &context.design;
+ let source = key(tree);
+ let extended = (!design.units.contains_key(&source))
+ .then(|| design.including_tree(tree))
+ .transpose()?;
+ let design = extended.as_ref().unwrap_or(design);
+ Ok(in_unit(design, at, &design.units[&source]))
}
/// A standalone time literal used as a delay: round at the declaring
diff --git a/crates/celox-sv-analyzer/src/procedural.rs b/crates/celox-sv-analyzer/src/procedural.rs
index d3c5d154662..a5940ca627c 100644
--- a/crates/celox-sv-analyzer/src/procedural.rs
+++ b/crates/celox-sv-analyzer/src/procedural.rs
@@ -87,6 +87,9 @@ pub enum StmtBase {
amount: E,
/// Global-precision ticks in one time unit of the declaring scope.
ticks_per_unit: u64,
+ /// Global-precision ticks in one time precision step of the
+ /// declaring scope, to which a real amount is rounded (3.14.1).
+ ticks_per_precision: u64,
},
/// `@(items)`: suspend the process until one of the events occurs
/// (9.4.2).
@@ -304,9 +307,11 @@ impl StmtBase {
StmtBase::Delay {
amount,
ticks_per_unit,
+ ticks_per_precision,
} => StmtBase::Delay {
amount: fe(amount),
ticks_per_unit,
+ ticks_per_precision,
},
StmtBase::WaitEvent(items) => StmtBase::WaitEvent(
items
diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs
index 7f81f933cb9..c08bf462526 100644
--- a/crates/celox-sv-analyzer/src/tests.rs
+++ b/crates/celox-sv-analyzer/src/tests.rs
@@ -3509,7 +3509,6 @@ fn rejects_unimplemented_timing_constructs() {
"intra-assignment timing control",
),
("initial begin : b disable b; end", "disable statement"),
- ("initial #1.5;", "delay value"),
(
"logic a, y; always_latch y <= a;",
"nonblocking assignment inside always_latch",
@@ -6316,6 +6315,7 @@ fn time_literal_delays_accept_numeric_separators() {
let ir::Stmt::Delay {
amount,
ticks_per_unit,
+ ..
} = &ir.modules()[0].initial_processes()[0].body()[0]
else {
panic!("delay");
diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest
index c6c9106baca..24763826bf6 100644
--- a/crates/celox-test-suite/src/sv/cases/timing.vtest
+++ b/crates/celox-test-suite/src/sv/cases/timing.vtest
@@ -496,6 +496,98 @@
(assert_eq d 3)
(assert_eq sampled 2 "the register samples the value before the edge's update"))
+(case staged_nonblocking_updates_keep_their_order
+ (source "staged_nba.sv" #"
+ module Top(output logic [7:0] last, count, early, two_sites, stim_seen, sampled);
+ logic [7:0] x = 8'd0, n = 8'd0, y = 8'd0, stim = 8'd0, r = 8'd0;
+ logic clk = 1'b0;
+ always #5 clk = ~clk;
+ initial begin
+ #1;
+ for (int i = 0; i < 3; i++) x <= 8'(i + 4);
+ repeat (2) n <= n + 8'd1;
+ for (int i = 0; i < 2; i++)
+ if (i == 1) y <= 8'd1;
+ else y <= 8'd2;
+ #0 early = x;
+ end
+ initial forever @(posedge clk) stim <= stim + 8'd3;
+ always_ff @(posedge clk) r <= stim;
+ assign last = x;
+ assign count = n;
+ assign two_sites = y;
+ assign stim_seen = stim;
+ assign sampled = r;
+ endmodule"#)
+ (top Top)
+ (run_until 1)
+ (assert_eq early 0 "a staged update lands after the inactive region")
+ (assert_eq last 6 "the last update of one site in a time slot wins")
+ (assert_eq count 1 "each update reads the value before the slot's updates")
+ (assert_eq two_sites 1 "updates of two sites land in the order they were issued")
+ (run_until 26)
+ (assert_eq stim_seen 9)
+ (assert_eq sampled 6 "the register samples the value before the edge's update"))
+
+(case narrow_nonblocking_updates_keep_the_other_bits
+ (source "narrow_nba.sv" #"
+ module Top(output logic [16:0] ps, pq, output logic [64:0] ws, wq,
+ output logic [65:0] xs, xq);
+ logic [15:0] p = 16'hffff, q = 16'hffff;
+ logic [63:0] w = 64'd0, v = 64'd0;
+ logic [64:0] x = 65'd0, y = 65'd0;
+ initial begin
+ #1;
+ p[11:4] <= 8'ha5;
+ q[11:4] <= 8'h5a;
+ q[3:0] <= 4'h0;
+ w <= 64'hfedc_ba98_7654_3210;
+ v <= 64'h0123_4567_89ab_cdef;
+ v[63:60] <= 4'h8;
+ x <= {1'b1, 64'h8000_0000_0000_0001};
+ y[64:1] <= 64'hffff_ffff_ffff_ffff;
+ y[0] <= 1'b0;
+ end
+ // Extended, so that no target becomes a port.
+ assign ps = {1'b0, p};
+ assign pq = {1'b0, q};
+ assign ws = {1'b0, w};
+ assign wq = {1'b0, v};
+ assign xs = {1'b0, x};
+ assign xq = {1'b0, y};
+ endmodule"#)
+ (top Top)
+ (run_until 1)
+ (assert_eq ps 0xfa5f "a part select across a byte boundary keeps the other bits")
+ (assert_eq pq 0xf5a0)
+ (assert_eq ws 0xfedcba9876543210 "a 64-bit target takes all its bits")
+ (assert_eq wq 0x8123456789abcdef)
+ (assert_eq xs 0x18000000000000001 "a 65-bit target takes all its bits")
+ (assert_eq xq 0x1fffffffffffffffe))
+
+(case four_state_nonblocking_updates_keep_unknown_bits
+ (source "four_state_nba.sv" #"
+ module Top(output bit staged, queued, wide);
+ logic [15:0] p = 16'bx, q = 16'bx;
+ logic [64:0] x = 65'bx;
+ initial begin
+ #1;
+ p[11:4] <= 8'ha5;
+ q[11:4] <= 8'h5z;
+ q[3:0] <= 4'h1;
+ x[32:1] <= 32'h8000_0001;
+ end
+ assign staged = p === 16'bxxxx_1010_0101_xxxx;
+ assign queued = q === 16'bxxxx_0101_zzzz_0001;
+ assign wide = x === {32'bx, 32'h8000_0001, 1'bx};
+ endmodule"#)
+ (top Top)
+ (four_state)
+ (run_until 1)
+ (assert_eq staged 1 "an update keeps the unknown bits around it")
+ (assert_eq queued 1)
+ (assert_eq wide 1))
+
(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;
@@ -1057,6 +1149,56 @@ module Top(input bit clk,output bit[7:0]seen);bit q;Child c(clk,q);initial forev
(run_to_finish)
(assert_eq count 8))
+(case real_delays_round_at_the_scope_precision
+ ; IEEE 1800-2023 3.14.1: a delay is rounded at the scope's precision, here
+ ; the default 1 ps, and 6.12.1 rounds a real tie away from zero: 0.0625 ns
+ ; waits 63 ps. A NaN delay counts as zero, as Icarus 13.0 and Verilator
+ ; 5.052 do.
+ (source "real_delays.sv" #"
+ module Top(output bit a_before, a_after, b_before, b_after, c_before,
+ c_after, d_after, e_before, e_after);
+ real r = 2.75, tie = 0.0625, zero = 0.0, nan;
+ shortreal quarter = 0.25;
+ bit a, b, c, d, e;
+ initial begin #r a = 1; end
+ initial begin #2749ps a_before = a; #2ps a_after = a; end
+ initial begin #3; #tie b = 1; end
+ initial begin #3062ps b_before = b; #2ps b_after = b; end
+ initial begin #5; #quarter c = 1; end
+ initial begin #5249ps c_before = c; #2ps c_after = c; end
+ initial begin nan = zero / zero; #6; #nan d = 1; end
+ initial begin #6001ps d_after = d; end
+ initial begin #7; #(r * 2) e = 1; end
+ initial begin #12499ps e_before = e; #2ps e_after = e; end
+ initial #20 $finish;
+ endmodule
+ "#)
+ (top Top)
+ (run_to_finish)
+ (assert_eq a_before 0)
+ (assert_eq a_after 1 "2.75 waits 2750 ps")
+ (assert_eq b_before 0)
+ (assert_eq b_after 1 "0.0625 waits 63 ps")
+ (assert_eq c_before 0)
+ (assert_eq c_after 1 "shortreal 0.25 waits 250 ps")
+ (assert_eq d_after 1 "a NaN delay waits zero")
+ (assert_eq e_before 0)
+ (assert_eq e_after 1 "r * 2 waits 5.5 ns"))
+
+(case negative_real_delays_wait_their_twos_complement
+ ; IEEE 1800-2023 9.4.1: a negative delay is read as a two's-complement
+ ; unsigned time, so -1.5 waits about 2^64 precision steps.
+ (source "negative_real_delay.sv" #"
+ module Top(output bit woke);
+ real r = -1.5;
+ initial begin #r woke = 1; end
+ initial #10 $finish;
+ endmodule
+ "#)
+ (top Top)
+ (run_to_finish)
+ (assert_eq woke 0))
+
(case expression_events_see_pulses_within_a_time_slot
; IEEE 1800-2023 9.4.2: each change of the expression's value is an
; event, also one the slot undoes before it ends. The waits begin after
diff --git a/crates/celox-test-suite/verification/sv/icarus/timing.json b/crates/celox-test-suite/verification/sv/icarus/timing.json
index df08045c942..bdda61cc112 100644
--- a/crates/celox-test-suite/verification/sv/icarus/timing.json
+++ b/crates/celox-test-suite/verification/sv/icarus/timing.json
@@ -485,6 +485,17 @@
"tag_reasons": {},
"tags": []
},
+ {
+ "category": "Sequential",
+ "detail": "",
+ "expectation": "Simulation",
+ "name": "timing::negative_real_delays_wait_their_twos_complement",
+ "phase": "execute",
+ "status": "passed",
+ "stronger_than_sv": false,
+ "tag_reasons": {},
+ "tags": []
+ },
{
"category": "Sequential",
"detail": "",
@@ -584,6 +595,17 @@
"tag_reasons": {},
"tags": []
},
+ {
+ "category": "Sequential",
+ "detail": "",
+ "expectation": "Simulation",
+ "name": "timing::real_delays_round_at_the_scope_precision",
+ "phase": "execute",
+ "status": "passed",
+ "stronger_than_sv": false,
+ "tag_reasons": {},
+ "tags": []
+ },
{
"category": "Sequential",
"detail": "",
diff --git a/crates/celox-test-suite/verification/sv/verilator/timing.json b/crates/celox-test-suite/verification/sv/verilator/timing.json
index 6058dfc509d..db973636cdb 100644
--- a/crates/celox-test-suite/verification/sv/verilator/timing.json
+++ b/crates/celox-test-suite/verification/sv/verilator/timing.json
@@ -485,6 +485,17 @@
"tag_reasons": {},
"tags": []
},
+ {
+ "category": "Sequential",
+ "detail": "",
+ "expectation": "Simulation",
+ "name": "timing::negative_real_delays_wait_their_twos_complement",
+ "phase": "execute",
+ "status": "passed",
+ "stronger_than_sv": false,
+ "tag_reasons": {},
+ "tags": []
+ },
{
"category": "Sequential",
"detail": "",
@@ -584,6 +595,17 @@
"tag_reasons": {},
"tags": []
},
+ {
+ "category": "Sequential",
+ "detail": "",
+ "expectation": "Simulation",
+ "name": "timing::real_delays_round_at_the_scope_precision",
+ "phase": "execute",
+ "status": "passed",
+ "stronger_than_sv": false,
+ "tag_reasons": {},
+ "tags": []
+ },
{
"category": "Sequential",
"detail": "",
diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs
index 70aabb29492..200cbe17a52 100644
--- a/crates/celox/tests/frontends/systemverilog/timing.rs
+++ b/crates/celox/tests/frontends/systemverilog/timing.rs
@@ -80,6 +80,9 @@ timed_cases! {
fn blocking_ff_stores_are_visible_before_inactive_work = "timing::blocking_ff_stores_are_visible_before_inactive_work";
fn blocking_ff_clock_edges_trigger_their_domains_before_inactive_work = "timing::blocking_ff_clock_edges_trigger_their_domains_before_inactive_work";
fn nonblocking_assignments_in_processes_update_in_the_nba_region = "timing::nonblocking_assignments_in_processes_update_in_the_nba_region";
+ fn staged_nonblocking_updates_keep_their_order = "timing::staged_nonblocking_updates_keep_their_order";
+ fn narrow_nonblocking_updates_keep_the_other_bits = "timing::narrow_nonblocking_updates_keep_the_other_bits";
+ fn four_state_nonblocking_updates_keep_unknown_bits = "timing::four_state_nonblocking_updates_keep_unknown_bits";
fn nonblocking_ff_stores_remain_pending_during_inactive_work = "timing::nonblocking_ff_stores_remain_pending_during_inactive_work";
fn mixed_ff_stores_keep_their_active_and_nba_values = "timing::mixed_ff_stores_keep_their_active_and_nba_values";
fn printed_finish_notice_is_design_output = "timing::printed_finish_notice_is_design_output";
@@ -119,6 +122,8 @@ timed_cases! {
fn long_process_loops_finish_within_one_time_slot = "timing::long_process_loops_finish_within_one_time_slot";
fn initial_blocks_run_at_time_zero = "timing::initial_blocks_run_at_time_zero";
fn host_edges_after_time_zero_clock_flip_flops = "timing::host_edges_after_time_zero_clock_flip_flops";
+ fn real_delays_round_at_the_scope_precision = "timing::real_delays_round_at_the_scope_precision";
+ fn negative_real_delays_wait_their_twos_complement = "timing::negative_real_delays_wait_their_twos_complement";
fn expression_events_see_pulses_within_a_time_slot = "timing::expression_events_see_pulses_within_a_time_slot";
fn real_expression_events_see_fractional_changes = "timing::real_expression_events_see_fractional_changes";
fn bit_select_edges_follow_the_selected_bit = "timing::bit_select_edges_follow_the_selected_bit";
@@ -219,6 +224,58 @@ fn time_literal_delays_round_at_scope_precision() {
assert_eq!(sim.get(coarse), 1u8.into());
}
+/// A real delay is rounded at its scope's precision with ties away from
+/// zero (IEEE 1800-2023 3.14.1, 6.12.1): 2.7505 ns waits 2751 ps at 1 ps,
+/// and 2.75 ns waits 2.8 ns at 100 ps.
+#[test]
+fn real_delays_round_at_scope_precision() {
+ let source = r#"
+ module Fine(output int stage);
+ timeunit 1ns / 1ps;
+ real r = 2.7505;
+ initial begin #r stage = 1; #1.5 stage = 2; end
+ endmodule
+ module Coarse(output int stage);
+ timeunit 1ns / 100ps;
+ real r = 2.75;
+ shortreal half = 0.05;
+ initial begin #r stage = 1; #1.25 stage = 2; #half stage = 3; end
+ endmodule
+ module Top(output int fine, coarse);
+ timeunit 1ns / 1ps;
+ Fine f(fine); Coarse c(coarse);
+ endmodule
+ "#;
+ for level in [celox::OptLevel::O0, celox::OptLevel::O1] {
+ let mut sim = celox::Simulation::from_sv_sources(
+ vec![(source, std::path::Path::new("real_delays.sv"))],
+ "Top",
+ )
+ .opt_level(level)
+ .build()
+ .unwrap();
+ let fine = sim.signal("fine");
+ let coarse = sim.signal("coarse");
+ // (time in ps, fine stage, coarse stage)
+ for (time, f, c) in [
+ (2750u64, 0u32, 0u32),
+ (2751, 1, 0),
+ (2799, 1, 0),
+ (2800, 1, 1),
+ (4099, 1, 1),
+ (4100, 1, 2),
+ (4199, 1, 2),
+ (4200, 1, 3),
+ (4250, 1, 3),
+ (4251, 2, 3),
+ ] {
+ sim.run_until(time).unwrap();
+ assert_eq!(sim.get(fine), f.into(), "{level:?} fine at {time}");
+ assert_eq!(sim.get(coarse), c.into(), "{level:?} coarse at {time}");
+ }
+ }
+}
+
/// The variables of an event expression, `$event[k]` and its copies of
/// process-local operands, are state like the process slots: a state file
/// keeps them, while the signal listing and the waveform leave them out.
@@ -483,3 +540,105 @@ fn timing_controls_outside_suspendable_processes_are_rejected() {
assert!(error.contains(construct), "{body}: {error}");
}
}
+
+/// A nonblocking site stages its value (`NbaSite::pending`) only if its
+/// target has no other writer and nothing observes the order of the
+/// updates in the NBA region: no wait reads the target, directly or through
+/// combinational logic, including the `$event` variable of an expression
+/// event. Every other site keeps the ordered queue.
+#[test]
+fn nonblocking_sites_stage_only_unobserved_targets_with_one_writer() {
+ let source = r#"
+ module Top(output logic [7:0] q, output bit seen_wait, seen_comb);
+ timeunit 1ps / 1ps;
+ logic [7:0] stim = 8'd0, blocking = 8'd0, r = 8'd0;
+ logic a = 1'b0, b = 1'b0, d = 1'b0, e = 1'b0, s = 1'b0, en = 1'b1, clk = 1'b0;
+ logic [7:0] hits = 8'd0;
+ wire c = d & ~e;
+ always #5 clk = ~clk;
+ initial forever @(posedge clk) stim <= stim + 8'd3;
+ always_ff @(posedge clk) r <= stim;
+ initial begin #2; a <= 1'b1; b <= 1'b1; d <= 1'b1; e <= 1'b1; end
+ initial begin #10; b <= 1'b1; e <= 1'b1; end
+ initial begin wait (a && !b); seen_wait = 1'b1; end
+ initial begin @(posedge c); seen_comb = 1'b1; end
+ initial forever @(posedge clk) s <= ~s;
+ initial forever @(posedge (s & en)) hits = hits + 8'd1;
+ initial begin #1; blocking <= 8'd1; #1 blocking = 8'd2; end
+ initial begin #1; q <= stim; end
+ endmodule
+ "#;
+ let simulator = celox::Simulator::from_sv_sources(
+ vec![(source, std::path::Path::new("staged_sites.sv"))],
+ "Top",
+ )
+ .build()
+ .unwrap();
+ let program = simulator.program();
+ let mut staged: Vec<_> = ["stim", "blocking", "a", "b", "d", "e", "s", "q"]
+ .into_iter()
+ .filter(|name| {
+ let target = program.get_addr(&[], &[name]).unwrap();
+ program
+ .runtime_schema
+ .nba_sites
+ .iter()
+ .filter(|site| site.target == target)
+ .all(|site| site.pending.is_some())
+ })
+ .collect();
+ staged.sort_unstable();
+ assert_eq!(staged, ["stim"]);
+
+ // The observed sites keep the ordered queue, and behave as before any
+ // site could stage: Celox evaluates the waits after the region's
+ // updates, so neither sees `a && !b` or `c` hold between two of them.
+ let mut sim = celox::Simulation::from_sv_sources(
+ vec![(source, std::path::Path::new("staged_sites.sv"))],
+ "Top",
+ )
+ .build()
+ .unwrap();
+ sim.run_until(26).unwrap();
+ assert_eq!(sim.get(sim.signal("seen_wait")), 0u8.into());
+ assert_eq!(sim.get(sim.signal("seen_comb")), 0u8.into());
+ assert_eq!(sim.get(sim.signal("q")), 0u8.into());
+ assert_eq!(sim.get(sim.signal("stim")), 9u8.into());
+ assert_eq!(sim.get(sim.signal("r")), 6u8.into());
+ assert_eq!(sim.get(sim.signal("hits")), 2u8.into());
+}
+
+/// The narrow updates case covers staged and queued sites alike.
+#[test]
+fn narrow_nonblocking_updates_cover_staged_and_queued_sites() {
+ let design = celox_test_suite::sv::cases()
+ .find(|case| case.name == "timing::narrow_nonblocking_updates_keep_the_other_bits")
+ .unwrap()
+ .design();
+ let sources = design
+ .sources
+ .iter()
+ .map(|source| (source.text.as_str(), source.path.as_path()))
+ .collect::>();
+ let simulator = celox::Simulator::from_sv_sources(sources, &design.top)
+ .build()
+ .unwrap();
+ let program = simulator.program();
+ let staged = |name: &str| {
+ let target = program.get_addr(&[], &[name]).unwrap();
+ let sites = program
+ .runtime_schema
+ .nba_sites
+ .iter()
+ .filter(|site| site.target == target)
+ .collect::>();
+ assert!(!sites.is_empty(), "{name}");
+ sites.iter().all(|site| site.pending.is_some())
+ };
+ for name in ["p", "w", "x"] {
+ assert!(staged(name), "{name} stages its update");
+ }
+ for name in ["q", "v", "y"] {
+ assert!(!staged(name), "{name} queues its updates");
+ }
+}
diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md
index cbe8d605be0..e5b182f7fa9 100644
--- a/docs/guide/systemverilog-reference.md
+++ b/docs/guide/systemverilog-reference.md
@@ -48,7 +48,7 @@ In a timed `Simulation`, `initial` and plain `always` processes can suspend:
| Control | Supported |
| --- | --- |
-| `#delay` | integral delays, `#(min:typ:max)` (the typical value) and [time literals](#time-literal-delays); an X or Z delay counts as zero |
+| `#delay` | integral and real delays, `#(min:typ:max)` (the typical value) and [time literals](#time-literal-delays); an X or Z delay counts as zero |
| `@(...)` | variables, `posedge` / `negedge` / `edge`, items joined by `or` or `,`, bit, part and run-time index selects, any expression including calls of pure functions, and `@*` / `@(*)`, which waits on the variables its statement reads |
| `wait (condition)` | any condition; an X or Z condition counts as false |
| Assignments | blocking and nonblocking; nonblocking updates take effect in the NBA region of the time slot |
@@ -94,8 +94,10 @@ constants, selects and concatenation arguments are unsupported and rejected.
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
-delays are not supported yet ([#1707](https://github.com/celox-sim/celox/issues/1707)).
+scope's precision before conversion to scheduler ticks (5.8, 3.14.1). A real
+delay such as `#1.5` or `#r` rounds the same way, with ties away from zero
+(6.12.1); a negative one waits its two's complement (9.4.1), and a NaN one
+waits zero.
### Built-in functions and tasks
@@ -123,7 +125,7 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https:
delayed continuous assignments ([#444](https://github.com/celox-sim/celox/issues/444)),
named events and `->`, `fork` / `join`, `wait fork` / `disable fork`, concurrent assertions, `force` / `release`.
- Timing controls in processes: `iff` qualifiers ([#1444](https://github.com/celox-sim/celox/issues/1444)),
- real-valued delays ([#1707](https://github.com/celox-sim/celox/issues/1707)), package-scoped delay values
+ package-scoped delay values
([#1710](https://github.com/celox-sim/celox/issues/1710)), impure function calls in event expressions, and
`wait` or event expressions reading a static task argument. Nonblocking
assignments in a process cannot yet target an unpacked array element, a
diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md
index 7623b7ee719..b78bf2a0674 100644
--- a/docs/guide/systemverilog.md
+++ b/docs/guide/systemverilog.md
@@ -92,9 +92,8 @@ ports, types, statements or system functions before porting a design.
Common reasons a design needs changes are:
- Class-based verification and concurrent assertions.
-- `fork` / `join`, named events, intra-assignment timing such as `a = #1 b`,
- `iff` in event controls ([#1444](https://github.com/celox-sim/celox/issues/1444)) and real-valued delays
- ([#1707](https://github.com/celox-sim/celox/issues/1707)).
+- `fork` / `join`, named events, intra-assignment timing such as `a = #1 b`
+ and `iff` in event controls ([#1444](https://github.com/celox-sim/celox/issues/1444)).
- Nonblocking latch assignments, multiple drivers and tri-state buses. Inferred latches in `always_comb` require `inferred_latch = "warn"` or `"allow"` in the common `[diagnostics]` configuration.
- Non-ANSI module ports, wildcard `.*` connections, gate primitives and `bind`.
- Strings, `real`, unpacked structs and several interface features.
diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md
index 50ec446cad0..11966f17216 100644
--- a/docs/ja/guide/systemverilog-reference.md
+++ b/docs/ja/guide/systemverilog-reference.md
@@ -47,7 +47,7 @@ outline: [2, 3]
| 制御 | 対応範囲 |
| --- | --- |
-| `#delay` | 整数の遅延、`#(min:typ:max)`(typ の値)、[時間リテラル](#time-literal-delays)。X / Z の遅延は 0 として扱う |
+| `#delay` | 整数と実数の遅延、`#(min:typ:max)`(typ の値)、[時間リテラル](#time-literal-delays)。X / Z の遅延は 0 として扱う |
| `@(...)` | 変数、`posedge` / `negedge` / `edge`、`or` または `,` で並べた項目、ビット選択・部分選択・実行時添字の選択、pure な関数呼び出しを含む任意の式、文が読む変数を待つ `@*` / `@(*)` |
| `wait (condition)` | 任意の条件。X / Z の条件は偽として扱う |
| 代入 | ブロッキング代入とノンブロッキング代入。ノンブロッキング代入はそのタイムスロットの NBA 領域で反映 |
@@ -88,7 +88,8 @@ select・連結式の引数は未対応として拒否します。
遅延制御の時間リテラルは `#5ns`、`#(2.75ns)`、`#40ps` など、`fs` から `s` の6単位に
対応します。宣言スコープの時間精度で丸めてから scheduler の tick に変換します
-(5.8、3.14.1)。実数の遅延はまだ未対応です([#1707](https://github.com/celox-sim/celox/issues/1707))。
+(5.8、3.14.1)。`#1.5` や `#r` などの実数の遅延も同様に丸め、ちょうど中間の値は 0 から遠い方に
+丸めます(6.12.1)。負の遅延は2の補数として待ち(9.4.1)、NaN の遅延は 0 として扱います。
### 組み込み関数とタスク
@@ -117,7 +118,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行
- 振る舞い記述・検証向けの構文:`final`、代入内のタイミング制御(`a = #1 b`)、遅延付き継続代入([#444](https://github.com/celox-sim/celox/issues/444))、
named event と `->`、`fork` / `join`、`wait fork` / `disable fork`、並行アサーション、`force` / `release`。
- プロセス内のタイミング制御:`iff` 修飾([#1444](https://github.com/celox-sim/celox/issues/1444))、
- 実数の遅延([#1707](https://github.com/celox-sim/celox/issues/1707))、package スコープの遅延値
+ package スコープの遅延値
([#1710](https://github.com/celox-sim/celox/issues/1710))、イベント式内の impure な関数呼び出し、
static task 引数を読む `wait` 条件とイベント式。プロセス内のノンブロッキング代入は、
unpacked 配列の要素、実行時に決まる位置、代入先の範囲外の定数位置をまだ代入先にできません
diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md
index c341643e4eb..1125011e7cc 100644
--- a/docs/ja/guide/systemverilog.md
+++ b/docs/ja/guide/systemverilog.md
@@ -88,7 +88,7 @@ X/Z を扱う場合は builder に `.four_state(true)` を指定します。
- クラスを使う検証、並行アサーション。
- `fork` / `join`、named event、`a = #1 b` のような代入内のタイミング制御、
- イベント制御の `iff`([#1444](https://github.com/celox-sim/celox/issues/1444))、実数の遅延([#1707](https://github.com/celox-sim/celox/issues/1707))。
+ イベント制御の `iff`([#1444](https://github.com/celox-sim/celox/issues/1444))。
- ラッチ内のノンブロッキング代入、複数ドライバ、トライステートバス。`always_comb` の暗黙のラッチ推論は 共通の `[diagnostics]` 設定で `inferred_latch = "warn"` または `"allow"` を指定して許可します。
- 非 ANSI モジュールポート、ワイルドカード `.*` 接続、ゲートプリミティブ、`bind`。
- 文字列、`real`、unpacked 構造体、interface の一部の機能。