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)