From 7972552dfbf76c3eefe8dfe06d8103f4f20aeeb1 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 13:29:18 +0900 Subject: [PATCH 1/3] fix(sv): keep the bit ranges a child reads from its input ports Flattening splits combinational paths at the bit boundaries each variable is accessed at, and propagates boundaries across port connections. Input ports only passed the parent's boundaries to the child, so where a child read its input port in parts the connected parent variable stayed one range. A parent that fed other bits of the child's output back into that variable then formed a combinational loop that does not exist; written in one module, the same logic simulates. The boundaries of the child port now propagate to the parent variable when the connection is one range as wide as the port, mapped onto that range, so the parent is split as it is when it reads the bits itself. Closes #1955 Change-Id: I24f244b6bb1f0b940eef0f1fbae08573ca011747 --- .../src/symbolic/assembly.rs | 43 +++++++++++++++ .../src/sv/cases/hierarchy.vtest | 54 +++++++++++++++++++ .../frontends/systemverilog/hierarchy.rs | 9 ++++ 3 files changed, 106 insertions(+) diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 8c11b502974..9f14b9f63ac 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2401,6 +2401,29 @@ fn extend_boundaries( target.len() != old_len } +/// Add the boundaries of `source` within its range to `target`, mapping the +/// range of `source` onto the equally wide range of `target`. +fn extend_shifted_boundaries( + boundaries: &mut HashMap>, + (source, source_access): (AbsoluteAddr, BitAccess), + (target, target_access): (AbsoluteAddr, BitAccess), +) -> bool { + let shifted: Vec = boundaries + .get(&source) + .into_iter() + .flatten() + .filter(|&&boundary| source_access.lsb <= boundary && boundary <= source_access.msb + 1) + .map(|&boundary| boundary - source_access.lsb + target_access.lsb) + .collect(); + if shifted.is_empty() || (source == target && source_access == target_access) { + return false; + } + let target = boundaries.entry(target).or_default(); + let old_len = target.len(); + target.extend(shifted); + target.len() != old_len +} + fn propagate_boundaries( bindings: &PackageBindings, expanded: &HashMap, @@ -2453,6 +2476,26 @@ fn propagate_boundaries( child_abs, ); } + + // Child -> Parent: where the child reads the + // port in parts, the connected range of a parent + // variable is read in the same parts, as in + // `a = {x[7:4], ...}` within one module. Only a + // connection of one range as wide as the port maps + // bit for bit. + let mut sources = child_addr.sources.iter(); + if let (Some(source), None) = (sources.next(), sources.next()) + && let GlueAddr::Parent(parent_var) = source.id + && source.access.msb - source.access.lsb + == target.access.msb - target.access.lsb + { + let parent_abs = bindings.locate(*id, parent_var); + changed |= extend_shifted_boundaries( + &mut current_boundaries, + (child_abs, target.access), + (parent_abs, source.access), + ); + } } } diff --git a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest index 6538509dbce..307729ae1be 100644 --- a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest +++ b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest @@ -1462,3 +1462,57 @@ (top Top) (eval) (assert_eq y (+ (<< 1 128) (+ (<< 2 43) 1))) (assert_eq width 129)) + +; A child's output port depends only on the bits of its input port that +; the child reads, so a parent may feed other bits of that output back into +; the port without a combinational loop (#1955). +(case child_ports_keep_the_bit_ranges_they_read + (source "port_bit_ranges.sv" #" + module Btb(input logic [7:0] ifpc_in, output logic [7:0] tar); + logic [3:0] tgt = 4'h9; + assign tar = {ifpc_in[7:4], tgt}; + endmodule + module Top; + logic clk = 0; + logic [7:0] tar, ifpc_out, fetch; + logic [7:0] ifpc = 8'h50; + assign fetch = tar; + always @(posedge clk) ifpc <= fetch; + assign ifpc_out = {ifpc[7:4], fetch[3:0]}; + Btb b(.ifpc_in(ifpc_out), .tar(tar)); + initial begin + #1 $display("%h", fetch); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "59\n")) + +; The same through a part-select of a wider parent variable connected to the +; input port: the bits the child reads map onto the selected range. +(case child_ports_keep_the_bit_ranges_of_selected_connections + (source "port_select_ranges.sv" #" + module Btb(input logic [7:0] ifpc_in, output logic [7:0] tar); + logic [3:0] tgt = 4'h9; + assign tar = {ifpc_in[7:4], tgt}; + endmodule + module Top; + logic clk = 0; + logic [7:0] tar, fetch; + logic [11:0] ifpc_out; + logic [7:0] ifpc = 8'h50; + assign fetch = tar; + always @(posedge clk) ifpc <= fetch; + assign ifpc_out = {ifpc[7:4], fetch[3:0], 4'h3}; + Btb b(.ifpc_in(ifpc_out[11:4]), .tar(tar)); + initial begin + #1 $display("%h %h", fetch, ifpc_out); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "59 593\n")) diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index 94f3838738b..ca63ad3c551 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -698,3 +698,12 @@ fn array_parameter_elements_check_unselected_conditional_branch_types() { ); } } + +sv_backends! { + fn child_ports_keep_the_bit_ranges_they_read(sim) { + @case "hierarchy::child_ports_keep_the_bit_ranges_they_read"; + } + fn child_ports_keep_the_bit_ranges_of_selected_connections(sim) { + @case "hierarchy::child_ports_keep_the_bit_ranges_of_selected_connections"; + } +} From 33445331f50fca6f1f20a096c512f77235573fa0 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 14:19:51 +0900 Subject: [PATCH 2/3] feat(runtime): run slots of designs with derived clocks in the compiled scheduler The compiled scheduler rejected every design with gated, inverted or divided clocks ("the design has derived clocks", "RTL logic drives an event signal"), so those designs ran every slot in the reference loop. It now tracks the clocks derived, transitively, from the events its slots change, and runs a slot's domains in the reference loop's waves: after the process phase, combinational logic settles; the domains of the events with an active edge evaluate together with those of the clocks gated by a changed source whose levels moved to their active edge, judged then, whose levels become their baselines; a slot without an active edge runs every tracked event whose level moved to its active edge. After each wave commits and logic settles, the domains not run yet whose clocks moved to their active edge run in another, until none does. Baselines are the levels of the tracked events at the slot's start, in the levels slot, which now covers the derived clocks too, so a run that returns in the middle of a slot leaves their levels as the reference does. RTL logic may drive exactly those derived clocks. A design with derived clocks keeps the reference loop when a waiting kernel stages nonblocking assignments, a tracked domain commits in the active region, or a tracked domain may end the run; and when the host observes a derived clock, which changes in the slots of its sources. Change-Id: Ibb48c1e36a21599607c012f0e6748de35e2616ae --- crates/celox-runtime/src/schedule.rs | 19 +- .../celox-runtime/src/simulation/compiled.rs | 3 + crates/celox/src/scheduler.rs | 599 +++++++++++++----- crates/celox/src/simulation/differential.rs | 76 +++ 4 files changed, 548 insertions(+), 149 deletions(-) diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index 85be69ad6e6..064c9049bad 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -83,6 +83,9 @@ pub(crate) struct SchedulerRefs { pub(crate) kernel_events: Vec, /// Per clock slot, the bit of `levels` of its event. pub(crate) clock_events: Vec, + /// The bits of `levels` of clocks derived from the others, which any + /// slot may change. + pub(crate) derived_events: u64, pub(crate) clock_next: SignalRef, pub(crate) clock_period: SignalRef, pub(crate) clock_value: SignalRef, @@ -324,7 +327,7 @@ impl ResolvedSchedule { time_slots: model.time_slots.iter().map(resolve).collect(), scheduler: model.scheduler.as_ref().and_then(|scheduler| { let slots = &scheduler.slots; - Some(SchedulerRefs { + let mut refs = SchedulerRefs { unit: scheduler.unit?, limit: resolve(&slots.limit), now: resolve(&slots.now), @@ -408,7 +411,19 @@ impl ResolvedSchedule { clock_period: resolve(&slots.clock_period), clock_value: resolve(&slots.clock_value), clock_armed: resolve(&slots.clock_armed), - }) + derived_events: 0, + }; + // What no kernel and no clock writes itself derives from them. + let all = 1u64 + .checked_shl(refs.events.len() as u32) + .map_or(u64::MAX, |bit| bit - 1); + let driven = refs + .kernel_events + .iter() + .chain(&refs.clock_events) + .fold(0, |mask, &bits| mask | bits); + refs.derived_events = all & !driven; + Some(refs) }), kernel_fallback: model .scheduler diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs index 5fff1ceb3e2..7173050bca6 100644 --- a/crates/celox-runtime/src/simulation/compiled.rs +++ b/crates/celox-runtime/src/simulation/compiled.rs @@ -75,6 +75,9 @@ impl SimulationState { || !pending.ready.is_empty() || !pending.inactive.is_empty() || !pending.nba_queue.is_empty() + // A derived clock changes with the slots of its sources, which + // the scheduler does not tell apart. + || self.observed_events & scheduler.derived_events != 0 || pending.waiters.iter().any(|(process, _)| { scheduler.waits.get(process).is_none_or(Option::is_none) || self.writes_observed(scheduler, process) diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs index ad23951dc38..1b8bc883877 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -20,6 +20,11 @@ //! any kernel, and re-arm at its end. A design without kernels gets the //! unit for its host clocks alone. //! +//! Clocks derived from the events the slots change (gated, inverted or +//! divided clocks, which RTL logic drives) run in the same slots: their +//! domains evaluate in the reference loop's waves, which judge each clock +//! against its level at the slot's start (see `Plan::batch`). +//! //! The runtime runs the unit only for slots that touch nothing else (see //! `celox_runtime::SimulationState::run_until_observed`): every other slot, //! and every design or kernel this module does not qualify, runs in the @@ -31,6 +36,7 @@ use celox_design::{ TIME_SLOT_WIDTH, schedule::ScheduleModel, }; use celox_sir::{BinaryOp, SIRBuilder, SIRSwitchCase, SIRValue}; +use std::collections::BTreeSet; use crate::{ HashMap, HashSet, @@ -88,7 +94,7 @@ pub(crate) fn attach(program: &mut LaidOutProgram) { // Without kernels, slots of host clocks alone. let unit = (plan.kernels.iter().any(Option::is_some) || !plan.clocks.is_empty()) .then(|| plan.generate(program, &schema.slots)); - let edged = plan.edged(); + let tracked = plan.tracked(); let kernel_events = plan .kernels .iter() @@ -97,14 +103,14 @@ pub(crate) fn attach(program: &mut LaidOutProgram) { .iter() .flat_map(|kernel| &kernel.writes) .map(|event| { - edged + tracked .binary_search(event) - .expect("the scheduler's kernels write edged events") + .expect("the scheduler's kernels write tracked events") }) .collect() }) .collect(); - let events = edged + let events = tracked .into_iter() .map(|event| plan.events[event].signal) .collect(); @@ -195,6 +201,14 @@ struct Plan { /// 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, + /// The clocks derived from the events the slots change, in event order, + /// as indices into [`Self::events`]: their domains run in the waves of + /// a slot (see `Generator::batch`). + derived: Vec, + /// The events the slots change that gate clocks computed + /// combinationally from them, with those clocks: their edges are judged + /// when the source changes. + gating: Vec<(usize, Vec)>, } /// Deferred settles. The reference loop settles after every pass of the @@ -245,12 +259,6 @@ impl Plan { return Err("the design counts event occurrences".into()); } let topology = &model.events; - if !topology.cascaded_events.is_empty() - || !topology.derived_events.is_empty() - || !topology.combinational_derived.is_empty() - { - return Err("the design has derived clocks".into()); - } if !schema.comb_observers.is_empty() { return Err("the design observes combinational processes".into()); } @@ -343,11 +351,9 @@ impl Plan { .chain(sir.eval_only_ffs.values().flatten()) .chain(sir.apply_ffs.values().flatten()) }; - for unit in rtl_units() { - if !written(unit).is_empty() { - return Err("RTL logic drives an event signal".into()); - } - } + // The events RTL logic drives: clocks derived from the events the + // scheduler's slots change, and only those (checked below). + let rtl_written: BTreeSet = rtl_units().flat_map(written).collect(); // A domain that commits its blocking results in the active region // evaluates before the NBA region when it triggers; a kernel that // may trigger it keeps the reference loop. @@ -704,7 +710,7 @@ impl Plan { latest: u64::MAX - longest, } }); - let plan = Self { + let mut plan = Self { events, kernels, clocks, @@ -712,10 +718,99 @@ impl Plan { finish_sites, settle_reads, lazy, + derived: Vec::new(), + gating: Vec::new(), }; let edged = plan.edged(); - if edged.len() > 1 - && edged.iter().any(|&event| { + // The clocks derived from the events the slots change, transitively: + // their levels change only through those events' domains and + // combinational logic. + let index_of: HashMap = plan + .events + .iter() + .enumerate() + .map(|(index, event)| (event.signal, index)) + .collect(); + let derived_from = |event: usize| -> Vec { + let signal = plan.events[event].signal; + topology + .derived_events + .get(&signal) + .into_iter() + .flatten() + .copied() + .chain( + topology + .combinational_derived + .get(&signal) + .into_iter() + .flatten() + .map(|clock| clock.clock), + ) + .filter_map(|address| index_of.get(&topology.canonical(address)).copied()) + .collect() + }; + let mut derived = BTreeSet::new(); + let mut pending = edged.clone(); + while let Some(event) = pending.pop() { + for next in derived_from(event) { + if !edged.contains(&next) && derived.insert(next) { + pending.push(next); + } + } + } + if !rtl_written.is_subset(&derived) { + return Err("RTL logic drives an event signal".into()); + } + let gating: Vec<(usize, Vec)> = edged + .iter() + .filter_map(|&source| { + let signal = plan.events[source].signal; + let gated: Vec = topology + .combinational_derived + .get(&signal) + .into_iter() + .flatten() + .filter_map(|clock| index_of.get(&topology.canonical(clock.clock)).copied()) + .filter(|gated| derived.contains(gated)) + .collect(); + (!gated.is_empty()).then_some((source, gated)) + }) + .collect(); + plan.derived = derived.into_iter().collect(); + plan.gating = gating; + let tracked = plan.tracked(); + if !plan.derived.is_empty() { + // The domains of a slot evaluate in waves until none triggers + // (see `Generator::batch`), which these the reference loop + // runs otherwise keep out of. + if plan + .kernels + .iter() + .flatten() + .filter_map(|kernel| kernel.wait.as_ref()) + .any(|wait| !wait.sites.is_empty()) + { + return Err("a design with derived clocks stages nonblocking assignments".into()); + } + if tracked.iter().any(|event| active_commits.contains(event)) { + return Err(ACTIVE_COMMIT.into()); + } + let ends = |unit: &Unit| fails(unit) || emits_finish(unit, &plan.finish_sites); + if tracked.iter().any(|&event| { + let event = &plan.events[event]; + event + .eval_apply + .iter() + .chain(event.eval_only.iter().flatten()) + .chain(event.apply.iter().flatten()) + .any(ends) + }) { + return Err("a domain of a design with derived clocks may end the run".into()); + } + } + if tracked.len() > 1 + && tracked.iter().any(|&event| { plan.events[event].eval_only.is_none() || plan.events[event].apply.is_none() }) { @@ -724,6 +819,16 @@ impl Plan { Ok(plan) } + /// The events whose levels the slots record and compare: those that + /// can have edges in them and the clocks derived from those, in event + /// order: the bits of [`SchedulerSlots::levels`]. + fn tracked(&self) -> Vec { + let mut tracked = self.edged(); + tracked.extend(&self.derived); + tracked.sort_unstable(); + tracked + } + /// The events the scheduler's kernels write, in event order: the only /// ones that can have edges in its slots. fn written(&self) -> Vec { @@ -751,6 +856,7 @@ impl Plan { fn generate(&self, program: &LaidOutProgram, slots: &SchedulerSlots) -> Unit { let schema = &program.runtime.runtime_schema; let edged = self.edged(); + let tracked = self.tracked(); let mut b = Builder::new(); let comb = b.new_block(); let mut g = Generator { @@ -922,7 +1028,7 @@ impl Plan { // exit in the middle of the slot; those of the clocks' events below, // when the run has clocks. let mut levels = g.constant(0, MAX_EVENTS); - for (bit, &event) in edged.iter().enumerate() { + for (bit, &event) in tracked.iter().enumerate() { if self.clocks.contains(&event) { continue; } @@ -963,10 +1069,10 @@ impl Plan { let due = g.binary(1, due, BinaryOp::And, on); let value = g.mask_bit(values, bit); let was = g.level(event); - let position = edged + let position = tracked .iter() - .position(|&edged| edged == index) - .expect("clocks are edged"); + .position(|&tracked| tracked == index) + .expect("clocks are tracked"); let level = g.bit(was, position); levels = g.binary(MAX_EVENTS, levels, BinaryOp::Or, level); let is = g.b.alloc_bit(1, false); @@ -1214,148 +1320,152 @@ impl Plan { // The domains the edges trigger, then the NBA region. g.b.switch_to_block(domains); - let staged: Vec<&Staged> = waits.iter().flat_map(|(_, wait)| &wait.sites).collect(); - let mask = g.load(slots.exit_arg, MAX_EVENTS); - let zero = g.constant(0, MAX_EVENTS); - let quiet = g.binary(1, mask, BinaryOp::Eq, zero); - let triggered = g.b.new_block(); - let untriggered = g.b.new_block(); - g.b.seal_block(SIRTerminator::Branch { - cond: quiet, - true_block: (untriggered, Vec::new()), - false_block: (triggered, Vec::new()), - }); - - // Without a domain, published nonblocking values settle once more. - g.b.switch_to_block(untriggered); - 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())); + if !self.derived.is_empty() { + self.batch(&mut g, &tracked, slot_end, finish_exit); } else { - let mut any = g.constant(0, 1); - for site in &staged { - let pending = g.load(site.pending, 1); - any = g.binary(1, any, BinaryOp::Or, pending); - } - g.publish(&staged); - let publish_settle = g.b.new_block(); + let staged: Vec<&Staged> = waits.iter().flat_map(|(_, wait)| &wait.sites).collect(); + let mask = g.load(slots.exit_arg, MAX_EVENTS); + let zero = g.constant(0, MAX_EVENTS); + let quiet = g.binary(1, mask, BinaryOp::Eq, zero); + let triggered = g.b.new_block(); + let untriggered = g.b.new_block(); g.b.seal_block(SIRTerminator::Branch { - cond: any, - true_block: (publish_settle, Vec::new()), - false_block: (slot_end, Vec::new()), + cond: quiet, + true_block: (untriggered, Vec::new()), + false_block: (triggered, Vec::new()), }); - g.b.switch_to_block(publish_settle); - g.settle_then(slot_end); - } - g.b.switch_to_block(triggered); - let evaluated = g.b.new_block(); - if edged.is_empty() { - // No event can have an edge; the mask stays empty. - g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); - } else { - let one = g.constant(1, MAX_EVENTS); - let lower = g.binary(MAX_EVENTS, mask, BinaryOp::Sub, one); - let others = g.binary(MAX_EVENTS, mask, BinaryOp::And, lower); - let single = g.binary(1, others, BinaryOp::Eq, zero); - let one_domain = g.b.new_block(); - let domains = g.b.new_block(); - g.b.seal_block(SIRTerminator::Branch { - cond: single, - true_block: (one_domain, Vec::new()), - false_block: (domains, Vec::new()), - }); + // Without a domain, published nonblocking values settle once more. + g.b.switch_to_block(untriggered); + 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); + for site in &staged { + let pending = g.load(site.pending, 1); + any = g.binary(1, any, BinaryOp::Or, pending); + } + g.publish(&staged); + let publish_settle = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: any, + true_block: (publish_settle, Vec::new()), + false_block: (slot_end, Vec::new()), + }); + g.b.switch_to_block(publish_settle); + g.settle_then(slot_end); + } - // One triggered domain evaluates and applies at once. The events - // kernels write are tested first: a run without clocks reaches - // their domains as soon as without clock events. - g.b.switch_to_block(one_domain); - let written = self.written(); - for &index in written.iter().chain(&self.clocks) { - let event = &self.events[index]; - let bit = g.constant(1 << index, MAX_EVENTS); - let this = g.binary(1, mask, BinaryOp::Eq, bit); - let unit = g.b.new_block(); - let next = g.b.new_block(); + g.b.switch_to_block(triggered); + let evaluated = g.b.new_block(); + if edged.is_empty() { + // No event can have an edge; the mask stays empty. + g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); + } else { + let one = g.constant(1, MAX_EVENTS); + let lower = g.binary(MAX_EVENTS, mask, BinaryOp::Sub, one); + let others = g.binary(MAX_EVENTS, mask, BinaryOp::And, lower); + let single = g.binary(1, others, BinaryOp::Eq, zero); + let one_domain = g.b.new_block(); + let domains = g.b.new_block(); g.b.seal_block(SIRTerminator::Branch { - cond: this, - true_block: (unit, Vec::new()), - false_block: (next, Vec::new()), + cond: single, + true_block: (one_domain, Vec::new()), + false_block: (domains, Vec::new()), }); - g.b.switch_to_block(unit); - 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) => { + + // One triggered domain evaluates and applies at once. The events + // kernels write are tested first: a run without clocks reaches + // their domains as soon as without clock events. + g.b.switch_to_block(one_domain); + let written = self.written(); + for &index in written.iter().chain(&self.clocks) { + let event = &self.events[index]; + let bit = g.constant(1 << index, MAX_EVENTS); + let this = g.binary(1, mask, BinaryOp::Eq, bit); + let unit = g.b.new_block(); + let next = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: this, + true_block: (unit, Vec::new()), + false_block: (next, Vec::new()), + }); + g.b.switch_to_block(unit); + 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())); + g.b.switch_to_block(next); + } + g.b.seal_block(SIRTerminator::Jump(internal_exit, Vec::new())); + + // Several evaluate, then apply, each in event order. + g.b.switch_to_block(domains); + 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); - &event.eval_apply + mask = g.load(slots.exit_arg, MAX_EVENTS); + zero = g.constant(0, MAX_EVENTS); } - }; - for unit in units { - g.inline_writer(unit, finish_exit); - } - g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); - g.b.switch_to_block(next); - } - g.b.seal_block(SIRTerminator::Jump(internal_exit, Vec::new())); - - // Several evaluate, then apply, each in event order. - g.b.switch_to_block(domains); - 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]; - let bit = g.constant(1 << index, MAX_EVENTS); - let selected = g.binary(MAX_EVENTS, mask, BinaryOp::And, bit); - let this = g.binary(1, selected, BinaryOp::Ne, zero); - let unit = g.b.new_block(); - let next = g.b.new_block(); - g.b.seal_block(SIRTerminator::Branch { - cond: this, - true_block: (unit, Vec::new()), - false_block: (next, Vec::new()), - }); - g.b.switch_to_block(unit); - let units = match phase { - Phase::Evaluate => event.eval_only.as_ref(), - Phase::Apply => event.apply.as_ref(), - } - .expect("several edged events have their units (`Plan::new`)"); - for unit in units { - g.inline_writer(unit, finish_exit); + for phase in [Phase::Evaluate, Phase::Apply] { + for &index in &edged { + let event = &self.events[index]; + let bit = g.constant(1 << index, MAX_EVENTS); + let selected = g.binary(MAX_EVENTS, mask, BinaryOp::And, bit); + let this = g.binary(1, selected, BinaryOp::Ne, zero); + let unit = g.b.new_block(); + let next = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: this, + true_block: (unit, Vec::new()), + false_block: (next, Vec::new()), + }); + g.b.switch_to_block(unit); + let units = match phase { + Phase::Evaluate => event.eval_only.as_ref(), + Phase::Apply => event.apply.as_ref(), + } + .expect("several edged events have their units (`Plan::new`)"); + for unit in units { + g.inline_writer(unit, finish_exit); + } + g.b.seal_block(SIRTerminator::Jump(next, Vec::new())); + g.b.switch_to_block(next); } - g.b.seal_block(SIRTerminator::Jump(next, Vec::new())); - g.b.switch_to_block(next); } + g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); } - g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); } - } - // The domains' results and the nonblocking values publish before - // combinational logic settles. - g.b.switch_to_block(evaluated); - g.publish(&staged); - match &self.lazy { - Some(_) => { - g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); + // The domains' results and the nonblocking values publish before + // combinational logic settles. + g.b.switch_to_block(evaluated); + g.publish(&staged); + match &self.lazy { + Some(_) => { + g.b.seal_block(SIRTerminator::Jump(slot_end, Vec::new())); + } + None => g.settle_then(slot_end), } - None => g.settle_then(slot_end), } // At the end of the slot each clock whose edge applied waits for the @@ -1448,6 +1558,177 @@ impl Plan { } } +impl Plan { + /// The domains of a slot of a design with derived clocks, as the + /// reference loop's waves run them: combinational logic settles; the + /// domains of the events with an active edge evaluate together with + /// those of the clocks computed combinationally from a changed source + /// whose level moved to their active edge, judged now, whose levels + /// become their baseline; without an active edge, every tracked event + /// whose level moved to its active edge since the slot started. After + /// each wave commits and logic settles, the domains not run yet whose + /// clocks moved to their active edge run in another, until none does. + /// The domains run in the slot collect in `exit_arg`. + fn batch( + &self, + g: &mut Generator<'_>, + tracked: &[usize], + slot_end: celox_sir::BlockId, + finish_exit: celox_sir::BlockId, + ) { + let slots = g.slots; + let wave = g.b.new_block(); + let mask = g.b.alloc_bit(MAX_EVENTS, false); + let fire = g.b.new_block_with(vec![mask]); + let judge = g.b.new_block(); + // A pass of the process phase settles before the domains; a + // deferred one runs now. + match &self.lazy { + Some(_) => g.settle_then(judge), + None => { + g.b.seal_block(SIRTerminator::Jump(judge, Vec::new())); + } + } + + g.b.switch_to_block(judge); + let active = g.load(slots.exit_arg, MAX_EVENTS); + let levels = g.load(slots.levels, MAX_EVENTS); + let stable = self.stable_edges(g, tracked, levels); + let mut gated_edges = g.constant(0, MAX_EVENTS); + let mut judged = levels; + for (source, gated) in &self.gating { + let source_bit = position(tracked, *source); + let was = g.mask_bit(levels, source_bit); + let is = g.level(&self.events[*source]); + let changed = g.binary(1, was, BinaryOp::Ne, is); + for &clock in gated { + let clock_bit = position(tracked, clock); + let was = g.mask_bit(levels, clock_bit); + let is = g.level(&self.events[clock]); + let edge = g.edge(&self.events[clock], was, is); + let edge = g.binary(1, edge, BinaryOp::And, changed); + let bit = g.bit(edge, clock); + gated_edges = g.binary(MAX_EVENTS, gated_edges, BinaryOp::Or, bit); + // The judged level is the clock's baseline from now on. + let level = g.b.alloc_bit(1, false); + g.b.emit(SIRInstruction::Mux(level, changed, is, was)); + let keep = g.constant(!(1u64 << clock_bit), MAX_EVENTS); + let kept = g.binary(MAX_EVENTS, judged, BinaryOp::And, keep); + let bit = g.bit(level, clock_bit); + judged = g.binary(MAX_EVENTS, kept, BinaryOp::Or, bit); + } + } + g.store(slots.levels, SCHEDULER_TIME_WIDTH, judged); + let zero = g.constant(0, MAX_EVENTS); + let edged = g.binary(1, active, BinaryOp::Ne, zero); + let sources = g.binary(MAX_EVENTS, active, BinaryOp::Or, gated_edges); + let triggers = g.b.alloc_bit(MAX_EVENTS, false); + g.b.emit(SIRInstruction::Mux(triggers, edged, sources, stable)); + g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, triggers); + let quiet = g.binary(1, triggers, BinaryOp::Eq, zero); + let first = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: quiet, + true_block: (slot_end, Vec::new()), + false_block: (first, Vec::new()), + }); + g.b.switch_to_block(first); + g.b.seal_block(SIRTerminator::Jump(fire, vec![triggers])); + + // A wave after a commit: the domains not run yet whose clocks moved. + g.b.switch_to_block(wave); + let fired = g.load(slots.exit_arg, MAX_EVENTS); + let levels = g.load(slots.levels, MAX_EVENTS); + let stable = self.stable_edges(g, tracked, levels); + let all = g.constant(u64::MAX, MAX_EVENTS); + let unfired = g.binary(MAX_EVENTS, fired, BinaryOp::Xor, all); + let ready = g.binary(MAX_EVENTS, stable, BinaryOp::And, unfired); + let zero = g.constant(0, MAX_EVENTS); + let quiet = g.binary(1, ready, BinaryOp::Eq, zero); + let next = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: quiet, + true_block: (slot_end, Vec::new()), + false_block: (next, Vec::new()), + }); + g.b.switch_to_block(next); + let fired = g.binary(MAX_EVENTS, fired, BinaryOp::Or, ready); + g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, fired); + g.b.seal_block(SIRTerminator::Jump(fire, vec![ready])); + + // A wave: one domain evaluates and commits at once, several + // evaluate, then commit, in event order; then logic settles. + g.b.switch_to_block(fire); + let zero = g.constant(0, MAX_EVENTS); + let one = g.constant(1, MAX_EVENTS); + let lower = g.binary(MAX_EVENTS, mask, BinaryOp::Sub, one); + let others = g.binary(MAX_EVENTS, mask, BinaryOp::And, lower); + let single = g.binary(1, others, BinaryOp::Eq, zero); + let alone = g.b.new_block(); + let together = g.b.new_block(); + let committed = g.b.new_block(); + g.b.seal_block(SIRTerminator::Branch { + cond: single, + true_block: (alone, Vec::new()), + false_block: (together, Vec::new()), + }); + g.b.switch_to_block(alone); + for &index in tracked { + g.if_bit(mask, index, |g| { + for unit in &self.events[index].eval_apply { + g.inline_writer(unit, finish_exit); + } + }); + } + g.b.seal_block(SIRTerminator::Jump(committed, Vec::new())); + g.b.switch_to_block(together); + if tracked.len() > 1 { + for phase in [Phase::Evaluate, Phase::Apply] { + for &index in tracked { + let event = &self.events[index]; + let units = match phase { + Phase::Evaluate => event.eval_only.as_ref(), + Phase::Apply => event.apply.as_ref(), + } + .expect("tracked events have their units (`Plan::new`)"); + g.if_bit(mask, index, |g| { + for unit in units { + g.inline_writer(unit, finish_exit); + } + }); + } + } + } + g.b.seal_block(SIRTerminator::Jump(committed, Vec::new())); + g.b.switch_to_block(committed); + g.settle_then(wave); + } + + /// The tracked events whose levels moved to their active edge against + /// `levels`, their baselines, as bits by event index. + fn stable_edges( + &self, + g: &mut Generator<'_>, + tracked: &[usize], + levels: RegisterId, + ) -> RegisterId { + let mut edges = g.constant(0, MAX_EVENTS); + for (position, &index) in tracked.iter().enumerate() { + let was = g.mask_bit(levels, position); + let is = g.level(&self.events[index]); + let edge = g.edge(&self.events[index], was, is); + let bit = g.bit(edge, index); + edges = g.binary(MAX_EVENTS, edges, BinaryOp::Or, bit); + } + edges + } +} + +/// The place of event `index` among `tracked`, the bit of its level. +fn position(tracked: &[usize], index: usize) -> usize { + tracked.binary_search(&index).expect("the event is tracked") +} + enum Phase { Evaluate, Apply, @@ -1559,6 +1840,30 @@ impl Generator<'_> { self.binary(1, value, BinaryOp::Ne, zero) } + /// Whether a change of `event`'s level from `was` to `is` is its active + /// edge. + fn edge(&mut self, event: &Event, was: RegisterId, is: RegisterId) -> RegisterId { + let changed = self.binary(1, was, BinaryOp::Ne, is); + let active = self.equals(is, u64::from(event.active)); + self.binary(1, changed, BinaryOp::And, active) + } + + /// Run `body` when bit `index` of the 64-bit `mask` is set. + fn if_bit(&mut self, mask: RegisterId, index: usize, body: impl FnOnce(&mut Self)) { + let set = self.mask_bit(mask, index); + let run = self.b.new_block(); + let next = self.b.new_block(); + self.b.seal_block(SIRTerminator::Branch { + cond: set, + true_block: (run, Vec::new()), + false_block: (next, Vec::new()), + }); + self.b.switch_to_block(run); + body(self); + self.b.seal_block(SIRTerminator::Jump(next, Vec::new())); + self.b.switch_to_block(next); + } + /// A block that ends the run with `exit`, emitted by /// [`Self::emit_exits`]. fn exit_block(&mut self, exit: SchedulerExit) -> celox_sir::BlockId { diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs index 8a8c3f1ff38..ce77aa31b3e 100644 --- a/crates/celox/src/simulation/differential.rs +++ b/crates/celox/src/simulation/differential.rs @@ -1151,6 +1151,82 @@ mod tests { } } + /// Clocks derived from the clock a kernel drives run in compiled slots: + /// gated by a kernel's enable, gated by an enable the clock's own domain + /// raises, inverted, moved back by the commit after the clock's edge + /// moved it, divided by a register, a divided clock gated by a kernel's + /// enable that changes with the clock's edge (it runs after the commit), + /// and divided twice. + #[test] + fn derived_clocks_run_in_compiled_slots() { + for derived in [ + "assign dclk = clk & en;", + "assign dclk = clk & ren;", + "assign dclk = ~clk;", + "logic tog = 1'b1; always_ff @(posedge clk) tog <= ~tog; assign dclk = clk ^ tog;", + "always_ff @(posedge clk) dclk <= ~dclk;", + "logic div = 1'b0; always_ff @(posedge clk) div <= ~div; assign dclk = div & en;", + "logic half = 1'b0; always_ff @(posedge clk) half <= ~half; \ + always_ff @(posedge half) dclk <= ~dclk;", + ] { + let source = format!( + "`timescale 1ns/1ns + module Top(output logic [7:0] y); + logic clk = 1'b0; + logic en = 1'b0; + logic ren = 1'b0; + logic dclk; + logic [7:0] a = 8'd0; + logic [7:0] b = 8'd0; + always #5 clk = ~clk; + initial forever begin #17 en = ~en; end + always_ff @(posedge clk) begin a <= a + 8'd1; ren <= a[1]; end + {derived} + always_ff @(posedge dclk) b <= b + a; + assign y = a ^ b; + endmodule" + ); + host_driven_agrees(&source, &[(100, &[]), (333, &[])]); + } + } + + /// A host clock gated by a kernel's enable, or divided, in a design + /// with and without kernels. + #[test] + fn derived_host_clocks_run_in_compiled_slots() { + for (kernel, derived) in [ + ( + "initial forever begin #17 en = ~en; end", + "assign dclk = clk & en;", + ), + ("", "always_ff @(posedge clk) dclk <= ~dclk;"), + ("", "assign dclk = clk & k[0];"), + ] { + let source = format!( + "`timescale 1ns/1ns + module Top(input logic clk, input logic [7:0] k, output logic [7:0] y); + logic en = 1'b0; + logic dclk; + logic [7:0] a = 8'd0; + logic [7:0] b = 8'd0; + {kernel} + always_ff @(posedge clk) a <= a + k; + {derived} + always_ff @(posedge dclk) b <= b + a; + assign y = a ^ b; + endmodule" + ); + host_driven_agrees( + &source, + &[ + (100, &[Host::Set("k", 3), Host::Clock("clk", 10, 5)]), + (200, &[Host::Set("k", 2)]), + (300, &[]), + ], + ); + } + } + /// A domain whose next state combinational logic computes runs its /// fused units with a settle pending: they compute what it reads. #[test] From 3fb259bef18ef061ef0b8d3328a0cc1bb83e638a Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 14:45:58 +0900 Subject: [PATCH 3/3] fix(runtime): judge derived clocks of slots against every source's level Two cases where the waves of a slot with derived clocks differed from the reference loop's: - A host clock input with no clock armed kept its slot-start level out of the levels slot, which only the clock-apply block filled. The waves compared against zero, so a gate on a clock input the host had set high fired its source's domain at every slot. The levels of every tracked event are now recorded at the slot's start. - A waiting kernel woken by a clock's change runs in a pass after the settle that judges the clocks gated by it; what it writes moves those clocks only for the waves after the commit. The waves judge once, after every pass, so a design with gated clocks whose waiting kernels write what combinational logic reads keeps the reference loop. Change-Id: I42793209eeebcfeffaf0fbc08b91fc586edc58f0 --- crates/celox/src/scheduler.rs | 25 ++++++++- crates/celox/src/simulation/differential.rs | 60 +++++++++++++++++++++ 2 files changed, 83 insertions(+), 2 deletions(-) diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs index 1b8bc883877..05002091ffb 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -796,6 +796,26 @@ impl Plan { if tracked.iter().any(|event| active_commits.contains(event)) { return Err(ACTIVE_COMMIT.into()); } + // A gated clock is judged at the settle after its source changes, + // before a kernel the change wakes runs in another pass; what that + // kernel writes moves the clock only for the waves after the + // commit. The waves judge once, after every pass. + if !plan.gating.is_empty() { + let comb_reads: HashSet = + sir.eval_comb.iter().flat_map(loads).map(storage).collect(); + let feeds_gates = plan.kernels.iter().enumerate().any(|(index, kernel)| { + kernel.as_ref().is_some_and(|kernel| kernel.wait.is_some()) + && kernel_stores[index] + .iter() + .any(|store| comb_reads.contains(store)) + }); + if feeds_gates { + return Err( + "a waiting kernel writes what combinational logic of a gated clock reads" + .into(), + ); + } + } let ends = |unit: &Unit| fails(unit) || emits_finish(unit, &plan.finish_sites); if tracked.iter().any(|&event| { let event = &plan.events[event]; @@ -1026,10 +1046,11 @@ impl Plan { } // The levels the slot starts from, the baseline of its edges, for an // exit in the middle of the slot; those of the clocks' events below, - // when the run has clocks. + // when the run has clocks, unless the slot's waves compare against + // them: a host clock no clock drives keeps the level the host set. let mut levels = g.constant(0, MAX_EVENTS); for (bit, &event) in tracked.iter().enumerate() { - if self.clocks.contains(&event) { + if self.clocks.contains(&event) && self.derived.is_empty() { continue; } let level = g.level(&self.events[event]); diff --git a/crates/celox/src/simulation/differential.rs b/crates/celox/src/simulation/differential.rs index ce77aa31b3e..44896cfbc7f 100644 --- a/crates/celox/src/simulation/differential.rs +++ b/crates/celox/src/simulation/differential.rs @@ -1227,6 +1227,66 @@ mod tests { } } + /// A host clock input the host set once and no clock drives keeps its + /// level through compiled slots: a gate on it judges from that level, + /// not from an unrecorded one. + #[test] + fn derived_clocks_of_an_unclocked_host_input_keep_its_level() { + let source = r#" + `timescale 1ns/1ns + module Top(input logic clk, output logic [7:0] y); + logic en = 1'b0; + logic dclk; + logic [7:0] a = 8'd0; + logic [7:0] b = 8'd0; + initial forever #17 en = ~en; + assign dclk = clk & en; + always_ff @(posedge clk) a <= a + 8'd1; + always_ff @(posedge dclk) b <= b + 8'd1; + assign y = a ^ b; + endmodule + "#; + host_driven_agrees(source, &[(100, &[Host::Set("clk", 1)]), (200, &[])]); + } + + /// A gate a waiting kernel writes changes after the pass that judged + /// its clock: the reference judges it again only after the commit, so + /// the design keeps the reference loop. + #[test] + fn gates_written_by_waiting_kernels_keep_the_reference_loop() { + let source = r#" + `timescale 1ns/1ns + module Top(output logic [7:0] y); + logic clk = 1'b0; + logic en = 1'b0; + logic gclk; + logic [7:0] a = 8'd0; + logic [7:0] b = 8'd0; + always #5 clk = ~clk; + initial forever @(posedge clk) en = ~en; + assign gclk = clk & en; + always_ff @(posedge clk) a <= a + 8'd1; + always_ff @(posedge gclk) b <= a; + assign y = a ^ b; + endmodule + "#; + let mut reference = build_in(source, SchedulerMode::Reference); + reference.run_until(200).unwrap(); + let expected = reference.save_state().unwrap(); + for mode in MODES { + let mut sim = build_in(source, mode); + sim.run_until(200).unwrap(); + assert_eq!(sim.save_state().unwrap(), expected, "{mode:?}"); + } + let gate = crate::KernelSchedule::Reference( + "a waiting kernel writes what combinational logic of a gated clock reads".into(), + ); + let kernels = build_in(source, SchedulerMode::Compiled) + .scheduler_stats() + .kernels; + assert!(kernels.iter().all(|kernel| *kernel == gate), "{kernels:?}"); + } + /// A domain whose next state combinational logic computes runs its /// fused units with a settle pending: they compute what it reads. #[test]