diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index b432a3b64b9..2e5793d4715 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -5565,10 +5565,28 @@ impl<'p, 'a> Ff<'p, 'a> { let mut changed = self.b.alloc_bit(1, false); self.b .emit(SIRInstruction::Imm(changed, SIRValue::new(0u8))); + // A large sensitivity list need not retain every old and current + // value until the final comparison. Check bounded groups, stop at + // the first change, and refresh the snapshots only when needed. + // Occurrence counters also observe transient changes; retain their + // existing path until they can share the same grouped check. + let grouped = sources.len() >= 4 && !self.input_occurrences; + let capture = grouped.then(|| self.b.new_block()); + let execute = self.b.new_block(); + let done = self.b.new_block(); + if let Some(capture) = capture { + let check = self.b.new_block(); + self.b.seal_block(SIRTerminator::Branch { + cond: init, + true_block: (check, vec![]), + false_block: (capture, vec![]), + }); + self.b.switch_to_block(check); + } let mut snapshots = Vec::new(); let mut sensitivity_counters = Vec::new(); let mut counter_snapshots = Vec::new(); - for source in &sources { + for (ordinal, source) in sources.iter().enumerate() { let width = source.access.msb - source.access.lsb + 1; let (saved, _) = self.m.temp( "comb_input", @@ -5603,6 +5621,26 @@ impl<'p, 'a> Ff<'p, 'a> { .emit(SIRInstruction::Binary(next, changed, BinaryOp::Or, differs)); changed = next; snapshots.push((saved, width, current)); + if let Some(capture) = capture + && ((ordinal + 1).is_multiple_of(4) || ordinal + 1 == sources.len()) + { + let next = if ordinal + 1 == sources.len() { + done + } else { + self.b.new_block() + }; + self.b.seal_block(SIRTerminator::Branch { + cond: changed, + true_block: (capture, vec![]), + false_block: (next, vec![]), + }); + if next != done { + self.b.switch_to_block(next); + changed = self.b.alloc_bit(1, false); + self.b + .emit(SIRInstruction::Imm(changed, SIRValue::new(0u8))); + } + } if !self.input_occurrences { continue; } @@ -5641,8 +5679,18 @@ impl<'p, 'a> Ff<'p, 'a> { sensitivity_counters.push((*source, counter)); counter_snapshots.push((counter, saved_counter)); } + if let Some(capture) = capture { + self.b.switch_to_block(capture); + } let run = self.b.alloc_bit(1, false); - if runs_at_time_zero { + if grouped && runs_at_time_zero { + self.b.emit(SIRInstruction::Imm(run, SIRValue::new(1u8))); + } else if grouped { + // Ordinary event controls establish their initial baseline + // without executing; always_comb executes on that first visit. + self.b + .emit(SIRInstruction::Binary(run, init, BinaryOp::Or, init)); + } else if runs_at_time_zero { let first = self.b.alloc_bit(1, false); self.b .emit(SIRInstruction::Unary(first, UnaryOp::LogicNot, init)); @@ -5653,14 +5701,27 @@ impl<'p, 'a> Ff<'p, 'a> { .emit(SIRInstruction::Binary(run, init, BinaryOp::And, changed)); } // Snapshot before executing: writes in the body do not retrigger it. - for &(saved, width, current) in &snapshots { + for (source, &(saved, width, current)) in sources.iter().zip(&snapshots) { + let current = if grouped { + // The checks do not mutate input state. Load each value at + // its store, avoiding a live snapshot set spanning the list. + let current = self.b.alloc_logic(width); + let offset = sv_memory_offset(self.m.var(source.id), source.access.lsb, width); + self.b.emit(SIRInstruction::Load( + current, + stable(source.id), + offset, + width, + )); + current + } else { + current + }; self.store(saved, SIROffset::Static(0), width, current); } let one = self.b.alloc_bit(1, false); self.b.emit(SIRInstruction::Imm(one, SIRValue::new(1u8))); self.store(initialized, SIROffset::Static(0), 1, one); - let execute = self.b.new_block(); - let done = self.b.new_block(); self.b.seal_block(SIRTerminator::Branch { cond: run, true_block: (execute, vec![]), diff --git a/crates/celox-slt/src/scheduler.rs b/crates/celox-slt/src/scheduler.rs index 70bfea9cc15..2abc9fb480a 100644 --- a/crates/celox-slt/src/scheduler.rs +++ b/crates/celox-slt/src/scheduler.rs @@ -3675,9 +3675,27 @@ fn plan_settle_partitions= partitioning.target_cost { first_work.push(index); cost = 0; @@ -3704,6 +3722,9 @@ fn plan_settle_partitions WorkLowering<'a } } - /// Start a settle of `count` partitions. Record whether all flags are set - /// or an untracked raw view requires a full settle. A fraction of dirty flags is not a cost estimate: a - /// clean partition can contain most of the program's work. + /// Start a settle of `count` partitions. An untracked raw view requires + /// every partition to run. When all individual flags are already set, + /// their own guards suffice; counting them would scan the complete flag + /// array on every settle without changing which partitions execute. fn begin_settle(&mut self, flags: Addr, count: usize) { - let all = self.builder.alloc_bit(count * 8, false); - self.builder.emit(SIRInstruction::Load( - all, - flags, - SIROffset::Static(0), - count * 8, - )); - let count_width = UnaryOp::PopCount.result_width(count * 8); - let dirty = self.builder.alloc_bit(count_width, false); - self.builder - .emit(SIRInstruction::Unary(dirty, UnaryOp::PopCount, all)); - let threshold = self.builder.alloc_bit(count_width, false); - self.builder - .emit(SIRInstruction::Imm(threshold, SIRValue::new(count as u64))); - let busy = self.builder.alloc_bit(1, false); - self.builder.emit(SIRInstruction::Binary( - busy, - dirty, - BinaryOp::GeU, - threshold, - )); let untracked = self.builder.alloc_bit(8, false); self.builder.emit(SIRInstruction::Load( untracked, @@ -3968,15 +3969,11 @@ impl<'a, Addr: Clone + Eq + Ord + Hash + Debug + Copy + Display> WorkLowering<'a let raw = self.builder.alloc_bit(1, false); self.builder .emit(SIRInstruction::Binary(raw, untracked, BinaryOp::Ne, zero)); - let full = self.builder.alloc_bit(1, false); - self.builder - .emit(SIRInstruction::Binary(full, busy, BinaryOp::Or, raw)); let one = self.builder.alloc_bit(8, false); self.builder .emit(SIRInstruction::Imm(one, SIRValue::new(1u64))); let byte = self.builder.alloc_bit(8, false); - self.builder - .emit(SIRInstruction::Mux(byte, full, one, zero)); + self.builder.emit(SIRInstruction::Mux(byte, raw, one, zero)); self.builder.emit(SIRInstruction::Store( flags, SIROffset::Static((count + 1) * 8), @@ -6468,31 +6465,59 @@ mod tests { .chain(outputs.map(|output| output + 100)) .map(|variable| (variable, if variable == PROCESS { 1 } else { 8 })) .collect(); - let result = sort( - paths, - &arena, - &crate::HashSet::default(), - &crate::HashMap::default(), - false, - &widths, - 1, - ) - .unwrap(); - let stores = |variable| { - result - .execution_units - .iter() - .flat_map(|unit| unit.blocks.values()) - .flat_map(|block| &block.instructions) - .filter(|instruction| { - matches!(instruction, SIRInstruction::Store(target, ..) if *target == variable) - }) - .count() - }; - assert_eq!(stores(PROCESS), 1, "the unit runs once"); - for output in outputs { - assert_eq!(stores(output), 1); - assert_eq!(stores(output + 100), 1, "each consumer is emitted"); + for partitioning in [ + None, + Some(super::SettlePartitioning { + flags: 99, + target_cost: 1, + }), + ] { + let result = super::sort_with_unpacked_element_widths( + paths.clone(), + &arena, + &crate::HashSet::default(), + &crate::HashMap::default(), + false, + &widths, + &crate::HashMap::default(), + 1, + partitioning, + ) + .unwrap(); + let stores = |variable| { + result.execution_units.iter() + .flat_map(|unit| unit.blocks.values()) + .flat_map(|block| &block.instructions) + .filter(|instruction| matches!(instruction, SIRInstruction::Store(target, ..) if *target == variable)) + .count() + }; + assert_eq!(stores(PROCESS), 1, "the unit runs once"); + for output in outputs { + assert_eq!(stores(output), 1); + assert_eq!(stores(output + 100), 1, "each consumer is emitted"); + } + if !result.partitions.is_empty() { + assert_eq!(result.partitions.len(), 4, "one body and three consumers"); + assert_eq!( + result + .partitions + .iter() + .filter(|part| part.reads.contains(&INPUT)) + .count(), + 1 + ); + for output in outputs.into_iter().chain([PROCESS]) { + assert_eq!( + result + .partitions + .iter() + .filter(|part| part.writes.contains(&output)) + .count(), + 1, + "only the executing partition watches output {output}" + ); + } + } } } } diff --git a/crates/celox-test-suite/src/sv/cases/always_comb.vtest b/crates/celox-test-suite/src/sv/cases/always_comb.vtest index a5f14236fc7..848bfa9ef9e 100644 --- a/crates/celox-test-suite/src/sv/cases/always_comb.vtest +++ b/crates/celox-test-suite/src/sv/cases/always_comb.vtest @@ -407,3 +407,44 @@ (modify (set a 0xe318)) (assert_eq y 15) (modify (set a 0xe680)) (assert_eq y 14) (modify (set a 0x1000)) (assert_eq y 0)) + +; A long event list must refresh every baseline after an early difference, +; observe a last-input X/Z-only change, and stay dormant for repeated values. +; The intermediate pulse makes executing the body unnecessarily observable. +(case large_sensitivity_list_preserves_initial_wait_and_four_state_changes + (four_state) + (source "large_sensitivity.sv" #" + module Top; + logic a, b, c, d, e, f, g, h, i; + logic [8:0] observed = 9'h155; + logic [8:0] combinational; + bit pulse = 0; + int count = 0; + always_comb combinational = {a,b,c,d,e,f,g,h,i}; + always @(a or b or c or d or e or f or g or h or i) begin + pulse = 0; + observed = {a,b,c,d,e,f,g,h,i}; + pulse = 1; + end + always @(posedge pulse) count = count + 1; + initial begin + #1 $display("%b %b %0d", observed, combinational, count); + a = 0; + #1 $display("%b %b %0d", observed, combinational, count); + i = 1; + #1 $display("%b %b %0d", observed, combinational, count); + i = 1; + #1 $display("%b %b %0d", observed, combinational, count); + i = 1'bx; + #1 $display("%b %b %0d", observed, combinational, count); + i = 1'bz; + #1 $display("%b %b %0d", observed, combinational, count); + a = 1; + #1 $display("%b %b %0d", observed, combinational, count); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "101010101 xxxxxxxxx 0\n0xxxxxxxx 0xxxxxxxx 1\n0xxxxxxx1 0xxxxxxx1 2\n0xxxxxxx1 0xxxxxxx1 2\n0xxxxxxxx 0xxxxxxxx 3\n0xxxxxxxz 0xxxxxxxz 4\n1xxxxxxxz 1xxxxxxxz 5\n")) diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs index 8b89be25fc3..ffadf1a26d4 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -3144,6 +3144,9 @@ impl Plan { /// 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: Levels) -> RegisterId { + if tracked.len() >= 4 { + return self.batched_stable_edges(g, tracked, levels); + } let mut edges = g.constant(0, self.event_bits); for (position, &index) in tracked.iter().enumerate() { let was = g.saved_level(levels, position); @@ -3154,6 +3157,80 @@ impl Plan { } edges } + + /// Judge independent edges as bit planes, in chunks of at most one word. + /// Baselines use tracked positions; the result uses event indices, which + /// need not be contiguous. No level or event is published by this check. + fn batched_stable_edges( + &self, + g: &mut Generator<'_>, + tracked: &[usize], + levels: Levels, + ) -> RegisterId { + let zero = g.constant(0, 1); + let mut result = vec![zero; self.event_bits]; + for (chunk, events) in tracked.chunks(64).enumerate() { + let width = events.len(); + let mut values = Vec::with_capacity(width); + let mut unknowns = Vec::with_capacity(width); + let mut falling = 0u64; + for (bit, &index) in events.iter().enumerate() { + let event = &self.events[index]; + let level = g.level(event); + let (value, unknown) = g.level_planes(level); + values.push(value); + if let Some(unknown) = unknown { + unknowns.push(unknown); + } + if event.active == 0 { + falling |= 1u64 << bit; + } + } + let pack = |g: &mut Generator<'_>, mut bits: Vec| { + bits.reverse(); + let result = g.b.alloc_bit(width, false); + g.b.emit(SIRInstruction::Concat(result, bits)); + result + }; + let slice = |g: &mut Generator<'_>, source: RegisterId| { + let result = g.b.alloc_bit(width, false); + g.b.emit(SIRInstruction::Slice(result, source, chunk * 64, width)); + result + }; + let was = slice(g, levels.values); + let is = pack(g, values); + // Invert both value planes of falling-edge lanes. Their masks + // stay unchanged, turning the same edge formula into negedge. + let falling = g.constant(falling, width); + let was = g.binary(width, was, BinaryOp::Xor, falling); + let is = g.binary(width, is, BinaryOp::Xor, falling); + let all = g.ones(width); + let not_was = g.binary(width, was, BinaryOp::Xor, all); + let edges = if let Some(old_unknown) = levels.unknown { + let old_unknown = slice(g, old_unknown); + let new_unknown = pack(g, unknowns); + // Table 9-2: leave known zero or reach known one, excluding + // all unknown-to-unknown transitions (including X <-> Z). + let leaves = g.binary(width, not_was, BinaryOp::Or, old_unknown); + let reaches = g.binary(width, is, BinaryOp::Or, new_unknown); + let both_unknown = g.binary(width, old_unknown, BinaryOp::And, new_unknown); + let some_known = g.binary(width, both_unknown, BinaryOp::Xor, all); + let edges = g.binary(width, leaves, BinaryOp::And, reaches); + g.binary(width, edges, BinaryOp::And, some_known) + } else { + g.binary(width, not_was, BinaryOp::And, is) + }; + for (bit, &index) in events.iter().enumerate() { + let lane = g.b.alloc_bit(1, false); + g.b.emit(SIRInstruction::Slice(lane, edges, bit, 1)); + result[index] = lane; + } + } + result.reverse(); + let edges = g.b.alloc_bit(self.event_bits, false); + g.b.emit(SIRInstruction::Concat(edges, result)); + edges + } } /// Edge levels of the tracked events, one bit per event (see diff --git a/crates/celox/tests/frontends/systemverilog/always_comb.rs b/crates/celox/tests/frontends/systemverilog/always_comb.rs index 6a66f644f65..9d2f2c8536e 100644 --- a/crates/celox/tests/frontends/systemverilog/always_comb.rs +++ b/crates/celox/tests/frontends/systemverilog/always_comb.rs @@ -77,3 +77,9 @@ sv_backends! { @case "always_comb::settles_feedback_through_chained_qspi_four_state"; } } + +sv_backends! { + fn large_sensitivity_list_preserves_initial_wait_and_four_state_changes(sim) { + @case "always_comb::large_sensitivity_list_preserves_initial_wait_and_four_state_changes"; + } +} diff --git a/crates/celox/tests/sv_four_state_scheduler.rs b/crates/celox/tests/sv_four_state_scheduler.rs index 87fc4781b4f..81604742580 100644 --- a/crates/celox/tests/sv_four_state_scheduler.rs +++ b/crates/celox/tests/sv_four_state_scheduler.rs @@ -91,6 +91,55 @@ macro_rules! four_state_scheduler { assert_eq!(value(&mut sim, "waited"), (4, 0)); } + /// Exercise both polarities and every Table 9-2 transition across + /// word boundaries in the compiled scheduler's edge bitmaps. + #[test] + fn many_mixed_edges_follow_table_9_2() { + const CLOCKS: usize = 70; + let literals = ["1'b0", "1'b1", "1'bx", "1'bz"]; + let mut body = String::from(";\n"); + for i in 0..CLOCKS { + let edge = if i % 2 == 0 { "posedge" } else { "negedge" }; + body += &format!( + "logic c{i} = 0; logic [7:0] n{i} = 0;\n\ + always_ff @({edge} c{i}) n{i} <= n{i} + 1;\n" + ); + } + let mut before = [0usize; CLOCKS]; + let mut expected = [0u64; CLOCKS]; + body += "initial begin\n"; + for old in 0..4 { + for new in 0..4 { + for state in [old, new] { + body += "#1 begin\n"; + for i in 0..CLOCKS { + let after = (state + i) % 4; + let from = before[i]; + let edge = if i % 2 == 0 { + (from == 0 && after != 0) || (from >= 2 && after == 1) + } else { + (from == 1 && after != 1) || (from >= 2 && after == 0) + }; + expected[i] += u64::from(edge); + before[i] = after; + body += &format!("c{i} = {};\n", literals[after]); + } + body += "end\n"; + } + } + } + body += "end\n"; + let mut sim = simulation(&body); + run(&mut sim, 40); + for (i, expected) in expected.into_iter().enumerate() { + assert_eq!( + value(&mut sim, &format!("n{i}")), + (expected, 0), + "clock {i}" + ); + } + } + /// Asynchronous resets that become x or z: a move to x is an /// edge of either polarity, and the flip-flop's condition is /// then unknown.