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
3 changes: 3 additions & 0 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion crates/celox-design/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1358,7 +1358,8 @@ pub struct SchedulerSlots<A> {
/// Where a shared combinational settle continues.
pub cont: A,
/// Set when state combinational logic reads may have changed since its
/// last settle.
/// last settle. The caller initializes this before every scheduler run;
/// timed runs set it even after a checkpoint restore or partial-slot exit.
pub dirty: A,
/// The number of time slots the run ran.
pub count: A,
Expand Down
2 changes: 2 additions & 0 deletions crates/celox-runtime/src/schedule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ pub(crate) struct SchedulerRefs {
pub(crate) exit: SignalRef,
pub(crate) exit_arg: SignalRef,
pub(crate) finish: SignalRef,
pub(crate) dirty: SignalRef,
pub(crate) count: SignalRef,
pub(crate) current: SignalRef,
pub(crate) levels: SignalRef,
Expand Down Expand Up @@ -426,6 +427,7 @@ impl<B: SimBackend> ResolvedSchedule<B> {
exit: resolve(&slots.exit),
exit_arg: resolve(&slots.exit_arg),
finish: resolve(&slots.finish),
dirty: resolve(&slots.dirty),
count: resolve(&slots.count),
current: resolve(&slots.current),
levels: resolve(&slots.levels),
Expand Down
2 changes: 1 addition & 1 deletion crates/celox-runtime/src/simulation/activation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ impl<B: SimBackend> SimulationState<B> {
}
}
}
let live_cancelled = cancelled
let live_cancelled: Vec<usize> = cancelled
.iter()
.enumerate()
.filter_map(|(id, &cancelled)| {
Expand Down
3 changes: 3 additions & 0 deletions crates/celox-runtime/src/simulation/compiled.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,9 @@ impl<B: SimBackend> SimulationState<B> {
backend.set(scheduler.limit, limit);
backend.set(scheduler.exit, 0u8);
backend.set(scheduler.finish, 0u8);
// State may have been restored or a prior slot may have exited early.
// Only hosts that prove their input state settled may enter clean.
backend.set(scheduler.dirty, 1u8);
backend.set(scheduler.count, 0u64);
for &(_, waiting) in scheduler.wake.iter().flatten() {
backend.set(waiting, 0u8);
Expand Down
8 changes: 8 additions & 0 deletions crates/celox-runtime/src/simulation/edges.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ impl<B: SimBackend> SimulationState<B> {
self.record_all_levels(backend);
}

/// Restore samples saved by a generated scheduler before it ran a slot.
/// This preserves pending asynchronous edges when execution returns to the queue.
pub fn restore_event_baselines(&mut self, levels: impl IntoIterator<Item = (usize, u8)>) {
for (event, level) in levels {
self.record_level(event, level);
}
}

/// Whether an event signal changed outside the queue since its last sample.
/// Callers must settle pending combinational writes before treating `false`
/// as permission to bypass the queue's transition detection.
Expand Down
89 changes: 37 additions & 52 deletions crates/celox-runtime/src/testbench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,39 +284,6 @@ fn bind_statement<B: SimBackend>(
.into_iter()
.map(|statement| bind_statement(backend, statement))
.collect::<Option<Vec<_>>>()?;
// A constant loop that only waits does not need a host wakeup at
// each iteration. clock_gen keeps running while this process
// sleeps; the induction variable is scoped to the empty body.
if !inclusive
&& !reverse
&& step == 1
&& step_op.is_none()
&& let (Some(0), Some(iterations)) = (constant_bound(&start), constant_bound(&end))
&& let [
GenericTestbenchStatement::ClockNext {
clock_event,
count,
period,
},
] = body.as_slice()
&& let Some(count) = match count {
GenericClockCount::Static(n) => Some(*n),
GenericClockCount::Dynamic(expr) => expr.constant_u64(),
}
&& count != 0
&& iterations != 0
&& loop_var.as_ref().is_none_or(|(_, width, signed)| {
let bits = width.saturating_sub(usize::from(*signed));
bits >= 64 || iterations < (1u64 << bits)
})
&& let Some(count) = iterations.checked_mul(count)
{
return Some(GenericTestbenchStatement::ClockNext {
clock_event: *clock_event,
count: GenericClockCount::Static(count),
period: *period,
});
}
Some(GenericTestbenchStatement::For {
loop_var: loop_var.map(|(signal, width, signed)| {
(backend.resolve_signal(&signal.address), width, signed)
Expand Down Expand Up @@ -405,25 +372,6 @@ fn bind_statement<B: SimBackend>(
}
}

fn constant_bound(bound: &ExecutableLoopBound) -> Option<u64> {
match bound {
GenericLoopBound::Static(value) => u64::try_from(*value).ok(),
GenericLoopBound::Dynamic {
expr,
width,
signed,
} if *width <= 64 => {
let value = expr.constant_u64()?;
if *signed && (*width == 0 || value >> (*width - 1) != 0) {
None
} else {
Some(value)
}
}
_ => None,
}
}

pub fn bind_testbench_program<B: SimBackend>(
backend: &B,
program: TestbenchProgram<AbsoluteAddr>,
Expand All @@ -443,6 +391,37 @@ pub fn bind_testbench_program<B: SimBackend>(
hardware.sort_unstable_by_key(|range| (range.start, range.end));
hardware.dedup();
let backend = &Binding { backend, hardware };
let kernels = program
.kernels()
.iter()
.map(|kernel| celox_testbench::TestbenchKernel {
entry: kernel.entry,
resume: backend.resolve_signal(&kernel.resume),
status: backend.resolve_signal(&kernel.status),
request: backend.resolve_signal(&kernel.request),
requests: kernel
.requests
.iter()
.map(|request| match request {
celox_testbench::KernelRequest::Statement(site) => {
celox_testbench::KernelRequest::Statement(*site)
}
celox_testbench::KernelRequest::Settle => {
celox_testbench::KernelRequest::Settle
}
celox_testbench::KernelRequest::Written { address, width } => {
celox_testbench::KernelRequest::Written {
address: backend.resolve_signal(address),
width: *width,
}
}
celox_testbench::KernelRequest::Error(message) => {
celox_testbench::KernelRequest::Error(message.clone())
}
})
.collect(),
})
.collect();
let lengths = program.process_lengths().to_vec();
if lengths
.iter()
Expand Down Expand Up @@ -497,6 +476,10 @@ pub fn bind_testbench_program<B: SimBackend>(
.into_iter()
.map(|component| bind_component(backend, component, rtl_writes))
.collect::<Option<Vec<_>>>()?;
let scheduler = program
.scheduler()
.cloned()
.map(|s| s.map(|a| backend.resolve_signal(&a)));
let statements = program
.into_statements()
.into_iter()
Expand All @@ -509,6 +492,8 @@ pub fn bind_testbench_program<B: SimBackend>(
.collect();
Some(
ExecutableTestbench::from_processes(processes, random_seed)
.with_kernels(kernels)
.with_scheduler(scheduler)
.with_clocks(clocks)
.with_private_signals(private_signals)
.with_component_runtime(
Expand Down
5 changes: 5 additions & 0 deletions crates/celox-testbench/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,15 @@ rust-version.workspace = true

[dependencies]
celox-design = { workspace = true }
celox-sir = { workspace = true }
celox-heap = { workspace = true }
num-bigint = { workspace = true }
num-traits = { workspace = true }
serde = { workspace = true }

[target.'cfg(target_arch = "x86_64")'.dev-dependencies]
celox-backend-x86 = { workspace = true }
celox-state-layout = { workspace = true }

[lints]
workspace = true
46 changes: 46 additions & 0 deletions crates/celox-testbench/src/expression.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//! A binding to an expression compiled as an ordinary SIR kernel.
//! Machine code is owned by the simulator backend and its program image.
use crate::{ExprBytecode, ExprOpcode as Opcode, ExpressionKernel};

#[derive(Clone, Debug)]
pub struct CompiledExpr {
bytecode: ExprBytecode,
observes_hardware: bool,
}
impl CompiledExpr {
pub fn new(bytecode: ExprBytecode) -> Self {
Self {
bytecode,
observes_hardware: true,
}
}
pub fn bytecode(&self) -> &ExprBytecode {
&self.bytecode
}
pub fn kernel(&self) -> Option<&ExpressionKernel<usize>> {
self.bytecode.kernel()
}
pub fn classify_hardware_access(mut self, mut hardware: impl FnMut(usize) -> bool) -> Self {
self.observes_hardware = self.bytecode.ops().iter().any(|op| match op {
Opcode::LoadU64 { location, .. }
| Opcode::LoadWide { location, .. }
| Opcode::LoadIndexed { location, .. }
| Opcode::LoadBitSelect { location, .. }
| Opcode::LoadString { location, .. }
| Opcode::StoreString { location, .. }
| Opcode::StoreU64 { location, .. } => hardware(*location),
_ => false,
});
self
}
pub fn observes_hardware(&self) -> bool {
self.observes_hardware
}
/// Literal folding for conservative binding-time overlap checks. General
/// constant folding belongs to the shared SIR optimizer.
pub fn constant_u64(&self) -> Option<u64> {
self.kernel()
.and_then(|kernel| kernel.constant)
.or_else(|| self.bytecode.literal_u64())
}
}
52 changes: 52 additions & 0 deletions crates/celox-testbench/src/expression_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
use crate::lowering::native_tests::evaluate;
use crate::{ExprOpcode as TbOpcode, TestbenchOperator as Op};
use celox_design::{FloatBinaryOp, FloatPrecision, FloatUnaryOp};

#[test]
fn deep_expression_compiles_without_a_runtime_operand_stack() {
for depth in [1, 8, 9, 32, 128, 129, 256] {
let mut ops: Vec<_> = (1..=depth).map(TbOpcode::ConstU64).collect();
ops.extend((1..depth).map(|_| TbOpcode::BinOp(Op::Add)));

assert_eq!(
evaluate(ops, &[]),
num_bigint::BigUint::from(depth * (depth + 1) / 2)
);
}
}

#[test]
fn floating_bytecode_keeps_precision_and_numeric_conversions() {
for (precision, expected) in [
(FloatPrecision::F32, 16777216),
(FloatPrecision::F64, 16777217),
] {
let ops = vec![
TbOpcode::ConstU64(16777216),
TbOpcode::FloatUnary {
op: FloatUnaryOp::FromUnsigned { width: 32 },
precision,
},
TbOpcode::ConstU64(1),
TbOpcode::FloatUnary {
op: FloatUnaryOp::FromUnsigned { width: 32 },
precision,
},
TbOpcode::FloatBinary {
op: FloatBinaryOp::Add,
precision,
},
TbOpcode::FloatUnary {
op: FloatUnaryOp::ToUnsigned {
width: 32,
round: true,
},
precision,
},
];
assert_eq!(
evaluate(ops, &[]),
num_bigint::BigUint::from(expected as u64)
);
}
}
Loading
Loading