From 72f732adf58f034a16e5deed320130dccae64610 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 01:55:08 +0900 Subject: [PATCH 1/4] perf(runtime): defer settles in compiled slots until their results are read The compiled scheduler settled combinational logic after every pass of the process phase and after the NBA region, as the reference loop does. Since #1811 it skips a settle whose inputs did not change, but the settle after a domain's commit ran in every slot that fired one, though usually only the host reads its results, at the end of the run. Such a settle now stays pending (the dirty flag stays set) until something observes it, and runs at the point the reference ran it last, so every observer sees the reference's values: - the host: before the run returns at its limit or after a clock overflow, which ends a complete slot; - a kernel that loads storage combinational logic writes, or may end the run in the middle of a slot ($finish, an error): before the slot it is due in, or, for a waiting kernel, which may wake in any pass, before every slot and pass; every kernel once a constant delay may overflow, as the run then returns in the middle of the slot; - a domain that may end the run, or reads combinational outputs without fused units: before it evaluates; slots that fire several domains whose units observe it: before their units; - a domain that reads combinational outputs and has fused units (Veryl): the fused units compute what it reads, then evaluate and apply. Combinational logic with effects of its own or that may fail keeps every settle where the reference has it. The waits the scheduler checks never watch combinational outputs, which a debug assertion now states. Change-Id: I5aa9c77efe9277bde745a55de530c352804f875e --- crates/celox/src/scheduler.rs | 466 ++++++++++++++++---- crates/celox/src/simulation/differential.rs | 136 +++++- docs/internals/optimizations.md | 7 + 3 files changed, 517 insertions(+), 92 deletions(-) diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs index 6287e96a9ee..00f29ecd707 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -11,6 +11,10 @@ //! each kernel in [`SchedulerSlots::wake`]. It inlines the units the //! reference loop calls, so their code is unchanged. //! +//! A settle whose results nothing reads before the next one is deferred +//! (see [`Lazy`]): it runs only before what observes it, at the point the +//! reference loop ran it. +//! //! Periodic host clocks (`add_clock`) on clock events no design code writes //! run in the same loop: their edges apply at the start of a slot, before //! any kernel, and re-arm at its end. A design without kernels gets the @@ -166,6 +170,44 @@ struct Plan { /// The storage combinational logic reads, when a settle whose inputs did /// not change may be skipped; `None` when every settle runs. settle_reads: Option>, + /// Where the settles run when they wait until their results are read; + /// `None` when every settle runs where the reference loop's does. + lazy: Option, +} + +/// Deferred settles. The reference loop settles after every pass of the +/// process phase and after the NBA region; the unit keeps such a settle +/// pending (the dirty flag stays set) until something observes its +/// results, and runs it where the reference ran it last, so every observer +/// sees what it sees in the reference: a kernel, before the slot it may run +/// in; a domain, before it evaluates (or the fused unit computes what it +/// reads); the host, before the run returns. Observers of the settled state +/// are units that load storage combinational logic writes, and units that +/// may end the run in the middle of a slot (`$finish`, an error), where the +/// reference's state is the last settle's. +struct Lazy { + /// Per process kernel, whether its runs observe the settled state. + kernels: Vec, + /// Per event, how its domain evaluates with a settle pending. + domains: Vec, + /// Whether the units of several triggered domains observe the settled + /// state. + several: bool, + /// The latest slot from which no delay of a kernel overflows: a run that + /// returns for an overflow in the middle of a later slot returns the last + /// settle's state. + latest: u64, +} + +/// How a domain evaluates while a settle is pending. +enum DomainSettle { + /// It does not observe the settled state. + Pending, + /// It reads what combinational logic writes: its fused units compute + /// what it reads, then evaluate and apply, leaving the settle pending. + Fused(Vec), + /// The settle runs first. + Settled, } impl Plan { @@ -547,6 +589,91 @@ impl Plan { }) .collect() }); + // A settle may wait for its readers only when it is a function of + // its inputs that cannot fail: when it would end the run, it must do + // so in its own slot. + let lazy = settle_reads + .as_ref() + .filter(|_| !sir.eval_comb.iter().any(fails)) + .map(|_| { + let comb_stores: HashSet = + sir.eval_comb.iter().flat_map(stores).collect(); + // The waits never watch what combinational logic writes, so + // they see the same with a settle pending. + debug_assert!( + kernels + .iter() + .flatten() + .filter_map(|kernel| kernel.wait.as_ref()) + .all(|wait| !comb_stores.contains(&storage(wait.signal))), + "a compiled wait watches a combinational output" + ); + let reads = + |unit: &Unit| loads(unit).any(|source| comb_stores.contains(&storage(source))); + let ends = |unit: &Unit| fails(unit) || emits_finish(unit, &finish_sites); + let observes = |unit: &Unit| reads(unit) || ends(unit); + let mut longest = 0; + for (index, kernel) in kernels.iter().enumerate() { + if kernel.as_ref().is_some_and(|kernel| kernel.wait.is_none()) { + let bound = + delay_bound(&sir.processes[index], schema.processes[index].delay); + longest = longest.max(bound); + } + } + let domains = events + .iter() + .map(|event| { + if event.eval_apply.iter().any(ends) { + return DomainSettle::Settled; + } + if !event.eval_apply.iter().any(reads) { + return DomainSettle::Pending; + } + let fused = &sir.eval_comb_apply_ffs; + let aliased = fused.keys().any(|key| { + *key != event.signal && topology.canonical(*key) == event.signal + }); + match fused.get(&event.signal) { + Some(units) if !aliased => DomainSettle::Fused(units.clone()), + _ => DomainSettle::Settled, + } + }) + .collect(); + let several = events.iter().any(|event| { + event + .eval_only + .iter() + .chain(&event.apply) + .flatten() + .any(observes) + }); + Lazy { + // A kernel's `$finish` is its status. + kernels: kernels + .iter() + .enumerate() + .map(|(index, kernel)| { + let unit = &sir.processes[index]; + kernel.is_some() + && (observes(unit) + || !statuses_only( + unit, + schema.processes[index].status, + &[ + ProcessStatus::Delay, + ProcessStatus::InactiveDelay, + ProcessStatus::Wait, + ProcessStatus::Nba, + ProcessStatus::Done, + ], + )) + }) + .collect(), + domains, + several, + latest: u64::MAX - longest, + } + }); let plan = Self { events, kernels, @@ -554,6 +681,7 @@ impl Plan { fallback, finish_sites, settle_reads, + lazy, }; let edged = plan.edged(); if edged.len() > 1 @@ -593,13 +721,17 @@ impl Plan { fn generate(&self, program: &LaidOutProgram, slots: &SchedulerSlots) -> Unit { let schema = &program.runtime.runtime_schema; let edged = self.edged(); + let mut b = Builder::new(); + let comb = b.new_block(); let mut g = Generator { - b: Builder::new(), + b, slots, finish_sites: &self.finish_sites, exits: Vec::new(), settle_reads: self.settle_reads.as_ref(), shared: program.shared_storage(), + comb, + continuations: Vec::new(), }; let waits: Vec<(usize, &Wait)> = self .kernels @@ -641,10 +773,14 @@ impl Plan { any = g.binary(1, any, BinaryOp::Or, waiting); } // Or the earliest next edge of a host clock, when the run has any. + // The clocks armed at the start of the slot, which the re-arm at its + // end compares with. + let mut started = None; if !self.clocks.is_empty() { let armed = g.load(slots.clock_armed, SCHEDULER_TIME_WIDTH); let zero = g.constant(0, SCHEDULER_CLOCKS); let clocked = g.binary(1, armed, BinaryOp::Ne, zero); + started = Some((armed, clocked)); let scan = g.b.new_block(); let joined_time = g.b.alloc_bit(SCHEDULER_TIME_WIDTH, false); let joined_any = g.b.alloc_bit(1, false); @@ -677,13 +813,70 @@ impl Plan { let stop = g.binary(1, after, BinaryOp::Or, none); let run = g.b.new_block(); let limit_exit = g.exit_block(SchedulerExit::Limit); + // The host reads the run's results settled. + let stopped = match &self.lazy { + Some(_) => g.b.new_block(), + None => limit_exit, + }; g.b.seal_block(SIRTerminator::Branch { cond: stop, - true_block: (limit_exit, Vec::new()), + true_block: (stopped, Vec::new()), false_block: (run, Vec::new()), }); + if self.lazy.is_some() { + g.b.switch_to_block(stopped); + g.settle_then(limit_exit); + } + // The kernels due now are ready. g.b.switch_to_block(run); + let mut ready = g.constant(0, MAX_KERNELS); + for &index in &delays { + let wake = g.load(slots.wake[index], SCHEDULER_TIME_WIDTH); + let waiting = g.waiting(index); + let due = g.binary(1, wake, BinaryOp::Eq, time); + let due = g.binary(1, due, BinaryOp::And, waiting); + let bit = g.bit(due, ordinals[index]); + ready = g.binary(MAX_KERNELS, ready, BinaryOp::Or, bit); + } + g.store(slots.ready, SCHEDULER_TIME_WIDTH, ready); + // A pending settle runs, as at the end of the last slot, before a + // kernel that observes it may run: one due now, any waiting one, + // which may wake in any pass, or any one in a slot after which a + // delay may overflow. + if let Some(lazy) = &self.lazy { + let waits = waits.iter().any(|&(index, _)| lazy.kernels[index]); + let observers = delays + .iter() + .filter(|&&index| lazy.kernels[index]) + .fold(0u64, |mask, &index| mask | 1 << ordinals[index]); + let late = lazy.latest < u64::MAX; + if waits || observers != 0 || late { + let mut observed = g.constant(u64::from(waits), 1); + if observers != 0 { + let mask = g.constant(observers, MAX_KERNELS); + let due = g.binary(MAX_KERNELS, ready, BinaryOp::And, mask); + let zero = g.constant(0, MAX_KERNELS); + let due = g.binary(1, due, BinaryOp::Ne, zero); + observed = g.binary(1, observed, BinaryOp::Or, due); + } + if late { + let latest = g.constant(lazy.latest, SCHEDULER_TIME_WIDTH); + let after = g.binary(1, time, BinaryOp::GtU, latest); + observed = g.binary(1, observed, BinaryOp::Or, after); + } + let settle = g.b.new_block(); + let slot = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: observed, + true_block: (settle, Vec::new()), + false_block: (slot, Vec::new()), + }); + g.b.switch_to_block(settle); + g.settle_then(slot); + g.b.switch_to_block(slot); + } + } g.store(slots.now, SCHEDULER_TIME_WIDTH, time); let count = g.load(slots.count, SCHEDULER_TIME_WIDTH); let one = g.constant(1, SCHEDULER_TIME_WIDTH); @@ -711,18 +904,6 @@ impl Plan { levels = g.binary(MAX_EVENTS, levels, BinaryOp::Or, value); } g.store(slots.levels, SCHEDULER_TIME_WIDTH, levels); - // The kernels due now are ready; the edges of the slot collect in - // `exit_arg`. - let mut ready = g.constant(0, MAX_KERNELS); - for &index in &delays { - let wake = g.load(slots.wake[index], SCHEDULER_TIME_WIDTH); - let waiting = g.waiting(index); - let due = g.binary(1, wake, BinaryOp::Eq, time); - let due = g.binary(1, due, BinaryOp::And, waiting); - let bit = g.bit(due, ordinals[index]); - ready = g.binary(MAX_KERNELS, ready, BinaryOp::Or, bit); - } - g.store(slots.ready, SCHEDULER_TIME_WIDTH, ready); // The host clocks due now set their levels, in event order, before // any kernel runs; their edges start the slot's edges, which // collect in `exit_arg`. A clock whose edge applied waits for its @@ -732,14 +913,7 @@ impl Plan { let finish_exit = g.exit_block(SchedulerExit::Finish); let internal_exit = g.exit_block(SchedulerExit::Internal); let pick = g.b.new_block(); - // The clocks armed at the start of the slot, which the re-arm at its - // end compares with. - let mut started = None; - if !self.clocks.is_empty() { - let armed = g.load(slots.clock_armed, SCHEDULER_TIME_WIDTH); - let zero = g.constant(0, SCHEDULER_CLOCKS); - let clocked = g.binary(1, armed, BinaryOp::Ne, zero); - started = Some((armed, clocked)); + if let Some((armed, clocked)) = started { let apply = g.b.new_block(); g.b.seal_block(SIRTerminator::Branch { cond: clocked, @@ -967,57 +1141,23 @@ impl Plan { } // The settles after a pass and after the domains share one copy of - // combinational logic. + // combinational logic. A deferred settle after a pass runs for the + // kernels that may run in another. g.b.switch_to_block(pass_end); let none = g.constant(u64::MAX, SCHEDULER_TIME_WIDTH); g.store(slots.current, SCHEDULER_TIME_WIDTH, none); - let comb = g.b.new_block(); - g.call_comb(comb, 1); - - // A settle whose inputs did not change since the last one would - // write what combinational logic already holds: it is skipped. - g.b.switch_to_block(comb); - if g.settle_reads.is_some() { - let dirty = g.load(slots.dirty, SCHEDULER_FLAG_WIDTH); - let zero = g.constant(0, SCHEDULER_FLAG_WIDTH); - let changed = g.binary(1, dirty, BinaryOp::Ne, zero); - let settle = g.b.new_block(); - let settled = g.b.new_block(); - g.b.seal_block(SIRTerminator::Branch { - cond: changed, - true_block: (settle, Vec::new()), - false_block: (settled, Vec::new()), - }); - g.b.switch_to_block(settle); - for unit in &program.sir.eval_comb { - g.inline(unit, finish_exit); - } - let clean = g.constant(0, SCHEDULER_FLAG_WIDTH); - g.store(slots.dirty, SCHEDULER_FLAG_WIDTH, clean); - g.b.seal_block(SIRTerminator::Jump(settled, Vec::new())); - g.b.switch_to_block(settled); - } else { - for unit in &program.sir.eval_comb { - g.inline(unit, finish_exit); - } - } - let continuation = g.load(slots.cont, SCHEDULER_FLAG_WIDTH); let settled = g.b.new_block(); let slot_end = g.b.new_block(); - g.b.seal_block(SIRTerminator::Switch { - selector: continuation, - cases: vec![ - SIRSwitchCase { - value: 1u8.into(), - target: settled, - }, - SIRSwitchCase { - value: 2u8.into(), - target: slot_end, - }, - ], - default: internal_exit, - }); + let wait_observers = self + .lazy + .as_ref() + .is_some_and(|lazy| waits.iter().any(|&(index, _)| lazy.kernels[index])); + match &self.lazy { + Some(_) => { + g.b.seal_block(SIRTerminator::Jump(settled, Vec::new())); + } + None => g.settle_then(settled), + } // After the settle of a pass the waits see its writes; woken // kernels run in another pass. @@ -1027,11 +1167,20 @@ impl Plan { let zero = g.constant(0, MAX_KERNELS); let more = g.binary(1, ready, BinaryOp::Ne, zero); let domains = g.b.new_block(); + let another = if wait_observers { + g.b.new_block() + } else { + pick + }; g.b.seal_block(SIRTerminator::Branch { cond: more, - true_block: (pick, Vec::new()), + true_block: (another, Vec::new()), false_block: (domains, Vec::new()), }); + if wait_observers { + g.b.switch_to_block(another); + g.settle_then(pick); + } // The domains the edges trigger, then the NBA region. g.b.switch_to_block(domains); @@ -1049,7 +1198,10 @@ impl Plan { // Without a domain, published nonblocking values settle once more. g.b.switch_to_block(untriggered); - if staged.is_empty() { + if self.lazy.is_some() { + g.publish(&staged); + g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); + } else if staged.is_empty() { g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); } else { let mut any = g.constant(0, 1); @@ -1065,7 +1217,7 @@ impl Plan { false_block: (slot_end, Vec::new()), }); g.b.switch_to_block(publish_settle); - g.call_comb(comb, 2); + g.settle_then(slot_end); } g.b.switch_to_block(triggered); @@ -1103,7 +1255,17 @@ impl Plan { false_block: (next, Vec::new()), }); g.b.switch_to_block(unit); - for unit in &event.eval_apply { + let units = match self.lazy.as_ref().map(|lazy| &lazy.domains[index]) { + None | Some(DomainSettle::Pending) => &event.eval_apply, + Some(DomainSettle::Fused(units)) => units, + Some(DomainSettle::Settled) => { + let evaluate = g.b.new_block(); + g.settle_then(evaluate); + g.b.switch_to_block(evaluate); + &event.eval_apply + } + }; + for unit in units { g.inline_writer(unit, finish_exit); } g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); @@ -1116,6 +1278,15 @@ impl Plan { if edged.len() < 2 { g.b.seal_block(SIRTerminator::Jump(internal_exit, Vec::new())); } else { + let mut mask = mask; + let mut zero = zero; + if self.lazy.as_ref().is_some_and(|lazy| lazy.several) { + let evaluate = g.b.new_block(); + g.settle_then(evaluate); + g.b.switch_to_block(evaluate); + mask = g.load(slots.exit_arg, MAX_EVENTS); + zero = g.constant(0, MAX_EVENTS); + } for phase in [Phase::Evaluate, Phase::Apply] { for &index in &edged { let event = &self.events[index]; @@ -1150,7 +1321,12 @@ impl Plan { // combinational logic settles. g.b.switch_to_block(evaluated); g.publish(&staged); - g.call_comb(comb, 2); + match &self.lazy { + Some(_) => { + g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); + } + None => g.settle_then(slot_end), + } // At the end of the slot each clock whose edge applied waits for the // opposite level, half a period later, in event order (as @@ -1210,7 +1386,13 @@ impl Plan { g.b.switch_to_block(overflowed); let clock = g.constant(bit as u64, SCHEDULER_TIME_WIDTH); g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, clock); - g.b.seal_block(SIRTerminator::Jump(overflow_exit, Vec::new())); + // The slot is complete: the host reads its results settled. + match &self.lazy { + Some(_) => g.settle_then(overflow_exit), + None => { + g.b.seal_block(SIRTerminator::Jump(overflow_exit, Vec::new())); + } + } g.b.switch_to_block(in_range); g.store_at( slots.clock_next, @@ -1231,6 +1413,7 @@ impl Plan { g.b.switch_to_block(rearmed); } g.b.seal_block(SIRTerminator::Jump(header, Vec::new())); + g.emit_settle(&program.sir.eval_comb, finish_exit, internal_exit); g.finish() } } @@ -1249,6 +1432,11 @@ struct Generator<'a> { /// See [`Plan::settle_reads`]. settle_reads: Option<&'a HashSet>, shared: HashMap, + /// The shared settle, emitted by [`Self::emit_settle`]. + comb: celox_sir::BlockId, + /// Where the shared settle continues, by case: case `i + 1` continues + /// at `continuations[i]`. + continuations: Vec, } impl Generator<'_> { @@ -1519,17 +1707,78 @@ impl Generator<'_> { } } - /// Run the shared settle, continuing at case `continuation` of its end. - fn call_comb(&mut self, comb: celox_sir::BlockId, continuation: u8) { - let value = self.constant(u64::from(continuation), SCHEDULER_FLAG_WIDTH); + /// Run the shared settle, then continue at `target`. The registers + /// `target` and its successors use must be defined in it or in the slot + /// loop's header, which alone dominates every entry of the settle. + fn settle_then(&mut self, target: celox_sir::BlockId) { + let case = match self.continuations.iter().position(|&block| block == target) { + Some(index) => index, + None => { + self.continuations.push(target); + self.continuations.len() - 1 + } + }; + let value = self.constant(case as u64 + 1, SCHEDULER_FLAG_WIDTH); self.store(self.slots.cont, SCHEDULER_FLAG_WIDTH, value); - self.b.seal_block(SIRTerminator::Jump(comb, Vec::new())); + self.b + .seal_block(SIRTerminator::Jump(self.comb, Vec::new())); + } + + /// Emit the shared settle: combinational logic, skipped when its inputs + /// did not change since the last one, as it would write what it already + /// holds; then the continuation of its caller. + fn emit_settle( + &mut self, + units: &[Unit], + finish_exit: celox_sir::BlockId, + internal_exit: celox_sir::BlockId, + ) { + self.b.switch_to_block(self.comb); + if self.settle_reads.is_some() { + let dirty = self.load(self.slots.dirty, SCHEDULER_FLAG_WIDTH); + let zero = self.constant(0, SCHEDULER_FLAG_WIDTH); + let changed = self.binary(1, dirty, BinaryOp::Ne, zero); + let settle = self.b.new_block(); + let settled = self.b.new_block(); + self.b.seal_block(SIRTerminator::Branch { + cond: changed, + true_block: (settle, Vec::new()), + false_block: (settled, Vec::new()), + }); + self.b.switch_to_block(settle); + for unit in units { + self.inline(unit, finish_exit); + } + let clean = self.constant(0, SCHEDULER_FLAG_WIDTH); + self.store(self.slots.dirty, SCHEDULER_FLAG_WIDTH, clean); + self.b.seal_block(SIRTerminator::Jump(settled, Vec::new())); + self.b.switch_to_block(settled); + } else { + for unit in units { + self.inline(unit, finish_exit); + } + } + let continuation = self.load(self.slots.cont, SCHEDULER_FLAG_WIDTH); + let cases = self + .continuations + .iter() + .enumerate() + .map(|(index, &target)| SIRSwitchCase { + value: (index as u8 + 1).into(), + target, + }) + .collect(); + self.b.seal_block(SIRTerminator::Switch { + selector: continuation, + cases, + default: internal_exit, + }); } /// Inline `unit`. A `$finish` record it emits ends the run after it, as /// the reference loop ends the slot after the unit that emitted one. fn inline(&mut self, unit: &Unit, finish_exit: celox_sir::BlockId) { - if self.finish_sites.is_empty() || !self.emits_finish(unit) { + if self.finish_sites.is_empty() || !emits_finish(unit, self.finish_sites) { self.b.inline_execution_unit(unit); return; } @@ -1547,13 +1796,6 @@ impl Generator<'_> { self.b.switch_to_block(next); } - fn emits_finish(&self, unit: &Unit) -> bool { - instructions(unit).any(|inst| { - matches!(inst, SIRInstruction::RuntimeEvent { site_id, .. } - if self.finish_sites.contains(site_id)) - }) - } - /// A copy of `unit` that sets the finish slot after every `$finish` /// record. fn instrument(&self, unit: &Unit) -> Unit { @@ -1651,6 +1893,58 @@ fn homes_overlap_only_whole(layout: &crate::backend::MemoryLayout) -> bool { homes.windows(2).all(|pair| pair[0].1 <= pair[1].0) } +/// The storage `unit` reads. +fn loads(unit: &Unit) -> impl Iterator + '_ { + instructions(unit).filter_map(|inst| match inst { + SIRInstruction::Load(_, source, ..) | SIRInstruction::Commit(source, ..) => { + Some(source.absolute_addr()) + } + _ => None, + }) +} + +/// Whether `unit` may end with an error. +fn fails(unit: &Unit) -> bool { + unit.blocks + .values() + .any(|block| matches!(block.terminator, SIRTerminator::Error(_))) +} + +/// Whether `unit` may record a `$finish`, one of `finish_sites`. +fn emits_finish(unit: &Unit, finish_sites: &HashSet) -> bool { + instructions(unit).any(|inst| { + matches!(inst, SIRInstruction::RuntimeEvent { site_id, .. } + if finish_sites.contains(site_id)) + }) +} + +/// The longest delay `unit` stores into `delay`: `u64::MAX` unless every +/// one is a constant. +fn delay_bound(unit: &Unit, delay: AbsoluteAddr) -> u64 { + let constants: HashMap = instructions(unit) + .filter_map(|inst| match inst { + SIRInstruction::Imm(register, value) => u64::try_from(&value.payload) + .ok() + .map(|value| (*register, value)), + _ => None, + }) + .collect(); + let delay = stable(delay); + instructions(unit) + .filter_map(|inst| match inst { + SIRInstruction::Store(target, offset, _, value, ..) if *target == delay => { + Some(match offset { + SIROffset::Static(0) => constants.get(value).copied().unwrap_or(u64::MAX), + _ => u64::MAX, + }) + } + SIRInstruction::Commit(_, target, ..) if *target == delay => Some(u64::MAX), + _ => None, + }) + .max() + .unwrap_or(0) +} + fn stable(address: AbsoluteAddr) -> RegionedAbsoluteAddr { RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address) } diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs index ccde1df4cfd..5aa02645edb 100644 --- a/crates/celox/src/simulation/differential.rs +++ b/crates/celox/src/simulation/differential.rs @@ -454,7 +454,8 @@ mod tests { /// A compiled kernel's `$finish` leaves the state the reference leaves: /// a kernel due in the same slot that did not run yet is still ready, - /// and a state file taken afterwards is the same. + /// combinational logic holds the last slot's settle, and a state file + /// taken afterwards is the same. #[test] fn compiled_slots_end_at_a_kernel_finish_as_the_reference_does() { let clock = "always #5 clk = ~clk;"; @@ -462,12 +463,13 @@ mod tests { for order in [[finish, clock], [clock, finish]] { let source = format!( "`timescale 1ns/1ns - module Top(output logic [7:0] count); + module Top(output logic [7:0] count, output logic [7:0] twice); logic clk = 1'b0; {} {} initial count = 8'd0; always_ff @(posedge clk) count <= count + 8'd1; + assign twice = count * 8'd2; endmodule", order[0], order[1] ); @@ -962,17 +964,18 @@ mod tests { /// The next edge of a host clock that overflows the simulation time /// fails the run as the reference's, after the clocks before it in the - /// slot re-armed. + /// slot re-armed and the slot settled. #[test] fn host_clock_overflow_fails_as_the_reference() { let source = r#" `timescale 1ns/1ns - module Top(input logic a, input logic b, output logic [7:0] n); + module Top(input logic a, input logic b, output logic [7:0] n, output logic [7:0] y); logic [7:0] ra = 8'd0; logic [7:0] rb = 8'd0; initial begin n = 8'd0; forever @(posedge b) n = n + 8'd1; end always_ff @(posedge a) ra <= ra + n; always_ff @(posedge b) rb <= rb + ra; + assign y = ra ^ rb; endmodule "#; let run = |mode: SchedulerMode| { @@ -1061,6 +1064,125 @@ mod tests { ); } + /// Settles wait for their readers, which see what they see in the + /// reference: a domain whose next state combinational logic computes, + /// a kernel that samples a combinational output after a delay, one that + /// samples it at an edge, in the pass after the clock's kernel changed + /// it, and the host between runs. + #[test] + fn deferred_settles_reach_their_readers() { + for reader in [ + "", + "always #3 seen = y;", + "initial forever @(negedge clk) seen = y + stim;", + ] { + let source = format!( + "`timescale 1ns/1ns + module Top(input logic [7:0] k, output logic [7:0] y); + logic clk = 1'b0; + logic [7:0] stim = 8'd0; + logic [7:0] r = 8'd0; + logic [7:0] q = 8'd0; + logic [7:0] seen = 8'd0; + logic [7:0] t = 8'd0; + logic [7:0] nxt; + always #5 begin t = t + 8'd1; clk = ~clk; end + always #7 stim = stim + 8'd1; + {reader} + always_comb nxt = r + stim + k; + always_ff @(posedge clk) r <= nxt; + always_ff @(posedge clk) q <= q + stim; + assign y = r ^ q ^ seen ^ t; + endmodule" + ); + host_driven_agrees( + &source, + &[ + (100, &[Host::Set("k", 1)]), + (200, &[Host::Set("k", 5)]), + (300, &[]), + ], + ); + } + } + + /// A domain whose next state combinational logic computes runs its + /// fused units with a settle pending: they compute what it reads. + #[test] + fn fused_domains_compute_what_they_read() { + let source = r#" + module Top ( + clk: input clock, + k : input logic<8>, + y : output logic<8>, + ) { + var r : logic<8>; + var nxt: logic<8>; + always_comb { + nxt = r + k; + } + always_ff (clk) { + r = nxt; + } + assign y = r ^ k; + } + "#; + let run = |mode: SchedulerMode| { + let mut sim = Simulation::builder(source, "Top") + .scheduler_mode(mode) + .build() + .unwrap(); + sim.add_clock("clk", 10, 5); + let k = sim.signal("k"); + let mut states = Vec::new(); + for (end, value) in [(100, 1u8), (200, 5), (300, 9)] { + sim.modify(|io| io.set(k, value)).unwrap(); + sim.run_until(end).unwrap(); + states.push(sim.save_state().unwrap()); + } + (states, sim.scheduler_stats().compiled_slots) + }; + let (expected, _) = run(SchedulerMode::Reference); + for mode in MODES { + let (states, compiled) = run(mode); + assert_eq!(states, expected, "{mode:?}"); + assert!(compiled > 0, "{mode:?}"); + } + } + + /// A `$fatal` in a domain ends the run with combinational logic as the + /// slot's settle before the domain left it. + #[test] + fn compiled_slots_fail_in_a_domain_as_the_reference() { + let source = r#" + `timescale 1ns/1ns + module Top(output logic [7:0] y); + logic clk = 1'b0; + logic [7:0] r = 8'd0; + always #5 clk = ~clk; + always_ff @(posedge clk) begin + r <= r + 8'd1; + if (r == 8'd6) $fatal(1, "stop"); + end + assign y = r * 8'd3; + endmodule + "#; + let run = |mode: SchedulerMode| { + let mut sim = build_in(source, mode); + let result = sim.run_until(1000).map_err(|error| error.to_string()); + (result, sim.time(), sim.save_state().unwrap(), sim) + }; + let (result, time, state, _) = run(SchedulerMode::Reference); + assert!(result.is_err(), "{result:?}"); + for mode in MODES { + let (mode_result, mode_time, mode_state, sim) = run(mode); + assert_eq!(mode_result, result, "{mode:?}"); + assert_eq!(mode_time, time, "{mode:?}"); + assert_eq!(mode_state, state, "{mode:?}"); + assert!(sim.scheduler_stats().compiled_slots > 0, "{mode:?}"); + } + } + /// A design without process kernels runs its host clocks in compiled /// slots: one domain, which has no units for several domains, coinciding /// domains and a domain-less edge, with host writes between runs and a @@ -1158,16 +1280,18 @@ mod tests { /// A compiled run of several slots that fails in a later one: the /// shadow catches up to that slot and fails the same way, so every mode - /// reports the reference's error and leaves its state. + /// reports the reference's error and leaves its state, combinational + /// outputs as the last slot settled them. #[test] fn compiled_runs_that_fail_after_several_slots_agree() { let source = r#" `timescale 1fs/1fs - module Top(output logic [7:0] x); + module Top(output logic [7:0] x, output logic [7:0] y); logic clk = 1'b0; logic [7:0] r = 8'd0; always #5 clk = ~clk; always_ff @(posedge clk) r <= r + 8'd1; + assign y = r + x; initial begin x = 8'd0; #30 x = 8'd1; diff --git a/docs/internals/optimizations.md b/docs/internals/optimizations.md index 7ecea17951a..12c2734c8e5 100644 --- a/docs/internals/optimizations.md +++ b/docs/internals/optimizations.md @@ -101,6 +101,13 @@ unnecessary: compile the clock's domain once more; the `derived_edge_units` selector (`-sir:derived_edge_units`, `SirPass::DerivedEdgeUnits`) turns them off to trade tick speed for build time. +- in the time slots a compiled scheduler runs, a combinational settle waits + until its results are read: it runs, where the reference loop last + settled, before a process kernel or domain that reads combinational outputs + or may end the run mid-slot (`$finish`, an error), and before the run + returns, so every reader sees the reference's values. A domain that only + reads combinational outputs runs its fused evaluate-and-commit units instead + where the frontend provides them (Veryl). These choices preserve the ordering model defined in [Runtime Semantics](./cascade-limitations.md). They do not change signal values or From 1344a30e46a2e029ba50184ff2219905157fa97e Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 01:16:17 +0900 Subject: [PATCH 2/4] fix(native): preserve array boundaries and store ordering in merged optimization Merged native optimization could drop one-hot LFSR state contributions when a padded unpacked scratch array was large, and store coalescing could move an earlier write past an overlapping overwrite. Preserve padded element boundaries at every array size and element width, and stop coalescing across overlapping writes and memory barriers while retaining disjoint-write optimization. Add shared regressions for function scratch arrays and partial overwrites, plus Native coverage of 58/65/129-bit elements in two/four-state modes at O0/O1/O2. Validation on master bd4fb45555: - SIR optimizer: 468 tests and one doctest pass; one existing ignored test. - Full SV suite: 4,495 pass, 20 existing ignored, including Native widths 58/65/129 x two/four-state x O0/O1/O2. - Six storage/function consumer suites: 240 pass, six existing ignored. - Affected library/integration clippy checks (-D warnings), formatting and diff checks pass. - Both unchanged shared regressions were independently checked with Verilator and Icarus. Upstream evidence on base 48f908e110: all 38 original Taxi LFSR configurations pass at O1/two-state, including the formerly incorrect scrambler and descrambler. A separate pre-existing 65-bit Wasm probe is outside this fix; the portable 58-bit regressions pass. Latest full-stack integration verification on master d34520d60d: - Full SV suite: 4,571 pass, 20 existing ignored. - Analyzer/frontend units: 802 pass, three existing ignored; two doctests pass. - Affected frontend/analyzer/Celox clippy checks (-D warnings), formatting and report-gate tests pass. CI follow-up validation: the false-loop suite passes all 25 tests. The reviewed disjoint-store coalescing snapshot is updated, and its fixed-point output is checked for all eight inputs; the snapshot test also passes independently on this stack member. Change-Id: I3a2eb46f622ccb63fe784ab98a9803a2858c14f7 --- .../src/optimizer/passes/memory/block_opt.rs | 125 +++++++++++++----- .../passes/memory/pass_coalesce_stores.rs | 94 ++++++++++--- .../src/sv/cases/procedural.vtest | 41 ++++++ crates/celox/src/optimizer/sir.rs | 7 +- crates/celox/tests/false_loop.rs | 21 +++ .../frontends/systemverilog/procedural.rs | 57 ++++++++ .../false_loop__scc_bit_cross_dependency.snap | 5 +- 7 files changed, 291 insertions(+), 59 deletions(-) diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/block_opt.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/block_opt.rs index 29b2be92e07..4132ef88968 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/memory/block_opt.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/memory/block_opt.rs @@ -351,30 +351,20 @@ fn coalesce_static_stores>> = HashMap::default(); - // Pre-index loads by address for efficient safety checks. - // Each entry is (instruction_index, offset, width, is_dynamic). - let mut load_index: HashMap, usize)>> = HashMap::default(); + // Moving a store to the end of a merged run must cross neither a read + // nor a later overlapping write. In particular, a narrow overwrite can + // sit between two adjacent candidate ranges in instruction order. + let mut access_index: HashMap, usize)>> = HashMap::default(); + let mut barriers = Vec::new(); for (idx, inst) in instructions.iter().enumerate() { - match inst { - SIRInstruction::Load(_, addr, SIROffset::Static(off), w) => { - load_index - .entry(addr.clone()) - .or_default() - .push((idx, Some(*off), *w)); - } - SIRInstruction::Load(_, addr, SIROffset::PackedElements { bit_offset, .. }, w) => { - load_index - .entry(addr.clone()) - .or_default() - .push((idx, Some(*bit_offset), *w)); - } - SIRInstruction::Load(_, addr, SIROffset::Dynamic(_) | SIROffset::Element { .. }, w) => { - load_index - .entry(addr.clone()) - .or_default() - .push((idx, None, *w)); - } - _ => {} + if is_memory_barrier(inst) { + barriers.push(idx); + } + if let Some((addr, offset, width, _)) = mem_access_info(inst) { + access_index + .entry(addr.clone()) + .or_default() + .push((idx, offset, width)); } } @@ -438,7 +428,7 @@ fn coalesce_static_stores insert_at_index { - return false; - } + let first_barrier = barriers.partition_point(|&idx| idx <= s.index); + if barriers + .get(first_barrier) + .is_some_and(|&idx| idx <= insert_at_index) + { + return false; + } + let first = accesses.partition_point(|&(idx, _, _)| idx <= s.index); + let end = accesses.partition_point(|&(idx, _, _)| idx <= insert_at_index); + !accesses[first..end].iter().any(|&(_, load_off, load_w)| { match load_off { None => true, // dynamic offset — conservatively unsafe Some(lo) => { @@ -1823,6 +1817,73 @@ mod tests { assert_eq!(reg_counter, 1); } + #[test] + fn store_coalescing_preserves_intervening_overlapping_writes() { + for intervening_offset in [ + SIROffset::Static(3), + SIROffset::PackedElements { + bit_offset: 3, + element_width: 1, + }, + SIROffset::Dynamic(RegisterId(2)), + SIROffset::Element { + index: RegisterId(2), + element_width: 2, + bit_offset: 1, + dynamic_bit_offset: None, + }, + ] { + let mut instructions = vec![ + SIRInstruction::Imm(RegisterId(0), SIRValue::new(0u8)), + SIRInstruction::Imm(RegisterId(1), SIRValue::new(1u8)), + SIRInstruction::Imm(RegisterId(2), SIRValue::new(1u8)), + SIRInstruction::Store(7u32, SIROffset::Static(2), 2, RegisterId(0), vec![], vec![]), + SIRInstruction::Store(7, intervening_offset, 1, RegisterId(1), vec![], vec![]), + SIRInstruction::Store(7, SIROffset::Static(1), 1, RegisterId(1), vec![], vec![]), + ]; + let original = instructions.clone(); + let mut registers = [ + (RegisterId(0), logic(2)), + (RegisterId(1), logic(1)), + (RegisterId(2), logic(32)), + ] + .into_iter() + .collect(); + let mut counter = 2; + // Merging the writes at bits 1 and 2..3 would move the latter + // past the intervening write of bit 3, erasing its new value. + assert!(!coalesce_static_stores_with_types( + &mut instructions, + &mut registers, + &mut counter, + &HashMap::default() + )); + assert_eq!(instructions, original); + } + } + + #[test] + fn store_coalescing_keeps_disjoint_intervening_writes_optimizable() { + let mut instructions = vec![ + SIRInstruction::Imm(RegisterId(0), SIRValue::new(0u8)), + SIRInstruction::Imm(RegisterId(1), SIRValue::new(1u8)), + SIRInstruction::Store(7u32, SIROffset::Static(2), 2, RegisterId(0), vec![], vec![]), + SIRInstruction::Store(7, SIROffset::Static(5), 1, RegisterId(1), vec![], vec![]), + SIRInstruction::Store(7, SIROffset::Static(1), 1, RegisterId(1), vec![], vec![]), + ]; + let mut registers = [(RegisterId(0), logic(2)), (RegisterId(1), logic(1))] + .into_iter() + .collect(); + let mut counter = 1; + assert!(coalesce_static_stores_with_types( + &mut instructions, + &mut registers, + &mut counter, + &HashMap::default() + )); + verify(instructions, registers); + } + #[test] fn store_coalescing_marks_cross_element_transfer_explicitly() { let mut instructions = (0..4) diff --git a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_coalesce_stores.rs b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_coalesce_stores.rs index 62c246c8e4b..7e265d4bce5 100644 --- a/crates/celox-sir-opt/src/optimizer/passes/memory/pass_coalesce_stores.rs +++ b/crates/celox-sir-opt/src/optimizer/passes/memory/pass_coalesce_stores.rs @@ -2,6 +2,7 @@ use crate::HashMap; use crate::HashSet; use crate::PassOptions; use crate::ir::*; +use std::collections::BTreeMap; use std::sync::Arc; use super::block_opt::aggregate_static_offset; @@ -51,6 +52,14 @@ struct StoreCandidate { comb_capture_sites: Vec, } +#[derive(Default)] +struct StoreGroup { + candidates: Vec, + // Open groups have disjoint ranges. The predecessor of a new range's + // end suffices to detect overlap without quadratic scans of large blocks. + ranges: BTreeMap, +} + fn coalesce_block( block: &mut BasicBlock, register_map: &mut HashMap, @@ -62,15 +71,38 @@ fn coalesce_block( // // groups: addr -> vec of candidates (current open group) // sealed_groups: completed groups ready for coalescing analysis - let mut groups: HashMap> = HashMap::default(); + let mut groups: HashMap = HashMap::default(); let mut sealed_groups: Vec> = Vec::new(); for (i, inst) in block.instructions.iter().enumerate() { + if inst.is_host_interaction() { + for (_, group) in groups.drain() { + if group.candidates.len() >= 2 { + sealed_groups.push(group.candidates); + } + } + } match inst { SIRInstruction::Store(addr, SIROffset::Static(off), width, src, triggers, sites) if triggers.is_empty() && sites.is_empty() => { - groups.entry(*addr).or_default().push(StoreCandidate { + let Some(end) = off.checked_add(*width) else { + seal_group(&mut groups, addr, &mut sealed_groups); + continue; + }; + let overlaps = groups.get(addr).is_some_and(|group| { + group + .ranges + .range(..end) + .next_back() + .is_some_and(|(_, &previous_end)| previous_end > *off) + }); + if overlaps { + seal_group(&mut groups, addr, &mut sealed_groups); + } + let group = groups.entry(*addr).or_default(); + group.ranges.insert(*off, end); + group.candidates.push(StoreCandidate { addr: *addr, inst_index: i, offset: *off, @@ -82,21 +114,12 @@ fn coalesce_block( SIRInstruction::Load(_, addr, _, _) => { seal_group(&mut groups, addr, &mut sealed_groups); } - SIRInstruction::Commit(src, _, _, _, _) => { - // Commit reads from src region + SIRInstruction::Commit(src, dst, _, _, _) => { seal_group(&mut groups, src, &mut sealed_groups); + seal_group(&mut groups, dst, &mut sealed_groups); } - // A Store with Dynamic offset could alias any static offset - SIRInstruction::Store( - addr, - SIROffset::Dynamic(_) - | SIROffset::Element { .. } - | SIROffset::PackedElements { .. }, - _, - _, - _, - _, - ) => { + // Noncandidate writes can overlap an open run or expose its state. + SIRInstruction::Store(addr, ..) => { seal_group(&mut groups, addr, &mut sealed_groups); } _ => {} @@ -104,9 +127,9 @@ fn coalesce_block( } // Flush remaining open groups - for (_, candidates) in groups.drain() { - if candidates.len() >= 2 { - sealed_groups.push(candidates); + for (_, group) in groups.drain() { + if group.candidates.len() >= 2 { + sealed_groups.push(group.candidates); } } @@ -273,13 +296,13 @@ fn coalesce_block( } fn seal_group( - groups: &mut HashMap>, + groups: &mut HashMap, addr: &RegionedAbsoluteAddr, sealed_groups: &mut Vec>, ) { - if let Some(candidates) = groups.remove(addr) { - if candidates.len() >= 2 { - sealed_groups.push(candidates); + if let Some(group) = groups.remove(addr) { + if group.candidates.len() >= 2 { + sealed_groups.push(group.candidates); } } } @@ -321,6 +344,33 @@ mod tests { } } + #[test] + fn overlapping_store_seals_the_open_run() { + let addr = make_addr(0); + for middle in [ + SIRInstruction::Store(addr, SIROffset::Static(3), 1, RegisterId(1), vec![], vec![]), + SIRInstruction::Commit(make_addr(1), addr, SIROffset::Static(3), 1, vec![]), + ] { + let instructions = vec![ + SIRInstruction::Imm(RegisterId(0), SIRValue::new(0u8)), + SIRInstruction::Imm(RegisterId(1), SIRValue::new(1u8)), + SIRInstruction::Store(addr, SIROffset::Static(2), 2, RegisterId(0), vec![], vec![]), + middle, + SIRInstruction::Store(addr, SIROffset::Static(1), 1, RegisterId(1), vec![], vec![]), + ]; + let registers = [ + (RegisterId(0), RegisterType::Logic { width: 2 }), + (RegisterId(1), RegisterType::Logic { width: 1 }), + ] + .into_iter() + .collect(); + let mut eu = make_eu(instructions.clone(), registers); + CoalesceStoresPass::default().run(&mut eu, &PassOptions::default()); + assert_eq!(eu.blocks[&BlockId(0)].instructions, instructions); + eu.verify(); + } + } + #[test] fn test_basic_contiguous_coalescing() { // 3 contiguous 1-bit stores to bits 0, 1, 2 of the same variable diff --git a/crates/celox-test-suite/src/sv/cases/procedural.vtest b/crates/celox-test-suite/src/sv/cases/procedural.vtest index 30c65da968d..26f8a919e5c 100644 --- a/crates/celox-test-suite/src/sv/cases/procedural.vtest +++ b/crates/celox-test-suite/src/sv/cases/procedural.vtest @@ -808,6 +808,47 @@ (eval) (assert_eq y 2)) +(case static_function_unpacked_scratch_bits_at_element_boundaries + (source "scratch_bits.sv" #" + module Top(input logic [5:0] index, output logic [57:0] y); + function [58:0] identity(input logic [5:0] selected); + logic [57:0] words[57:0]; + for (integer i=0; i<58; i=i+1) begin + words[i]='0; + words[i][i]=1'b1; + end + // The high result bit retains its value, so the function executes + // through the procedural path rather than symbolic substitution. + identity[57:0]=words[selected]; + endfunction + assign y=identity(index); + endmodule + "#) + (top Top) + (for bit (range 0 58) + (modify (set index bit)) + (assert_eq y (<< 1 bit)))) + +(case static_function_partial_writes_preserve_last_write + (source "partial_writes.sv" #" + module Top(input logic d, output wire [2:0] y); + function [4:0] update(input logic value); + update[3:2]='0; + update[3]=value; + update[1]=1'b1; + endfunction + wire [4:0] result=update(d); + assign y=result[3:1]; + endmodule + "#) + (top Top) + (modify (set d 1)) + (assert_eq y 5) + (modify (set d 0)) + (assert_eq y 1) + (modify (set d 1)) + (assert_eq y 5)) + (case constant_functions_preserve_concat_operand_widths (source "constant_concat.sv" #" module Top(output logic [15:0] a,b, output logic [7:0] zero_part); diff --git a/crates/celox/src/optimizer/sir.rs b/crates/celox/src/optimizer/sir.rs index e0fe93ea969..2d6987d2f47 100644 --- a/crates/celox/src/optimizer/sir.rs +++ b/crates/celox/src/optimizer/sir.rs @@ -115,9 +115,10 @@ pub(crate) fn optimize_native_merged_chain( .unpacked_arrays .iter() .filter(|(_, array)| { - (1..=64).contains(&array.element_width) - && array.element_stride * 8 != array.element_width - && array.plane_size <= 256 + // Element boundaries are a storage contract, including for + // large arrays and wide elements. Omitting them lets merged + // block optimization coalesce writes across padding gaps. + array.element_width != 0 && array.element_stride * 8 != array.element_width }) .flat_map(|(&address, array)| { [STABLE_REGION, WORKING_REGION, SPARSE_WORKING_REGION].map(move |region| { diff --git a/crates/celox/tests/false_loop.rs b/crates/celox/tests/false_loop.rs index 4429fd66402..e073b3eac9e 100644 --- a/crates/celox/tests/false_loop.rs +++ b/crates/celox/tests/false_loop.rs @@ -400,9 +400,30 @@ module Top ( (vec![], vec!["v".to_owned()]), ) .build_with_trace(); + let mut sim = result.res.unwrap(); let trace = result.trace; let sir_output = trace.format_program().unwrap(); + // Check the fixed point for every input before reviewing the optimized IR. + let select = sim.signal("sel"); + let input = sim.signal("i"); + let output = sim.signal("o"); + for select_value in 0u8..2 { + for input_value in 0u8..4 { + sim.modify(|io| { + io.set(select, select_value); + io.set(input, input_value); + }) + .unwrap(); + let bit = if select_value == 1 { + input_value & 1 + } else { + input_value >> 1 + }; + assert_eq!(sim.get(output), (bit * 3).into()); + } + } + // Snapshot will catch: // 1. Redundant emits of the mux/selection logic. // 2. Incorrect Store Forwarding where the 'old' value of v[x] is lost. diff --git a/crates/celox/tests/frontends/systemverilog/procedural.rs b/crates/celox/tests/frontends/systemverilog/procedural.rs index dd47e78f796..a9b5632084c 100644 --- a/crates/celox/tests/frontends/systemverilog/procedural.rs +++ b/crates/celox/tests/frontends/systemverilog/procedural.rs @@ -1,6 +1,63 @@ use super::*; +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +#[test] +fn native_merged_optimization_preserves_large_and_wide_array_boundaries() { + for width in [58, 65, 129] { + let source = format!( + r#" + module Top(input logic [7:0] index, output logic [{top}:0] y); + function [{width}:0] identity(input logic [7:0] selected); + logic [{top}:0] words[{top}:0]; + for (integer i=0; i<{width}; i=i+1) begin + words[i]='0; + words[i][i]=1'b1; + end + identity[{top}:0]=words[selected]; + endfunction + assign y=identity(index); + endmodule + "#, + top = width - 1, + ); + for four_state in [false, true] { + for level in [ + celox::OptLevel::O0, + celox::OptLevel::O1, + celox::OptLevel::O2, + ] { + let mut sim = Simulator::from_sv_sources( + vec![(&source, Path::new("native_array_boundaries.sv"))], + "Top", + ) + .four_state(four_state) + .opt_level(level) + .build_native() + .unwrap(); + let index = sim.signal("index"); + let y = sim.signal("y"); + for bit in 0..width { + sim.modify(|io| io.set(index, bit as u32)).unwrap(); + assert_eq!( + sim.get(y), + BigUint::from(1u8) << bit, + "width={width}, four_state={four_state}, level={level:?}, bit={bit}", + ); + } + } + } + } +} + sv_backends! { + fn static_function_partial_writes_preserve_last_write(sim) { + @case "procedural::static_function_partial_writes_preserve_last_write"; + } + + fn static_function_unpacked_scratch_bits_at_element_boundaries(sim) { + @case "procedural::static_function_unpacked_scratch_bits_at_element_boundaries"; + } + fn constant_functions_inside_selected_parameter_initializers(sim) { @case "procedural::constant_functions_inside_selected_parameter_initializers"; } diff --git a/crates/celox/tests/snapshots/false_loop__scc_bit_cross_dependency.snap b/crates/celox/tests/snapshots/false_loop__scc_bit_cross_dependency.snap index 429607a870b..bf976556a16 100644 --- a/crates/celox/tests/snapshots/false_loop__scc_bit_cross_dependency.snap +++ b/crates/celox/tests/snapshots/false_loop__scc_bit_cross_dependency.snap @@ -25,6 +25,7 @@ Execution Unit 0: r13: logic<64> r14: logic<64> r17: logic<2> + r18: bit<2> b0: r0 = Load(addr=sel (region=0), offset=0, bits=1) r1 = Load(addr=v (region=0), offset=0, bits=1) @@ -33,10 +34,10 @@ Execution Unit 0: r14 = r12 Shr r13 r2 = r14 And r13 r3 = Mux(cond=r0, then=r1, else=r2) - Store(addr=v (region=0), offset=1, bits=1, src_reg = 3) r4 = r12 And r13 r6 = Mux(cond=r0, then=r4, else=r3) - Store(addr=v (region=0), offset=0, bits=1, src_reg = 6) + r18 = Concat(r3, r6) + Store(addr=v (region=0), offset=0, bits=2, src_reg = 18) r8 = Mux(cond=r0, then=r6, else=r2) r10 = Mux(cond=r0, then=r4, else=r8) r17 = Concat(r8, r10) From a49828bb986215365c0bbe2c3e2bf7b59701c35d Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 04:28:49 +0900 Subject: [PATCH 3/4] ci: remove Lydite bridge from routine validation Change-Id: Id8090c5cbb732e2b632d7d0acb1cec6fe918ff2c --- .github/workflows/ci.yml | 4 +- .github/workflows/lydite-checks.yml | 112 +++------------------------ .github/workflows/nightly.yml | 5 +- .github/workflows/publish-crates.yml | 2 +- .github/workflows/rust-cache.yml | 2 +- CONTRIBUTING.md | 29 ++++--- lefthook.yml | 2 +- lydite/conformance/veryl/run_ci.sh | 2 +- scripts/ci-changes.mjs | 7 +- scripts/ci-changes.test.mjs | 10 +++ scripts/ci-lydite-changes.mjs | 25 ++---- scripts/ci-lydite-changes.test.mjs | 86 ++++++++++---------- scripts/ci-workflow.test.mjs | 6 +- 13 files changed, 94 insertions(+), 198 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a77cd3fe13a..7a7a4bb0e31 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -149,7 +149,7 @@ jobs: - name: cargo clippy if: (needs.changes.result != 'success' || needs.changes.outputs.rust == 'true') && needs.changes.outputs.rust_full != 'false' - run: cargo clippy --locked --workspace --all-targets --features celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus --no-deps + run: cargo clippy --locked --workspace --exclude lydite-celox --all-targets --features celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus --no-deps - name: Lint the crates this pull request can affect if: needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_lint_packages != '' @@ -162,7 +162,7 @@ jobs: if: (needs.changes.result != 'success' || needs.changes.outputs.rust == 'true') && needs.changes.outputs.rust_full != 'false' env: RUSTDOCFLAGS: -D warnings - run: cargo doc --locked --workspace --no-deps + run: cargo doc --locked --workspace --exclude lydite-celox --no-deps - name: Build the API documentation this pull request can affect if: needs.changes.outputs.rust_full == 'false' && needs.changes.outputs.rust_doc_libraries != '' diff --git a/.github/workflows/lydite-checks.yml b/.github/workflows/lydite-checks.yml index 92dff0e5283..1176b2834bc 100644 --- a/.github/workflows/lydite-checks.yml +++ b/.github/workflows/lydite-checks.yml @@ -5,8 +5,7 @@ name: Lydite # linted by ci.yml; this workflow owns Lydite tests and conformance gates. on: - # PRs select affected lanes; the heavy bridge runs on PRs only for Lydite-owned - # changes. Daily and manual runs enable every lane and report failures. + # Only Lydite core gates run here. Celox bridge/proof replay is disabled. pull_request: merge_group: schedule: @@ -37,7 +36,6 @@ jobs: runs-on: ubuntu-26.04 outputs: core: ${{ steps.scope.outputs.core }} - bridge: ${{ steps.scope.outputs.bridge }} defaults: run: working-directory: . @@ -57,7 +55,7 @@ jobs: rust: timeout-minutes: 30 needs: changes - if: always() && (needs.changes.result != 'success' || needs.changes.outputs.core == 'true' || needs.changes.outputs.bridge == 'true') + if: always() && (needs.changes.result != 'success' || needs.changes.outputs.core == 'true') runs-on: ubuntu-26.04 steps: - uses: actions/checkout@v7 @@ -72,21 +70,10 @@ jobs: - name: Install recorded solver version run: python -m pip install z3-solver==5.1.0 - name: Test affected Lydite packages and documentation - env: - CORE: ${{ needs.changes.outputs.core }} - BRIDGE: ${{ needs.changes.outputs.bridge }} - DETECTION: ${{ needs.changes.result }} run: | - args=() - if [ "$DETECTION" != success ] || [ "$CORE" = true ]; then - args+=(-p lydite -p lydite-ir -p lydite-solver -p lydite-syntax -p lydite-verify) - fi - if [ "$DETECTION" != success ] || [ "$BRIDGE" = true ]; then - args+=(-p lydite-celox) - fi Z3_BIN="$(command -v z3)" export Z3_BIN - cargo test --locked "${args[@]}" + cargo test --locked -p lydite -p lydite-ir -p lydite-solver -p lydite-syntax -p lydite-verify documentation: needs: changes @@ -110,7 +97,7 @@ jobs: persist-credentials: false - uses: ./.github/actions/setup-rust - name: Build the isolated editor worker - run: cargo build --release --locked --bin lydite-editor + run: cargo build --release --locked -p lydite --bin lydite-editor - name: Check bounded responses and reject deadlock and dropped-request mutants run: | cargo test --release --locked -p lydite --test responses --bin lydite-editor @@ -160,88 +147,9 @@ jobs: if-no-files-found: error retention-days: 14 - # The bridge lanes use the in-tree Celox and share one release build. - bridge: - needs: changes - if: always() && (needs.changes.result != 'success' || needs.changes.outputs.bridge == 'true') - runs-on: ubuntu-26.04 - # Cold builds plus replay and the sequential proof/mutation gates. - timeout-minutes: 150 - steps: - - uses: actions/checkout@v7 - with: - persist-credentials: false - - uses: ./.github/actions/setup-rust - with: - components: rustfmt - - name: Reproduce source violations and AXI4-Lite protocol regressions with Celox - run: ./conformance/axi4lite/run_ci.sh "$RUNNER_TEMP/celox-replay" - - name: Upload complete replay evidence - if: always() - uses: actions/upload-artifact@v7 - with: - name: celox-replay-${{ github.run_id }}-${{ github.run_attempt }} - path: ${{ runner.temp }}/celox-replay/ - if-no-files-found: error - retention-days: 14 - - # Keep collecting proof evidence after a replay failure. - # The conformance gates are pinned to Python 3.12. - - uses: actions/setup-python@v7 - if: ${{ !cancelled() }} - with: - python-version: "3.12" - - name: Run every reusable suite case with proof-backed reads - if: ${{ !cancelled() }} - run: ./conformance/veryl-proof/run_ci.sh "$RUNNER_TEMP/veryl-proof" - - name: Verify symbolic Veryl pipeline against ISA and reject RTL mutants - if: ${{ !cancelled() }} - run: ./conformance/veryl-symbolic/run_ci.sh "$RUNNER_TEMP/veryl-symbolic" - - name: Verify typed lemma candidates and proof-use diagnostics - if: ${{ !cancelled() }} - run: python3 -m audit.lemma_candidates.ci --out "$RUNNER_TEMP/lemma-candidates" - - name: Verify selected RV32I architecture, memory, latency and mutations - if: ${{ !cancelled() }} - run: ./conformance/veryl-symbolic/run_rv32i_ci.sh "$RUNNER_TEMP/selected-rv32i" - - name: Verify fixed automatic-proof held-outs and original-formula mutants - if: ${{ !cancelled() }} - run: ./conformance/veryl-symbolic/run_automatic_ci.sh "$RUNNER_TEMP/automatic-proof" - - name: Verify checked equality sharing and retain explicit Unknown diagnostics - if: ${{ !cancelled() }} - run: | - python3 -m unittest audit.equality_sharing.test_generate audit.equality_sharing.test_evidence audit.equality_sharing.test_ci - python3 -m audit.equality_sharing.ci --checker ../target/release/lydite --out "$RUNNER_TEMP/equality-sharing" - - name: Verify whole-word frontier controls and original-formula mutants - if: ${{ !cancelled() }} - run: | - python3 -m unittest audit.word_frontier.test_generate audit.word_frontier.test_ci - python3 -m audit.word_frontier.ci --checker ../target/release/lydite --expected-checker-sha256 "$(sha256sum ../target/release/lydite | cut -d' ' -f1)" --out "$RUNNER_TEMP/word-frontier" - - name: Verify guarded word expansion and reject escaped guards - if: ${{ !cancelled() }} - run: | - cargo test --release --locked -p lydite-solver equality_sharing::tests - python3 -m unittest audit.guarded_expansion.test_generate audit.guarded_expansion.test_ci - python3 -m audit.guarded_expansion.ci --checker ../target/release/lydite --expected-checker-sha256 "$(sha256sum ../target/release/lydite | cut -d' ' -f1)" --out "$RUNNER_TEMP/guarded-expansion" - - name: Upload proof and diagnostic evidence - if: always() - uses: actions/upload-artifact@v7 - with: - name: veryl-proof-${{ github.run_id }}-${{ github.run_attempt }} - path: | - ${{ runner.temp }}/veryl-proof/ - ${{ runner.temp }}/veryl-symbolic/ - ${{ runner.temp }}/selected-rv32i/ - ${{ runner.temp }}/automatic-proof/ - ${{ runner.temp }}/equality-sharing/ - ${{ runner.temp }}/word-frontier/ - ${{ runner.temp }}/guarded-expansion/ - ${{ runner.temp }}/lemma-candidates/ - if-no-files-found: error - retention-days: 14 - result: name: Lydite checks - needs: [changes, rust, documentation, editor, veryl-fv, bridge] + needs: [changes, rust, documentation, editor, veryl-fv] if: always() runs-on: ubuntu-26.04 defaults: @@ -256,17 +164,17 @@ jobs: import json, os needs = json.loads(os.environ["NEEDS"]) assert needs["changes"]["result"] == "success", needs - assert all(needs["changes"]["outputs"].get(key) in ("true", "false") for key in ("core", "bridge")), needs - for job, lane in {"rust": None, "documentation": "core", "editor": "core", "veryl-fv": "core", "bridge": "bridge"}.items(): + assert needs["changes"]["outputs"].get("core") in ("true", "false"), needs + for job in ("rust", "documentation", "editor", "veryl-fv"): outputs = needs["changes"]["outputs"] - selected = outputs.get(lane) == "true" if lane else any(outputs.get(key) == "true" for key in ("core", "bridge")) + selected = outputs.get("core") == "true" assert needs[job]["result"] == ("success" if selected else "skipped"), (job, needs[job]) PYCODE - # Report daily/manual runs; the bridge does not gate Celox PRs. + # Report daily/manual core runs. report: name: Report Lydite validation - needs: [changes, rust, documentation, editor, veryl-fv, bridge, result] + needs: [changes, rust, documentation, editor, veryl-fv, result] if: ${{ !cancelled() && (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') && (github.ref_name == 'master' || github.ref_name == 'develop') }} runs-on: ubuntu-26.04 permissions: diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml index bcc5e607f1e..58c3878c615 100644 --- a/.github/workflows/nightly.yml +++ b/.github/workflows/nightly.yml @@ -21,15 +21,14 @@ jobs: - name: Dispatch full CI on develop run: gh workflow run ci.yml --repo "$GITHUB_REPOSITORY" --ref develop - # lydite-checks.yml schedules the default branch itself; its bridge lanes do not run - # for Celox PRs, so check develop's in-tree Celox daily as well. + # Lydite core validation also runs on develop; bridge gates are disabled. queue-lydite-develop: name: Queue develop Lydite validation runs-on: ubuntu-latest env: GH_TOKEN: ${{ github.token }} steps: - - name: Dispatch every Lydite lane on develop + - name: Dispatch Lydite core validation on develop run: gh workflow run lydite-checks.yml --repo "$GITHUB_REPOSITORY" --ref develop # heliodor-bench.yml schedules the stable master lane directly. Dispatch the diff --git a/.github/workflows/publish-crates.yml b/.github/workflows/publish-crates.yml index adf6c1559f0..1854ecf87d2 100644 --- a/.github/workflows/publish-crates.yml +++ b/.github/workflows/publish-crates.yml @@ -107,7 +107,7 @@ jobs: - name: Build Rust API documentation env: RUSTDOCFLAGS: -D warnings - run: cargo doc --locked --workspace --no-deps + run: cargo doc --locked --workspace --exclude lydite-celox --no-deps publish: name: Publish to crates.io diff --git a/.github/workflows/rust-cache.yml b/.github/workflows/rust-cache.yml index b7113223635..c060a78f9ec 100644 --- a/.github/workflows/rust-cache.yml +++ b/.github/workflows/rust-cache.yml @@ -53,6 +53,6 @@ jobs: - name: Build test targets to populate dependencies if: steps.cache.outputs.cache-hit != 'true' run: >- - cargo nextest list --locked --workspace --message-format json + cargo nextest list --locked --workspace --exclude 'lydite*' --message-format json --features celox/systemverilog,celox-test-suite/verilator,celox-test-suite/icarus,celox-test-suite/runtime-cases > /dev/null diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b178404a8a2..1155a636b03 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -281,32 +281,31 @@ Job selection: Lydite has its own test cadence (`scripts/ci-lydite-changes.mjs`): -- Lydite sources and fixtures run its core and bridge lanes. The core lane owns - the proof-engine Rust tests, editor and standalone Veryl conformance. The - bridge lane (`bridge` job) runs replay and proof-backed Veryl/symbolic corpus - gates against the in-tree Celox exporter in one job sharing a release build. -- The bridge takes about an hour of runner time, so Celox changes do not run it - on PRs or queue drafts even when Cargo's dependency graph reaches - `lydite-celox`. The daily and manual runs on `master` (scheduled) and - `develop` (dispatched by `nightly.yml`) enable every lane and report failures - in the issue "Lydite validation is failing on ", closed by the next - passing run. NAPI/JS changes, upstream private tests and Markdown do not - reach Lydite. +- Lydite core sources and fixtures select proof-engine Rust tests, editor and + standalone Veryl conformance. Celox bridge/replay/proof-corpus CI is disabled + for PRs, merge queues, scheduled runs and manual workflow dispatches. + `lydite-celox` remains available for explicit local development, but normal + CI does not build, lint, document or test it. The routine pre-push Cargo + check also excludes it. +- Daily and manual core runs on `master` and `develop` report failures in the + issue "Lydite validation is failing on ". Celox and bridge-crate + changes do not select core gates. - Version-only Release Please diffs, including their queue drafts, skip Lydite. - PR workflows come from the PR's merge ref, so branches based on an older base still carry the earlier `lydite.yml`, which selected every lane. That workflow file stays disabled in repository settings; `lydite-checks.yml` replaces it. Re-enable nothing under the old path. - Shared dependency/toolchain configuration runs the core lane; an unreadable - diff or dependency graph runs both lanes. The graph includes optional, build + diff or dependency graph runs the core lane. The graph includes optional, build and dev edges. A `Cargo.lock` diff selects a lane only when a changed lock entry is in that lane's lockfile dependency closure, so adding a dependency to a Celox crate does not run Lydite. The Nix flake and `ci.yml` do not select Lydite; its jobs use neither. Celox's `conformance/sv-tests/` corpus also skips Lydite; Lydite's fixtures live under `lydite/conformance/`. - Ordinary `ci.yml` tests exclude `lydite*`, including daily and release runs; - formatting/lint/build checks remain there. The dedicated workflow tests the - selected Lydite packages, including doctests, and installs its solver. + lint and API documentation also exclude `lydite-celox`. The dedicated + workflow tests only core Lydite packages, including doctests, and installs + its solver. Cache warming excludes `lydite*`. - `Lydite checks` accepts skipped lanes only when change detection explicitly excludes them, and fails on selected-job failures or cancellations. Repository branch protection must require this check to make it a merge gate. @@ -360,7 +359,7 @@ Local validation uses the behavior-based matrix above. | Daily at 02:37 UTC (11:37 JST) | `heliodor-bench.yml` runs the complete master Linux suite on x86-64 and AArch64. Explicit manual selections retain focused suite runs and ARM64 profiling. PRs do not run this workflow; its tooling tests run in `Lint & Format` with the other script tests. | | Every daily/manual full CI run | Run the pinned upstream `common_cells` Gray code SV TB through `celox run --project`, plus an assertion negative control. Logs are retained for 14 days and failures feed the Full CI issue. See [the reproduction instructions](conformance/common-cells/README.md). | | Every full CI run | Run every shared Veryl and SystemVerilog case against both Verilator and Icarus, with locked Nix tools. Run the live adapter tests normally marked ignored because they need external tools. Preserve reports and per-case diagnostics as artifacts for 14 days, including on failure; matrix failures do not cancel the other comparisons. | -| Affected pull requests and merge groups; daily at 03:41 UTC (12:41 JST); on demand | `lydite-checks.yml` owns Lydite Rust tests, proof, conformance, editor, and mutation gates. Unrelated changes skip these jobs, and Celox changes skip the bridge. Daily and manual runs enable all lanes and report failures in an issue. | +| Affected pull requests and merge groups; daily at 03:41 UTC (12:41 JST); on demand | `lydite-checks.yml` owns Lydite Rust tests, proof, conformance, editor, and mutation gates. Unrelated changes skip these jobs. Bridge gates are disabled; daily and manual runs enable only core lanes and report failures in an issue. | | On demand | Dispatch `ci.yml` on the desired branch to run full CI and external comparisons, regardless of its diff. | | Pull requests that cut a release | A `master` pull request or legacy merge group whose diff changes `.release-please-manifest.json` (only the release pull request does there; syncing it into `develop` is not a release) runs full CI and the external comparisons. `Rust Test & NAPI Build` then requires the comparisons to pass, so a release cannot merge after only change-based checks. Daily and manual full runs do not gate on the comparisons; their failures reach the full CI issue below. A `master` pull request or legacy merge group whose diff cannot be determined is treated the same way. | diff --git a/lefthook.yml b/lefthook.yml index 74fa538bb1c..7f7af4133f7 100644 --- a/lefthook.yml +++ b/lefthook.yml @@ -18,4 +18,4 @@ pre-push: # builds, and documentation builds remain required in GitHub Actions. cargo-check: priority: 3 - run: cargo check --workspace --locked + run: cargo check --workspace --exclude lydite-celox --locked diff --git a/lydite/conformance/veryl/run_ci.sh b/lydite/conformance/veryl/run_ci.sh index 4847d8816f4..ba832516268 100755 --- a/lydite/conformance/veryl/run_ci.sh +++ b/lydite/conformance/veryl/run_ci.sh @@ -60,7 +60,7 @@ PY cd "$HERE" python3 generate.py # --locked forbids resolving newer dependencies. These are independent workspaces. -cargo build --release --locked --manifest-path "$REPO/../Cargo.toml" -p lydite-ir -p lydite -p lydite-celox -p lydite-solver -p lydite-syntax -p lydite-verify +cargo build --release --locked --manifest-path "$REPO/../Cargo.toml" -p lydite-ir -p lydite -p lydite-solver -p lydite-syntax -p lydite-verify cargo build --locked --manifest-path analyzer-probe/Cargo.toml --target-dir "$HERE/analyzer-probe/target" cargo build --locked --manifest-path Cargo.toml --target-dir "$HERE/target" -p extract-suite export LYDITE_BIN="$REPO/../target/release/lydite" diff --git a/scripts/ci-changes.mjs b/scripts/ci-changes.mjs index 3defbd38d10..a97b9d17302 100644 --- a/scripts/ci-changes.mjs +++ b/scripts/ci-changes.mjs @@ -305,7 +305,7 @@ if ( }); } -// Lydite tests are selected independently by lydite-checks.yml, including its bridge. +// Lydite core tests run independently; bridge CI is disabled. export function celoxRustTestScope(files, packages) { return rustTestScope( files.filter((path) => !/^(?:\.\/)?(?:lydite\/|crates\/lydite(?:-|\/))/.test(path)), @@ -324,7 +324,10 @@ export function rustScopeOutputs(files) { const packages = readWorkspace(root); scope = celoxRustTestScope(files, packages); // Lydite owns its tests, but lint and API documentation still live here. - checks = rustTestScope(files, packages); + checks = rustTestScope( + files.filter((path) => !/^(?:\.\/)?crates\/lydite-celox\//.test(path)), + packages.filter((pkg) => pkg.name !== "lydite-celox"), + ); } catch (error) { console.warn(`Unable to scope the Rust tests: ${error.message}`); } diff --git a/scripts/ci-changes.test.mjs b/scripts/ci-changes.test.mjs index d00b604c03a..7d2b80e76b2 100644 --- a/scripts/ci-changes.test.mjs +++ b/scripts/ci-changes.test.mjs @@ -597,3 +597,13 @@ test("VPI test-only edits do not select the unrelated ignored cocotb end-to-end assert.equal(rustScopeOutputs([path]).rust_vpi_e2e, true); assert.equal(rustScopeOutputs(null).rust_vpi_e2e, true); }); + + +test("disabled bridge is absent from every scoped test, lint and documentation plan", () => { + for (const path of ["crates/lydite-celox/src/lib.rs", "crates/celox/src/lib.rs", "crates/lydite-ir/src/lib.rs"]) { + const scope = rustScopeOutputs([path]); + assert.equal(scope.rust_full, false, path); + for (const key of ["rust_packages", "rust_libraries", "rust_lint_packages", "rust_doc_libraries", "rust_builds", "rust_lint_builds"]) + assert.ok(!scope[key].includes("lydite-celox"), `${path}: ${key}`); + } +}); diff --git a/scripts/ci-lydite-changes.mjs b/scripts/ci-lydite-changes.mjs index 8dec327c801..bc870e24ac2 100644 --- a/scripts/ci-lydite-changes.mjs +++ b/scripts/ci-lydite-changes.mjs @@ -6,7 +6,7 @@ import { changedFilesBetween, readWorkspace } from "./ci-rust-scope.mjs"; export const isLydite = (name) => name === "lydite" || name.startsWith("lydite-"); -const all = () => ({ core: true, bridge: true }); +const all = () => ({ core: true }); // Cargo.lock's `[[package]]` entries, keyed by "name version", with the names // each one depends on. @@ -40,7 +40,7 @@ export function lockChanges(baseText, headText) { // Follow actual Cargo edges, including optional, build and dev dependencies. // Celox consumes none of the proof engine; only lydite-celox consumes Celox. -// `lock` is lockChanges() of the diff; without it a Cargo.lock edit runs both. +// `lock` is lockChanges() of the diff; without it a Cargo.lock edit runs core checks. export function lyditeScope(files, packages, lock = null) { if (files === null) return all(); const byName = new Map(packages.map((pkg) => [pkg.name, pkg])); @@ -61,8 +61,7 @@ export function lyditeScope(files, packages, lock = null) { .filter((p) => isLydite(p.name) && p.name !== "lydite-celox") .map((p) => p.name); const core = closure(coreRoots); - const bridge = closure(["lydite-celox"]); - const result = { core: false, bridge: false }; + const result = { core: false }; const owners = [...packages].sort((a, b) => b.dir.length - a.dir.length); for (const raw of files) { const path = raw.replace(/^\.\//, ""); @@ -75,7 +74,6 @@ export function lyditeScope(files, packages, lock = null) { return [...lock.changed].some((name) => seen.has(name)); }; result.core ||= reaches(coreRoots); - result.bridge ||= reaches(["lydite-celox"]); continue; } if ( @@ -111,7 +109,6 @@ export function lyditeScope(files, packages, lock = null) { ) continue; result.core ||= core.has(owner.name); - result.bridge ||= bridge.has(owner.name); } else if ( ["crates/", "vendor/", "testdata/", "conformance/"].some((prefix) => path.startsWith(prefix), @@ -125,21 +122,9 @@ export function lyditeScope(files, packages, lock = null) { return result; } -// Celox dependency changes reach the bridge, but its replay and proof corpus -// are too heavy for every Celox PR. PRs run the bridge only for Lydite-owned -// sources; daily runs cover Celox and CI changes and report failures. -const ownsBridge = (path) => - ["lydite/", "crates/lydite"].some((prefix) => - path.replace(/^\.\//, "").startsWith(prefix), - ); - export function pullRequestScope(files, packages, lock = null) { - // Release PRs and their queue drafts only bump versions. - if (files !== null && isVersionOnlyRelease(files)) - return { core: false, bridge: false }; - const scope = lyditeScope(files, packages, lock); - if (files === null) return scope; - return { ...scope, bridge: scope.bridge && files.some(ownsBridge) }; + if (files !== null && isVersionOnlyRelease(files)) return { core: false }; + return lyditeScope(files, packages, lock); } // The lockfile at the merge base and at head, as changedFilesBetween compares. diff --git a/scripts/ci-lydite-changes.test.mjs b/scripts/ci-lydite-changes.test.mjs index b745af57b4a..fac8fdc01e6 100644 --- a/scripts/ci-lydite-changes.test.mjs +++ b/scripts/ci-lydite-changes.test.mjs @@ -14,10 +14,10 @@ import { readWorkspace } from "./ci-rust-scope.mjs"; const root = fileURLToPath(new URL("../", import.meta.url)); const packages = readWorkspace(root); const scope = (...files) => lyditeScope(files, packages); -const both = { core: true, bridge: true }; -const neither = { core: false, bridge: false }; +const coreOnly = { core: true }; +const neither = { core: false }; -test("Lydite core changes and shared configuration run both lanes", () => { +test("Lydite core changes and shared configuration run core checks", () => { for (const path of [ "crates/lydite/src/main.rs", "crates/lydite-ir/src/lib.rs", @@ -31,11 +31,11 @@ test("Lydite core changes and shared configuration run both lanes", () => { "crates/new/src/lib.rs", "conformance/new/case.sv", ]) - assert.deepEqual(scope(path), both, path); - assert.deepEqual(lyditeScope(null, packages), both); + assert.deepEqual(scope(path), coreOnly, path); + assert.deepEqual(lyditeScope(null, packages), coreOnly); }); -test("Celox dependencies select the bridge, without rerunning the editor/core", () => { +test("Celox and bridge changes do not select core checks", () => { for (const name of [ "celox", "celox-design", @@ -47,7 +47,7 @@ test("Celox dependencies select the bridge, without rerunning the editor/core", ]) assert.deepEqual( scope(`crates/${name}/src/lib.rs`), - { core: false, bridge: true }, + { core: false }, name, ); }); @@ -69,31 +69,14 @@ test("unrelated consumers and upstream private tests do not select Lydite", () = assert.deepEqual(scope(), neither); assert.deepEqual( scope("packages/celox/src/index.ts", "crates/lydite/src/main.rs"), - both, + coreOnly, ); }); -test("PRs run the bridge only for Lydite-owned changes", () => { - const pr = (...files) => pullRequestScope(files, packages); - for (const path of [ - "crates/celox/src/lib.rs", - "crates/celox-test-suite/src/veryl/cases/flip_flop.vtest", - ]) - assert.deepEqual(pr(path), neither, path); - for (const path of [ - "Cargo.lock", - "rust-toolchain.toml", - ".github/workflows/lydite-checks.yml", - "scripts/ci-lydite-changes.mjs", - ]) - assert.deepEqual(pr(path), { core: true, bridge: false }, path); - for (const path of [ - "crates/lydite-celox/src/lib.rs", - "crates/lydite/src/main.rs", - "lydite/conformance/veryl-proof/case-exceptions.json", - ]) - assert.equal(pr(path).bridge, true, path); - assert.deepEqual(pullRequestScope(null, packages), both); +test("bridge-only PRs do not select core gates", () => { + assert.deepEqual(pullRequestScope(["crates/lydite-celox/src/lib.rs"], packages), neither); + assert.deepEqual(pullRequestScope(["crates/lydite/src/main.rs"], packages), coreOnly); + assert.deepEqual(pullRequestScope(null, packages), coreOnly); }); test("Celox sv-tests changes skip Lydite without masking other changes", () => { @@ -116,12 +99,12 @@ test("Celox sv-tests changes skip Lydite without masking other changes", () => { "crates/lydite/src/main.rs", "lydite/conformance/veryl/run_ci.sh", ]) { - assert.deepEqual(pullRequestScope([...files, path], packages), both, path); - assert.deepEqual(pullRequestScope([path, ...files], packages), both, path); + assert.deepEqual(pullRequestScope([...files, path], packages), coreOnly, path); + assert.deepEqual(pullRequestScope([path, ...files], packages), coreOnly, path); } assert.deepEqual( pullRequestScope([...files, "conformance/unknown/case.sv"], packages), - { core: true, bridge: false }, + { core: true }, ); }); @@ -146,14 +129,13 @@ test("Cargo.lock edits select only the lanes that reach the changed entries", () ); assert.deepEqual(pr(edit("serde_json", "dependencies = [", "dependencies = [\n \"new\",")), { core: true, - bridge: false, }); assert.deepEqual( lyditeScope(["Cargo.lock"], packages, edit("celox", "dependencies = [", "dependencies = [\n \"new\",")), - { core: false, bridge: true }, + { core: false }, ); assert.deepEqual(pr(lockChanges(lockfile, lockfile)), neither); - assert.deepEqual(pr(null), { core: true, bridge: false }); + assert.deepEqual(pr(null), { core: true }); }); test("version-only release PRs skip Lydite", () => { @@ -171,10 +153,9 @@ test("version-only release PRs skip Lydite", () => { // Without the release manifest, Cargo changes are ordinary dependency edits. assert.deepEqual(pullRequestScope(release.slice(1), packages), { core: true, - bridge: false, }); assert.equal( - pullRequestScope([...release, "crates/lydite/src/main.rs"], packages).bridge, + pullRequestScope([...release, "crates/lydite/src/main.rs"], packages).core, true, ); }); @@ -196,10 +177,9 @@ test("dependency selection follows new transitive edges automatically", () => { ]; assert.deepEqual(lyditeScope(["crates/new-runtime/src/lib.rs"], graph), { core: false, - bridge: true, }); graph[0].dependencies.push("new-runtime"); - assert.deepEqual(lyditeScope(["crates/new-runtime/src/lib.rs"], graph), both); + assert.deepEqual(lyditeScope(["crates/new-runtime/src/lib.rs"], graph), coreOnly); }); test("Celox packages do not consume the excluded Lydite packages", () => { @@ -211,7 +191,7 @@ test("Celox packages do not consume the excluded Lydite packages", () => { } }); -test("daily, manual and unknown-diff invocations run every lane", () => { +test("daily, manual and unknown-diff invocations run only core gates", () => { for (const event of ["schedule", "workflow_dispatch", "merge_group"]) { const output = execFileSync( process.execPath, @@ -222,7 +202,7 @@ test("daily, manual and unknown-diff invocations run every lane", () => { encoding: "utf8", }, ); - assert.match(output, /core=true\nbridge=true/); + assert.match(output, /^core=true\n$/); } }); @@ -245,7 +225,6 @@ test("workflows transfer Rust tests and gate each Lydite lane", () => { ["documentation", "core"], ["editor", "core"], ["veryl-fv", "core"], - ["bridge", "bridge"], ]) { assert.ok( workflow.includes( @@ -254,7 +233,8 @@ test("workflows transfer Rust tests and gate each Lydite lane", () => { job, ); } - assert.match(workflow, /cargo test --locked "\$\{args\[@\]\}"/); + assert.match(workflow, /cargo test --locked -p lydite -p lydite-ir -p lydite-solver -p lydite-syntax -p lydite-verify/); + assert.doesNotMatch(workflow, / bridge:|outputs\.bridge|-p lydite-celox|conformance\/(axi4lite|veryl-proof|veryl-symbolic)/); assert.match( workflow, / report:\n name: Report Lydite validation\n[\s\S]*REPORT_NAME: Lydite validation\n run: node scripts\/report-full-ci\.mjs/, @@ -265,19 +245,18 @@ test("workflows transfer Rust tests and gate each Lydite lane", () => { .split(" PYCODE")[0] .replace(/^ /gm, ""); for (const core of [false, true]) - for (const bridge of [false, true]) { + { const needs = { changes: { result: "success", - outputs: { core: String(core), bridge: String(bridge) }, + outputs: { core: String(core) }, }, }; for (const [job, selected] of [ - ["rust", core || bridge], + ["rust", core], ["documentation", core], ["editor", core], ["veryl-fv", core], - ["bridge", bridge], ]) needs[job] = { result: selected ? "success" : "skipped" }; const run = () => @@ -315,3 +294,16 @@ test("scoped Celox PR tests also exclude the bridge and Lydite fixtures", () => assert.deepEqual(result.packages, []); } }); + + +test("normal CI and standalone core conformance never build the bridge", () => { + for (const pkg of packages.filter(p => p.name !== "lydite-celox")) + assert.ok(!pkg.dependencies.includes("lydite-celox"), pkg.name); + for (const path of [".github/workflows/ci.yml", ".github/workflows/publish-crates.yml"]) + assert.match(readFileSync(`${root}${path}`, "utf8"), /cargo doc --locked --workspace --exclude lydite-celox --no-deps/); + assert.match(readFileSync(`${root}.github/workflows/rust-cache.yml`, "utf8"), /cargo nextest list --locked --workspace --exclude 'lydite\*'/); + assert.match(readFileSync(`${root}lefthook.yml`, "utf8"), /cargo check --workspace --exclude lydite-celox --locked/); + const coreGate = readFileSync(`${root}lydite/conformance/veryl/run_ci.sh`, "utf8"); + assert.doesNotMatch(coreGate, /lydite-celox/); + assert.match(coreGate, /-p lydite-ir -p lydite -p lydite-solver -p lydite-syntax -p lydite-verify/); +}); diff --git a/scripts/ci-workflow.test.mjs b/scripts/ci-workflow.test.mjs index ed9ff3e9e7c..5eb9b86789d 100644 --- a/scripts/ci-workflow.test.mjs +++ b/scripts/ci-workflow.test.mjs @@ -389,7 +389,7 @@ test("cache warming shares the Rust Tests key and builds without running tests", assert.match(warm, /"scripts\/run-vtest.mjs"/); assert.match( warm, - /cargo nextest list --locked --workspace --message-format json/, + /cargo nextest list --locked --workspace --exclude 'lydite\*' --message-format json/, ); const features = job("rust-tests").match(/--features (\S+)/)[1]; assert.ok(warm.includes(`--features ${features}`)); @@ -501,8 +501,8 @@ test("cocotb retains Celox features without enabling unrelated adapter features" assert.match(job("rust-tests"), /name: Run cocotb VPI end-to-end test\n if: needs.changes.outputs.rust_vpi_e2e != 'false'/); }); -test("full Clippy validation covers every workspace crate", () => { - assert.match(job("lint"), /run: cargo clippy --locked --workspace --all-targets --features/); +test("full Clippy validation excludes the disabled bridge", () => { + assert.match(job("lint"), /run: cargo clippy --locked --workspace --exclude lydite-celox --all-targets --features/); }); test("upstream SV TB runs on full CI and feeds failure reporting", () => { From e7428ed453da2ab23a9cfd4414d420266cd7aad1 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 04:41:10 +0900 Subject: [PATCH 4/4] perf(runtime): settle stateful combinational logic where the reference does A deferred settle merges the settles it replaces into one, which is only equivalent when a settle is a function of its inputs. Combinational logic that keeps state between settles is not: a latch keeps what it captured while open, and the guarded units of `always @*` and similar processes run on a change of their inputs since their last activation, so a latch opened and closed between two observers, or inputs that changed and changed back, gave other results than the reference's. Combinational logic now settles lazily only when no settle reads what an earlier one left: every load of storage it writes is covered, on every path, by stores earlier in the same settle. Guarded units load their snapshots first, and feedback reads the previous value, so designs with either keep every settle where the reference has it, skipping only those whose inputs did not change. Change-Id: I568c6d92c6fa2c2b1a1fb64ffccfe1a3151aab5b --- crates/celox/src/scheduler.rs | 160 +++++++++++++++++++- crates/celox/src/simulation/differential.rs | 45 ++++++ docs/internals/optimizations.md | 4 +- 3 files changed, 203 insertions(+), 6 deletions(-) diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs index 00f29ecd707..9c58a9b5d39 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -184,7 +184,9 @@ struct Plan { /// reads); the host, before the run returns. Observers of the settled state /// are units that load storage combinational logic writes, and units that /// may end the run in the middle of a slot (`$finish`, an error), where the -/// reference's state is the last settle's. +/// reference's state is the last settle's. Only a settle that is a function +/// of its inputs may wait: one that reads what an earlier settle left (see +/// [`retains_state`]) is an activation of its own. struct Lazy { /// Per process kernel, whether its runs observe the settled state. kernels: Vec, @@ -591,13 +593,17 @@ impl Plan { }); // A settle may wait for its readers only when it is a function of // its inputs that cannot fail: when it would end the run, it must do - // so in its own slot. + // so in its own slot; when it reads what an earlier settle left (a + // latch, a guarded process's snapshots of its inputs, feedback), the + // settles in between are activations of their own. + let comb_stores: HashSet = sir.eval_comb.iter().flat_map(stores).collect(); let lazy = settle_reads .as_ref() - .filter(|_| !sir.eval_comb.iter().any(fails)) + .filter(|_| { + !sir.eval_comb.iter().any(fails) + && !retains_state(&sir.eval_comb, &storage, &comb_stores) + }) .map(|_| { - let comb_stores: HashSet = - sir.eval_comb.iter().flat_map(stores).collect(); // The waits never watch what combinational logic writes, so // they see the same with a settle pending. debug_assert!( @@ -1903,6 +1909,150 @@ fn loads(unit: &Unit) -> impl Iterator + '_ { }) } +/// Whether a settle of `units` may read what an earlier settle left: a load +/// of storage they write (`stores`, by representative) that stores earlier +/// in the same settle do not cover on every path. +fn retains_state( + units: &[Unit], + storage: &impl Fn(AbsoluteAddr) -> AbsoluteAddr, + stores: &HashSet, +) -> bool { + /// The bits of each home a settle has stored so far, as sorted, + /// disjoint `[start, end)` ranges. + type Covered = HashMap<(u32, AbsoluteAddr), Vec<(usize, usize)>>; + fn add(covered: &mut Covered, key: (u32, AbsoluteAddr), start: usize, end: usize) { + let ranges = covered.entry(key).or_default(); + ranges.push((start, end)); + ranges.sort_unstable(); + let mut merged: Vec<(usize, usize)> = Vec::with_capacity(ranges.len()); + for &(start, end) in ranges.iter() { + match merged.last_mut() { + Some(last) if start <= last.1 => last.1 = last.1.max(end), + _ => merged.push((start, end)), + } + } + *ranges = merged; + } + fn meet(a: &Covered, b: &Covered) -> Covered { + let mut met = Covered::default(); + for (key, left) in a { + let Some(right) = b.get(key) else { continue }; + let both: Vec<(usize, usize)> = left + .iter() + .flat_map(|&(ls, le)| { + right.iter().filter_map(move |&(rs, re)| { + let (start, end) = (ls.max(rs), le.min(re)); + (start < end).then_some((start, end)) + }) + }) + .collect(); + if !both.is_empty() { + met.insert(*key, both); + } + } + met + } + // Runs `block` from `covered`; `false` when a load reads what it does + // not cover. + let step = |block: &celox_sir::BasicBlock, covered: &mut Covered| { + for inst in &block.instructions { + match inst { + SIRInstruction::Load(_, source, offset, width) + | SIRInstruction::Commit(source, _, offset, width, _) => { + let home = storage(source.absolute_addr()); + if stores.contains(&home) { + let read = match offset { + SIROffset::Static(start) => { + covered.get(&(source.region, home)).is_some_and(|ranges| { + ranges + .iter() + .any(|&(s, e)| s <= *start && start + width <= e) + }) + } + _ => false, + }; + if !read { + return false; + } + } + } + _ => {} + } + match inst { + SIRInstruction::Store(target, SIROffset::Static(start), width, ..) + | SIRInstruction::Commit(_, target, SIROffset::Static(start), width, _) => add( + covered, + (target.region, storage(target.absolute_addr())), + *start, + start + width, + ), + _ => {} + } + } + true + }; + let mut entry = Covered::default(); + for unit in units { + // What every path stores before each block, from the paths found + // so far: a fixed point from above, as loops only remove. + let mut before: HashMap = HashMap::default(); + before.insert(unit.entry_block_id, entry.clone()); + let mut after: HashMap = HashMap::default(); + let mut changed = true; + while changed { + changed = false; + let mut ids: Vec<_> = unit.blocks.keys().copied().collect(); + ids.sort_unstable(); + for id in ids { + let Some(start) = before.get(&id).cloned() else { + continue; + }; + let mut covered = start; + if !step(&unit.blocks[&id], &mut covered) { + return true; + } + if after.get(&id) == Some(&covered) { + continue; + } + let successors: Vec<_> = match &unit.blocks[&id].terminator { + SIRTerminator::Jump(target, _) => vec![*target], + SIRTerminator::Branch { + true_block, + false_block, + .. + } => vec![true_block.0, false_block.0], + SIRTerminator::Switch { cases, default, .. } => cases + .iter() + .map(|case| case.target) + .chain([*default]) + .collect(), + SIRTerminator::Return | SIRTerminator::Error(_) => Vec::new(), + }; + for successor in successors { + let next = match before.get(&successor) { + Some(known) => meet(known, &covered), + None => covered.clone(), + }; + before.insert(successor, next); + } + after.insert(id, covered); + changed = true; + } + } + // The next unit starts from what every return of this one stored. + let mut returns = unit + .blocks + .iter() + .filter(|(_, block)| matches!(block.terminator, SIRTerminator::Return)) + .filter_map(|(id, _)| after.get(id)); + entry = match returns.next() { + Some(first) => returns.fold(first.clone(), |met, next| meet(&met, next)), + None => Covered::default(), + }; + } + false +} + /// Whether `unit` may end with an error. fn fails(unit: &Unit) -> bool { unit.blocks diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs index 5aa02645edb..8a8c3f1ff38 100644 --- a/crates/celox/src/simulation/differential.rs +++ b/crates/celox/src/simulation/differential.rs @@ -1106,6 +1106,51 @@ mod tests { } } + /// Combinational logic that keeps state between settles (a latch, the + /// snapshots an `always @*` waits on) settles where the reference + /// does: every activation in between counts, though no reader observes + /// it before the run ends. + #[test] + fn stateful_combinational_logic_settles_every_activation() { + let opened = r#" + `timescale 1ns/1ns + module Top(output logic [7:0] n); + logic [7:0] d = 8'd0; + logic en = 1'b0; + logic [7:0] q = 8'd0; + initial begin + #5 d = 8'd7; en = 1'b1; + #5 en = 1'b0; + #5 d = 8'd9; + end + always_latch if (en) q = d; + assign n = q; + endmodule + "#; + agrees_with_the_reference(opened, 30); + for process in [ + "always_latch if (g) l = d;", + "always @* if (g) l = d;", + "always @* l = d + 8'd1;", + ] { + let source = format!( + "`timescale 1ns/1ns + module Top(output logic [7:0] n); + logic clk = 1'b0; + logic [7:0] d = 8'd0; + logic g = 1'b1; + logic [7:0] l; + always #5 begin clk = ~clk; d = d + 8'd1; end + always_ff @(posedge clk) g <= ~g; + {process} + assign n = l; + endmodule" + ); + agrees_with_the_reference(&source, 30); + agrees_with_the_reference(&source, 300); + } + } + /// A domain whose next state combinational logic computes runs its /// fused units with a settle pending: they compute what it reads. #[test] diff --git a/docs/internals/optimizations.md b/docs/internals/optimizations.md index 12c2734c8e5..a10c48ca3b5 100644 --- a/docs/internals/optimizations.md +++ b/docs/internals/optimizations.md @@ -107,7 +107,9 @@ unnecessary: or may end the run mid-slot (`$finish`, an error), and before the run returns, so every reader sees the reference's values. A domain that only reads combinational outputs runs its fused evaluate-and-commit units instead - where the frontend provides them (Veryl). + where the frontend provides them (Veryl). Combinational logic that keeps state + between settles (latches, guarded processes such as `always @*`, feedback) + settles where the reference loop does. These choices preserve the ordering model defined in [Runtime Semantics](./cascade-limitations.md). They do not change signal values or