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
23 changes: 18 additions & 5 deletions crates/celox-napi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4343,8 +4343,12 @@ mod tests {
}

#[test]
fn native_handle_edges_of_clocks_comb_logic_does_not_read_stay_settled() {
for (seen, comb_read) in [("1'b1", false), ("clk", true)] {
fn native_handle_edges_preserve_settledness_for_unused_clocks_and_wiring() {
for (seen, settled, value) in [
("1'b1", true, Some(1)),
("clk", true, Some(0)),
("~clk", false, None),
] {
let source = format!(
"module Top (clk: input clock, count: output logic<8>, seen: output logic) {{
always_ff (clk) {{ count += 1; }}
Expand All @@ -4356,13 +4360,22 @@ mod tests {
let events: HashMap<String, u32> = serde_json::from_str(&handle.events_json()).unwrap();
let clk = events["clk"];
assert!(handle.edges(vec![clk], vec![true], None).unwrap());
// Moving `clk` without running a domain leaves combinational
// logic stale only when it reads `clk`, or already was.
// Unused clocks and direct wiring remain settled after an
// inactive edge. Other clock-dependent logic still needs a settle.
assert_eq!(
handle.edges(vec![clk], vec![false], Some(false)).unwrap(),
!comb_read,
settled,
"{seen}"
);
if let Some(value) = value {
let layout: serde_json::Value =
serde_json::from_str(&handle.layout_json()).unwrap();
let offset = layout["seen"]["offset"].as_u64().unwrap() as usize;
let (memory, len) = handle.backend.as_mut().unwrap().memory_as_mut_ptr();
assert!(offset < len);
// Read the stored result without implicitly evaluating comb.
assert_eq!(unsafe { *memory.add(offset) }, value, "{seen}");
}
assert!(handle.edges(vec![clk], vec![true], Some(true)).unwrap());
assert!(!handle.edges(vec![clk], vec![false], Some(true)).unwrap());
handle.dispose().unwrap();
Expand Down
8 changes: 8 additions & 0 deletions crates/celox-runtime/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ pub trait SimBackend {
// ── evaluation ──────────────────────────────────────────────
fn eval_comb(&mut self) -> Result<(), SimulatorErrorCode>;

/// Publish all combinational effects of a single clock-level change when
/// its cone is proven to contain only wiring. Called only from a settled
/// state, immediately after the host writes the clock. `false` must leave
/// state unchanged and requests the normal full settle.
fn eval_clock_aliases(&mut self, _event: Self::Event) -> Result<bool, SimulatorErrorCode> {
Ok(false)
}

/// Evaluate and apply a flip-flop domain for the given event.
fn eval_apply_ff_at(&mut self, event: Self::Event) -> Result<(), SimulatorErrorCode>;

Expand Down
11 changes: 7 additions & 4 deletions crates/celox-runtime/src/edge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -358,7 +358,9 @@ where
};
let new = edge.level();
let fires = info.fires(known(from), edge);
let settle = dirty || info.comb_read;
let comb_read =
info.comb_read && (dirty || !executor.backend_mut().eval_clock_aliases(event)?);
let settle = dirty || comb_read;
if let Some(plan) = plan {
// A gated clock is judged from the lever's real level before the
// edge, x and z included.
Expand All @@ -381,11 +383,11 @@ where
return Ok(if settled {
EdgeOutcome::Settled
} else {
moved_only(info.comb_read)
moved_only(comb_read)
});
}
if !fires {
return Ok(moved_only(info.comb_read));
return Ok(moved_only(comb_read));
}
if settle {
executor.eval_comb_apply_ff_at(event)?;
Expand Down Expand Up @@ -552,7 +554,8 @@ where
any_moved = true;
write.write(executor.backend_mut(), info.signal, new);
transitions.push((info.signal, (old, new)));
comb_read |= info.comb_read;
comb_read |=
info.comb_read && (dirty || !executor.backend_mut().eval_clock_aliases(event)?);
let fires = info.fires(known(old), edge);
if cached {
changed.push((event, fires));
Expand Down
107 changes: 106 additions & 1 deletion crates/celox/src/backend/native/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ impl super::super::EventHandle for NativeEventRef {
/// that share the same compiled machine code.
pub struct SharedNativeCode {
comb_func: NativeSimFunc,
clock_alias_funcs: Vec<Option<NativeSimFunc>>,
comb_unit_funcs: Vec<NativeSimFunc>,
/// One function per process kernel.
process_funcs: Vec<NativeSimFunc>,
Expand Down Expand Up @@ -308,8 +309,25 @@ impl SharedNativeCode {
.map(materialize)
.collect::<Result<Vec<_>, _>>()?;

// Optional named exports keep older images usable: absence requests a
// full settle. Export names are part of the native runtime contract.
let mut clock_alias_funcs = vec![None; id_to_event.len()];
for entry in &program_image.code_entries {
if let Some(id) = entry.name.strip_prefix(super::clock_aliases::EXPORT_PREFIX) {
let id = id
.strip_suffix(']')
.and_then(|id| id.parse::<usize>().ok())
.filter(|&id| id < clock_alias_funcs.len())
.ok_or_else(|| codegen_message("invalid clock alias export"))?;
if clock_alias_funcs[id].is_some() {
return Err(codegen_message("duplicate clock alias export"));
}
clock_alias_funcs[id] = Some(native_function_at(&jit_image, entry.offset)?);
}
}
Ok(Self {
comb_func,
clock_alias_funcs,
comb_unit_funcs,
process_funcs,
lane_kernels,
Expand Down Expand Up @@ -359,7 +377,8 @@ impl SharedNativeCode {
/// One callable function in a packed native code image.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct NativeCodeEntry {
/// Stable diagnostic name for the emitted function.
/// Stable name for the emitted function. `clock_alias_update[N]` names
/// an optional clock-wiring update entry for event N; other names are diagnostic.
pub name: String,
/// Byte offset from the start of the native image.
pub offset: usize,
Expand Down Expand Up @@ -2656,13 +2675,38 @@ fn compile_program_with_outlining_threshold(
.into_iter()
.collect::<Result<Vec<_>, _>>()?;
let lane_kernels = super::lanes::compile_lane_kernels(sir, options, cancel)?;
let mut clock_alias_jits = Vec::new();
if !options.four_state && !options.native_force_support && force_bindings.is_empty() {
let (_, clocks) = crate::backend::event_ids(sir);
for (id, clock) in clocks.into_iter().enumerate() {
if let Some(units) = super::clock_aliases::extract(sir, clock) {
let name = format!("{}{}]", super::clock_aliases::EXPORT_PREFIX, id);
let compiled = compile_units(
&units,
layout,
false,
&name,
&options.x86_options,
false,
&options.optimize_options.diagnostics,
cancel,
)?;
clock_alias_jits.push((name, compiled));
}
}
}
let codegen_trace = capture_trace
.then(|| format_native_codegen_trace(&comb_jit, &compiled_ff_codes, &compile_tasks));
let semantic_memory_size = layout
.merged_total_size
.checked_add(layout.triggered_bits_total_size)
.expect("native semantic-memory size overflow");
let native_memory_size = std::iter::once(comb_jit.required_state_size)
.chain(
clock_alias_jits
.iter()
.map(|(_, code)| code.required_state_size),
)
.chain(comb_chunk_jits.iter().map(|code| code.required_state_size))
.chain(
compiled_ff_codes
Expand All @@ -2683,6 +2727,11 @@ fn compile_program_with_outlining_threshold(
)
.fold(semantic_memory_size, usize::max);
let required_native_features = std::iter::once(comb_jit.required_native_features)
.chain(
clock_alias_jits
.iter()
.map(|(_, code)| code.required_native_features),
)
.chain(
comb_chunk_jits
.iter()
Expand Down Expand Up @@ -2768,6 +2817,15 @@ fn compile_program_with_outlining_threshold(
)?;
task_offsets.insert(task_id, offset);
}
for (name, compiled) in &clock_alias_jits {
append_native_code(
&mut packed_image,
&mut code_entries,
&mut image_symbols,
name.clone(),
compiled,
)?;
}
let lane_image = lane_kernels
.map(|kernels| kernels.pack(&mut packed_image, &mut code_entries, &mut image_symbols))
.transpose()?;
Expand Down Expand Up @@ -3695,6 +3753,14 @@ impl super::super::SimBackend for NativeBackend {
self.call_func_timed(func)
}

fn eval_clock_aliases(&mut self, event: NativeEventRef) -> Result<bool, SimulatorErrorCode> {
let Some(func) = self.compiled.clock_alias_funcs[event.id] else {
return Ok(false);
};
self.call_func_timed(func)?;
Ok(true)
}

fn eval_apply_ff_at(&mut self, event: NativeEventRef) -> Result<(), SimulatorErrorCode> {
if self.lane_event_kernel(event) {
let compiled = Arc::clone(&self.compiled);
Expand Down Expand Up @@ -4085,6 +4151,45 @@ mod tests {
BasicBlock, BlockId, RegisterId, RegisterType, SIRInstruction, SIRTerminator, SIRValue,
};

#[test]
fn image_without_clock_alias_exports_uses_full_settle() {
let source = r#"
module Child (clk: input clock, d: input bit<8>, q: output bit<8>) {
always_ff (clk) { q = d; }
}
module Top (clk: input clock, d: input bit<8>, q: output bit<8>) {
inst child: Child (clk, d, q);
}
"#;
let mut image = crate::Simulator::builder(source, "Top")
.four_state(false)
.compile_native()
.unwrap()
.into_program_image();
let previous = image.code_entries.len();
image.code_entries.retain(|entry| {
!entry
.name
.starts_with(super::super::clock_aliases::EXPORT_PREFIX)
});
assert_eq!(previous, image.code_entries.len() + 1);
let image =
NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()).unwrap();
let mut sim = crate::Simulator::from_sources(Vec::new(), "Top")
.build_native_from_image(image)
.unwrap();
let event = sim.event("clk");
let d = sim.signal("d");
sim.set(d, 42u8);
sim.active_edge(event).unwrap();
sim.inactive_edge(event).unwrap();
assert_eq!(sim.get(sim.signal("q")), 42u8.into());
assert_eq!(
sim.get(sim.child_signal(&[("child", 0)], "clk")),
0u8.into()
);
}

/// A unit of `blocks` blocks loading `value`, with its maps filled in
/// forward or reverse order.
fn unit(blocks: usize, value: u8, width: usize, reverse: bool) -> NativeUnit {
Expand Down
Loading
Loading