diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 7b440f50b12..d9bc370afc4 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -741,9 +741,18 @@ fn validate_net_driver_ranges( .iter() .any(|(_, local_range)| net_driver_ranges_overlap(*child_range, *local_range)) }); + // Each concatenation operand is a continuous driver, even when two + // operands occur in the same authored assignment. + let overlapping_continuous = driver_ranges_overlap(&continuous_driver_ranges( + &module.source, + signal_name, + &module.constants, + &module.parameter_types, + )); if driver_ranges_overlap(child_driver_ranges) || child_local_overlap || overlapping_local_drivers + || overlapping_continuous { return Err(sv::AnalyzerError::Unsupported(format!( "multiple net drivers for `{signal_name}`" @@ -940,10 +949,61 @@ fn driver_ranges_overlap(drivers: &[(usize, Option<(i128, i128)>)]) -> bool { }) } +/// Memories may have several edge-sensitive writers. Their NBA stores update +/// selected elements; always_ff additionally requires a single writing process. +fn shared_edge_memories( + module: &sv::ir::Module, + constants: &HashMap, + parameter_types: &HashMap, + warnings: &mut Vec, +) -> HashSet { + let mut memories = HashSet::default(); + let first_ff = module.comb_processes().len(); + let end_ff = first_ff + module.ff_processes().len(); + for signal in module + .signals() + .iter() + .filter(|s| !s.is_net() && !s.r#type().unpacked_ranges().is_empty()) + { + let drivers = local_driver_ranges(module, signal.name(), constants, parameter_types); + if drivers + .iter() + .any(|(id, _)| !(first_ff..end_ff).contains(id)) + { + continue; + } + let overlaps = drivers.iter().enumerate().any(|(i, a)| { + drivers[i + 1..] + .iter() + .any(|b| a.0 != b.0 && net_driver_ranges_overlap(a.1, b.1)) + }); + if !overlaps { + continue; + } + let mut restricted = false; + for (id, _) in drivers { + let process = &module.ff_processes()[id - first_ff]; + restricted |= process.is_always_ff(); + } + if restricted { + warnings.push(( + crate::FrontendWarningKind::MultipleAlwaysFfDrivers { + module: module.name().into(), + signal: signal.name().into(), + }, + None, + )); + } + memories.insert(signal.name().into()); + } + memories +} + fn validate_variable_driver_ranges( module: &sv::ir::Module, constants: &HashMap, parameter_types: &HashMap, + shared_memories: &HashSet, ) -> Result<(), sv::AnalyzerError> { for port in module .ports() @@ -977,7 +1037,13 @@ fn validate_variable_driver_ranges( .iter() .any(|right| left.0 != right.0 && net_driver_ranges_overlap(left.1, right.1)) }); - if has_overlap { + let overlapping_continuous = driver_ranges_overlap(&continuous_driver_ranges( + module, + signal_name, + constants, + parameter_types, + )); + if overlapping_continuous || (has_overlap && !shared_memories.contains(signal_name)) { return Err(sv::AnalyzerError::Unsupported(format!( "multiple variable drivers for `{signal_name}`" ))); @@ -2301,6 +2367,23 @@ fn lower_module_with_overrides( }); } } + let parameter_types = module + .imported_parameters() + .iter() + .chain(module.parameters()) + .filter_map(|parameter| { + Some(( + parameter.name().to_string(), + ( + parameter.resolved_width()?, + parameter.resolved_signed().unwrap_or(false), + ), + )) + }) + .collect(); + let constants = module_constants_with_overrides(module, parameter_overrides); + let shared_memories = shared_edge_memories(module, &constants, ¶meter_types, warnings); + validate_variable_driver_ranges(module, &constants, ¶meter_types, &shared_memories)?; let scheduled = module .ff_processes() .iter() @@ -2318,22 +2401,6 @@ fn lower_module_with_overrides( let mut name_to_id = HashMap::default(); let mut port_order = Vec::new(); let mut initial_memory_values = Vec::new(); - let parameter_types = module - .imported_parameters() - .iter() - .chain(module.parameters()) - .filter_map(|parameter| { - Some(( - parameter.name().to_string(), - ( - parameter.resolved_width()?, - parameter.resolved_signed().unwrap_or(false), - ), - )) - }) - .collect(); - let constants = module_constants_with_overrides(module, parameter_overrides); - validate_variable_driver_ranges(module, &constants, ¶meter_types)?; for port in module.ports() { if name_to_id.contains_key(port.name()) { @@ -2598,7 +2665,8 @@ fn lower_module_with_overrides( four_state, warnings, ); - let blocks = lower_ff_processes(module, &mut pm, ff_parts, &ff_event_roles)?; + let blocks = + lower_ff_processes(module, &mut pm, ff_parts, &ff_event_roles, &shared_memories)?; ( blocks, std::mem::take(&mut pm.runtime_event_sites), @@ -6561,6 +6629,32 @@ fn runtime_select_position( (i128::try_from(width).ok()?.checked_sub(1)?, 0) } }; + runtime_select_position_in_range( + left, + right, + window, + whole_array, + msb, + lsb, + variables, + name_to_id, + constants, + parameter_types, + ) +} + +fn runtime_select_position_in_range( + left: i128, + right: i128, + window: Option, + whole_array: bool, + msb: &sv::ir::ConstExpr, + lsb: &sv::ir::ConstExpr, + variables: &HashMap, + name_to_id: &HashMap, + constants: &HashMap, + parameter_types: &HashMap, +) -> Option { if right < 0 { return None; } @@ -6634,20 +6728,33 @@ fn runtime_select_as_shift( parameter_types: &HashMap, flat_arrays: bool, ) -> Option { - let sv::ir::Expr::Ident(name) = expr else { - return None; + let position = if let sv::ir::Expr::Ident(name) = expr { + runtime_select_position( + name, + msb, + lsb, + variables, + name_to_id, + constants, + parameter_types, + flat_arrays, + flat_arrays, + )? + } else { + let width = sv_expr_natural_width(expr, variables, name_to_id, constants, parameter_types)?; + runtime_select_position_in_range( + i128::try_from(width).ok()?.checked_sub(1)?, + 0, + None, + false, + msb, + lsb, + variables, + name_to_id, + constants, + parameter_types, + )? }; - let position = runtime_select_position( - name, - msb, - lsb, - variables, - name_to_id, - constants, - parameter_types, - flat_arrays, - flat_arrays, - )?; let shift = |value: sv::ir::Expr, op, amount: sv::ir::Expr| sv::ir::Expr::Binary { left: Box::new(value), op, @@ -6678,10 +6785,13 @@ fn runtime_select_as_shift( let moved = move_down(vector); // Shifting fills the missing bits with 0, which is what a two-state // vector (or a parameter) reads. - let four_state = name_to_id - .get(name) - .and_then(|id| variables.get(id)) - .is_some_and(|variable| variable.is_4state); + let four_state = match expr { + sv::ir::Expr::Ident(name) => name_to_id + .get(name) + .and_then(|id| variables.get(id)) + .is_some_and(|variable| variable.is_4state), + _ => true, + }; if !four_state { return Some(sv::ir::Expr::Select { expr: Box::new(moved), @@ -7166,6 +7276,7 @@ fn lower_ff_processes( pm: &mut procedural::ProcModule<'_>, ff_parts: bool, ff_event_roles: &[FfEventRole], + shared_memories: &HashSet, ) -> Result { let mut parallel_ff_parts = HashMap::<_, Vec<_>>::default(); let mut eval_only_ff_blocks = HashMap::default(); @@ -7275,7 +7386,9 @@ fn lower_ff_processes( active, nba, targets, - } = ff::Ff::new(pm, random_seeds[&(0, index)]).lower_process(process.body())?; + } = ff::Ff::new(pm, random_seeds[&(0, index)]) + .with_sparse_memories(shared_memories) + .lower_process(process.body())?; // A process without writes still runs for its runtime events and // extern calls. let has_effects = diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 633ef544b4a..9b9e3489141 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -609,6 +609,100 @@ impl<'p, 'a> Comb<'p, 'a> { self.m.expr_signed(expr) } + /// Replace bits absorbed by a constant zero mask by literal zeros before + /// dependency analysis (IEEE 1800-2023 Table 11-11, including X/Z inputs). + fn masked_and_operand( + &mut self, + store: &Store, + operand: NodeId, + constant: NodeId, + ) -> Result, sv::AnalyzerError> { + let Some((value, mask, width)) = slt_const4(self.arena, &mut self.consts, constant) else { + return Ok(None); + }; + if self.width(operand) != width { + return Ok(None); + } + self.masked_input(store, operand, &(value | mask)) + } + + fn masked_input( + &mut self, + store: &Store, + node: NodeId, + active: &BigUint, + ) -> Result, sv::AnalyzerError> { + if active.is_zero() { + return Ok(Some(( + self.constant(0, self.width(node))?, + Sources::default(), + ))); + } + match self.arena.get(node).clone() { + SLTNode::Constant(..) => Ok(Some((node, Sources::default()))), + SLTNode::Input { + variable, + index, + access, + .. + } if index.is_empty() => { + let mut sources = Sources::default(); + let mut parts = Vec::new(); + let width = access.msb - access.lsb + 1; + let mut bit = 0; + while bit < width { + let selected = active.bit(bit as u64); + let first = bit; + while bit < width && active.bit(bit as u64) == selected { + bit += 1; + } + let part = if selected { + let (part, read_sources) = self.read( + store, + variable, + BitAccess::new(access.lsb + first, access.lsb + bit - 1), + )?; + sources.extend(read_sources); + part + } else { + self.constant(0, bit - first)? + }; + parts.push((part, bit - first)); + } + Ok(Some((self.concat_lsb_first(parts)?, sources))) + } + SLTNode::Concat(parts) => { + let mut sources = Sources::default(); + let mut replacement = Vec::new(); + let mut offset = 0usize; + for (part, width) in parts.into_iter().rev() { + let selected = + (active >> offset) & ((BigUint::from(1u8) << width) - BigUint::from(1u8)); + if self.width(part) != width { + return Ok(None); + } + let Some((part, part_sources)) = self.masked_input(store, part, &selected)? + else { + return Ok(None); + }; + sources.extend(part_sources); + replacement.push((part, width)); + offset += width; + } + Ok(Some((self.concat_lsb_first(replacement)?, sources))) + } + SLTNode::Slice { expr, access } => { + let Some((expr, sources)) = + self.masked_input(store, expr, &(active << access.lsb))? + else { + return Ok(None); + }; + Ok(Some((self.slice(expr, access)?, sources))) + } + _ => Ok(None), + } + } + /// Rewrite the module-state reads of a freshly lowered tree to the values /// the store holds. fn resolve( @@ -722,8 +816,26 @@ impl<'p, 'a> Comb<'p, 'a> { } SLTNode::Constant(..) => (node, Sources::default()), SLTNode::Binary(left, op, right) => { - let (l, mut sources) = self.resolve(store, left, memo)?; - let (r, r_sources) = self.resolve(store, right, memo)?; + let (mut l, mut sources) = self.resolve(store, left, memo)?; + let (mut r, mut r_sources) = self.resolve(store, right, memo)?; + if op == BinaryOp::And + && !(node_is_signed(self.arena, l) && node_is_signed(self.arena, r)) + { + // A procedural observer still wakes on the original reads, + // even when a masked bit cannot affect the assigned value. + self.effect_sensitivity.extend(sources.iter().copied()); + self.effect_sensitivity.extend(r_sources.iter().copied()); + if let Some((masked, read_sources)) = self.masked_and_operand(store, left, r)? { + l = masked; + sources = read_sources; + } + if let Some((masked, read_sources)) = + self.masked_and_operand(store, right, l)? + { + r = masked; + r_sources = read_sources; + } + } sources.extend(r_sources); let rebuilt = if l == left && r == right { node @@ -1502,7 +1614,9 @@ impl<'p, 'a> Comb<'p, 'a> { Target::Static { access, .. } => access.msb - access.lsb + 1, Target::Dynamic { width, .. } => *width, }; - if self.continuous && matches!(target, Target::Dynamic { .. }) { + if self.continuous + && matches!(&target, Target::Dynamic { id, .. } if !self.m.is_hidden(*id)) + { return Err(unsupported(format!( "combinational assignment target `{}` at a run-time position", lhs.name() @@ -3461,7 +3575,12 @@ impl<'p, 'a> Comb<'p, 'a> { .is_ok_and(|parts| parts.iter().all(|(value, _)| value.is_some())) }); if !defined { - return Err(unsupported("latch inference inside always_comb")); + return Err(unsupported(format!( + "latch inference inside always_comb for `{}` (bits {}:{})", + self.m.var(id).path.join("."), + access.msb, + access.lsb + ))); } } let mut written: Vec = store @@ -3502,7 +3621,10 @@ impl<'p, 'a> Comb<'p, 'a> { .iter() .any(|source| source.id == id && source.access.overlaps(&target)) { - return Err(unsupported("latch inference inside always_comb")); + return Err(unsupported(format!( + "latch inference inside always_comb for `{}` (self dependency at bits {msb}:{lsb})", + self.m.var(id).path.join(".") + ))); } let previous_sources = sources .iter() diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 64b54726a4a..1bd4cc42a6f 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -13,7 +13,7 @@ mod file_io; use super::procedural::*; use super::*; -use celox_design::{CounterKind, NbaSite, WaitSite}; +use celox_design::{CounterKind, NbaSite, SPARSE_WORKING_REGION, WaitSite}; use celox_frontend_core::process::{ProcessKernelBuilder, ProcessKernelError}; use celox_sir::{RegisterId, RegisterType}; use celox_slt::SLTToSIRLowerer; @@ -34,6 +34,7 @@ struct FunctionBlocks { pub(super) struct Ff<'p, 'a> { pub m: &'p mut ProcModule<'a>, + sparse_memories: HashSet, b: SIRBuilder, /// Variables read from the working region. working: HashSet, @@ -97,6 +98,7 @@ impl<'p, 'a> Ff<'p, 'a> { } Self { m, + sparse_memories: HashSet::default(), b: SIRBuilder::new(), working: HashSet::default(), nonblocking: HashSet::default(), @@ -121,6 +123,11 @@ impl<'p, 'a> Ff<'p, 'a> { } } + pub fn with_sparse_memories(mut self, names: &HashSet) -> Self { + self.sparse_memories = names.iter().filter_map(|name| self.m.id(name)).collect(); + self + } + /// Where a write of `id`, and a read of a value the process wrote, go: /// the working region, or stable state in a process kernel. fn target(&self, id: SourceVarId) -> Addr { @@ -2203,6 +2210,20 @@ impl<'p, 'a> Ff<'p, 'a> { bit_offset: 0, dynamic_bit_offset: None, }; + if self.sparse_memories.contains(&id) { + let part = self.b.alloc_logic(packed_element_width); + self.b.emit(SIRInstruction::Slice( + part, + value, + inner_index * packed_element_width, + packed_element_width, + )); + self.when(valid, |this| { + this.store(id, offset, packed_element_width, part); + Ok(()) + })?; + continue; + } let old = self.b.alloc_logic(packed_element_width); let target = self.target(id); self.b.emit(SIRInstruction::Load( @@ -2230,6 +2251,12 @@ impl<'p, 'a> Ff<'p, 'a> { bit_offset: access.lsb, dynamic_bit_offset: None, }; + if self.sparse_memories.contains(&id) { + return self.when(valid, |this| { + this.store(id, offset, target_width, value); + Ok(()) + }); + } let old = self.b.alloc_logic(target_width); let target = self.target(id); self.b.emit(SIRInstruction::Load( @@ -3463,6 +3490,15 @@ impl<'p, 'a> Ff<'p, 'a> { ) -> Result { let mut visited = HashSet::default(); self.scan(body, &mut visited); + if self + .working + .iter() + .any(|id| self.sparse_memories.contains(id)) + { + return Err(unsupported( + "blocking writes to a shared edge-triggered memory", + )); + } // Merge the written ranges of each variable. let mut ranges: HashMap> = HashMap::default(); for (id, access) in std::mem::take(&mut self.targets) { @@ -3517,7 +3553,12 @@ impl<'p, 'a> Ff<'p, 'a> { } else { stage_nonblocking(body, &staged, self.m) }; - emit_ff_seeds(&mut self.b, &targets); + let ordinary_targets: Vec<_> = targets + .iter() + .copied() + .filter(|target| !self.sparse_memories.contains(&target.id)) + .collect(); + emit_ff_seeds(&mut self.b, &ordinary_targets); for stage in &staged { let width = self.m.var(stage.mask).width; let zero = self.b.alloc_bit(width, false); @@ -3527,18 +3568,44 @@ impl<'p, 'a> Ff<'p, 'a> { if self.exec_block(&body)? { self.b.seal_block(SIRTerminator::Return); } - let eval = seal_drained(self.b); + let mut eval = seal_drained(self.b); + if eval.blocks.values().flat_map(|block| &block.instructions).any(|instruction| { + matches!(instruction, SIRInstruction::Load(_, address, ..) + if address.region == WORKING_REGION && self.sparse_memories.contains(&address.var_id)) + }) { + return Err(unsupported("read-modify-write destination in a shared FF memory")); + } + for block in eval.blocks.values_mut() { + for instruction in &mut block.instructions { + if let SIRInstruction::Store(address, ..) = instruction + && address.region == WORKING_REGION + && self.sparse_memories.contains(&address.var_id) + { + address.region = SPARSE_WORKING_REGION; + } + } + } let (active_targets, nba_targets): (Vec<_>, Vec<_>) = targets .iter() .copied() .partition(|target| self.working.contains(&target.id)); let mut apply = SIRBuilder::new(); - emit_ff_commits(&mut apply, &targets); + emit_sparse_memory_commits( + &mut apply, + &targets, + &self.sparse_memories, + self.m.variables, + ); emit_nba_merges(&mut apply, &staged, self.m); let mut active = SIRBuilder::new(); emit_ff_commits(&mut active, &active_targets); let mut nba = SIRBuilder::new(); - emit_ff_commits(&mut nba, &nba_targets); + emit_sparse_memory_commits( + &mut nba, + &nba_targets, + &self.sparse_memories, + self.m.variables, + ); emit_nba_merges(&mut nba, &staged, self.m); Ok(FfProcessUnits { eval, @@ -3550,6 +3617,40 @@ impl<'p, 'a> Ff<'p, 'a> { } } +/// Reuse the sparse next-state protocol used by the Veryl frontend: no whole +/// memory seed, and publication touches only the dirty ranges. +fn emit_sparse_memory_commits( + builder: &mut SIRBuilder, + targets: &[VarAtomBase], + sparse: &HashSet, + variables: &HashMap, +) { + let mut committed = HashSet::default(); + for target in targets { + if sparse.contains(&target.id) { + if !committed.insert(target.id) { + continue; + } + // Sparse publication consumes this memory's complete dirty set, + // including updates from other processes evaluated before commit. + // Describe the full object, and publish it once even if this + // process writes several disjoint static ranges. + builder.emit(SIRInstruction::Commit( + Addr { + region: SPARSE_WORKING_REGION, + var_id: target.id, + }, + stable(target.id), + SIROffset::Static(0), + variables[&target.id].width, + Vec::new(), + )); + } else { + emit_ff_commits(builder, std::slice::from_ref(target)); + } + } +} + /// The units of an edge-triggered process: its evaluation, the commit of /// all its results, and that commit split into the blocking results (the /// active region) and the nonblocking ones (the NBA region). diff --git a/crates/celox-frontend-sv/src/warning.rs b/crates/celox-frontend-sv/src/warning.rs index 5024c2dc46d..f104b7966ef 100644 --- a/crates/celox-frontend-sv/src/warning.rs +++ b/crates/celox-frontend-sv/src/warning.rs @@ -38,6 +38,9 @@ pub enum FrontendWarningKind { /// IEEE 1800-2023 3.14.2.3 requires consistent explicit timing declarations. #[error("mixed explicit and default time units or precisions across design elements")] MixedTimescale, + /// IEEE 1800-2023 9.2.2.4 restricts writes by other processes. + #[error("multiple variable drivers for `{signal}` in `{module}` include an always_ff process")] + MultipleAlwaysFfDrivers { module: String, signal: String }, /// Aggregate defaults are a compatibility extension to IEEE 1800-2023 23.2.2.4. #[error("default value on unpacked input port `{module}.{port}` is a language extension")] UnpackedPortDefault { module: String, port: String }, @@ -144,6 +147,7 @@ impl miette::Diagnostic for FrontendWarning { fn code<'a>(&'a self) -> Option> { Some(Box::new(match self.kind { FrontendWarningKind::MixedTimescale => "mixed_timescale", + FrontendWarningKind::MultipleAlwaysFfDrivers { .. } => "multiple_always_ff_drivers", FrontendWarningKind::UnpackedPortDefault { .. } => "unpacked_port_default", FrontendWarningKind::MemoryFileWordCount { .. } => "memory_file_word_count", FrontendWarningKind::ExitOutsideProgram => "exit_outside_program", @@ -159,6 +163,9 @@ impl miette::Diagnostic for FrontendWarning { FrontendWarningKind::MixedTimescale => { "declare timeunit/timeprecision consistently; undeclared scopes use 1ns/1ps when this check is relaxed" } + FrontendWarningKind::MultipleAlwaysFfDrivers { .. } => { + "IEEE 1800-2023 9.2.2.4 prohibits overlapping writers; use ordinary always procedures, or multiple_always_ff_drivers=warn or allow for compatibility" + } FrontendWarningKind::UnpackedPortDefault { .. } => { "IEEE 1800-2023 23.2.2.4 permits defaults on singular input ports; use unpacked_port_default=warn or allow to enable aggregate defaults" } diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 220496f725f..27c9493cca7 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -2207,6 +2207,7 @@ pub enum CombProcessKind { #[derive(Debug, Clone, PartialEq, Eq)] pub struct FfProcess { + always_ff: bool, suspendable: bool, creation_order: usize, events: Vec, @@ -2214,6 +2215,10 @@ pub struct FfProcess { } impl FfProcess { + pub fn is_always_ff(&self) -> bool { + self.always_ff + } + /// Position among the elaborated module items, shared across process kinds. pub fn creation_order(&self) -> usize { self.creation_order @@ -2221,6 +2226,7 @@ impl FfProcess { fn new(events: Vec, body: Vec) -> Self { Self { + always_ff: false, suspendable: false, creation_order: 0, events, diff --git a/crates/celox-sv-analyzer/src/ast/comb_process.rs b/crates/celox-sv-analyzer/src/ast/comb_process.rs index 79f874c3490..e5bea37f837 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_process.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_process.rs @@ -61,31 +61,19 @@ fn comb_processes_from_item( ) -> Result<(), AnalyzerError> { match &syntax_tree.declarations().body_item(item.id).kind { celox_sv_syntax::BodyItemKind::Assign(id) => { - processes.extend( - continuous_assignments( - syntax_tree.declarations().assign_statement(*id), - syntax_tree, - packed_dimensions, - )? - .into_iter() - .map(|assignment| { - substitute_assignment_constants_with_parameter_literals( - &syntax_tree.state, - assignment, - const_env, - parameter_literals, - ) - }) - .map(|assignment| { - CombProcess::new( - CombProcessKind::ContinuousAssign, - condition - .clone() - .map(|condition| substitute_const_expr_constants(condition, const_env)), - vec![assignment], - ) - }), - ); + for mut process in continuous_assignments( + syntax_tree.declarations().assign_statement(*id), + syntax_tree, + packed_dimensions, + )? { + process.condition = condition.clone(); + processes.push(substitute_process_constants_with_parameter_literals( + &syntax_tree.state, + process, + const_env, + parameter_literals, + )); + } } celox_sv_syntax::BodyItemKind::Procedure(id) => { let local_packed_dimensions = @@ -190,7 +178,7 @@ fn continuous_assignments( native: &celox_sv_syntax::AssignSyntax, tree: &AnalysisContext<'_>, dimensions: &PackedDimensions, -) -> Converted> { +) -> Converted> { if native.assignments.is_empty() { return Err(AnalyzerError::Parse( "native continuous assignment has no operands".into(), @@ -216,6 +204,39 @@ fn continuous_assignments( .assignments .iter() .map(|assignment| { + let native_tree = tree.declarations(); + if matches!( + native_tree.expression(assignment.left).kind, + celox_sv_syntax::ExprKind::Concatenation(_) + ) { + let mut pending = vec![assignment.left]; + let mut parts = Vec::new(); + while let Some(id) = pending.pop() { + if let celox_sv_syntax::ExprKind::Concatenation(items) = + &native_tree.expression(id).kind + { + pending.extend(items.iter().rev().copied()); + } else { + parts.push(expression_binding::net_lvalue( + id, + native_tree, + tree, + dimensions, + )?); + } + } + let rhs = + expression_binding::value(assignment.right, native_tree, tree, dimensions)?; + return Ok(CombProcess::procedural( + CombProcessKind::ContinuousAssign, + None, + vec![Stmt::AssignConcat { + parts, + rhs, + nonblocking: false, + }], + )); + } if let Some(shape) = array_compatibility::native_unpacked_shape( assignment.left, tree.declarations(), @@ -254,7 +275,11 @@ fn continuous_assignments( } else { rhs }; - Ok(Assignment::new(lhs, rhs)) + Ok(CombProcess::new( + CombProcessKind::ContinuousAssign, + None, + vec![Assignment::new(lhs, rhs)], + )) }) .collect() } diff --git a/crates/celox-sv-analyzer/src/ast/constant_binding.rs b/crates/celox-sv-analyzer/src/ast/constant_binding.rs index 74a629b0e14..31c1698cce2 100644 --- a/crates/celox-sv-analyzer/src/ast/constant_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/constant_binding.rs @@ -247,6 +247,22 @@ fn bind_in_context( base = *expression; } if let ExprKind::Name(name) = &native.expression(base).kind { + // Override expressions retain symbolic values, but a packed + // element still has its declared width and coordinates. + // The symbolic context deliberately has no numeric env. + let name_key = instances::normalize_identifier(&name.spelling); + if dimensions.const_env.is_empty() + && query_dimensions.get(&name_key).is_some_and(|shape| { + shape.packed.len() > 1 || !shape.unpacked.is_empty() + }) + { + let value = indexed_expression(id, native, tree, query_dimensions)?; + values.push( + expr_to_index_const(&tree.state, value, query_dimensions) + .ok_or_else(|| unsupported("parameter selection shape"))?, + ); + continue; + } indices.reverse(); jobs.push(Job::Select( instances::normalize_identifier(&name.spelling), diff --git a/crates/celox-sv-analyzer/src/ast/constants.rs b/crates/celox-sv-analyzer/src/ast/constants.rs index 6324346940d..added3f24d0 100644 --- a/crates/celox-sv-analyzer/src/ast/constants.rs +++ b/crates/celox-sv-analyzer/src/ast/constants.rs @@ -739,9 +739,24 @@ pub(super) fn expr_to_index_const( }; assemble_index_bits(bits) } - Expr::Select { .. } | Expr::Concat(_) | Expr::RepeatConcat { .. } | Expr::Inside { .. } => { - None + expr @ (Expr::Concat(_) | Expr::RepeatConcat { .. }) => { + // Bit extraction retains self-determined operand widths and X/Z. + // Never duplicate a call whose effects have not been expanded. + if inlining::calls_subroutine(&expr) { + return None; + } + let source = IndexBitSource::from_expr(state, expr, dimensions)?; + let width = source.width(); + if width > constant_folding::MAX_CONSTANT_CONCAT_BITS { + return None; + } + assemble_index_bits( + (0..width) + .map(|bit| source.bit(bit as i128)) + .collect::>()?, + ) } + Expr::Select { .. } | Expr::Inside { .. } => None, } } diff --git a/crates/celox-sv-analyzer/src/ast/ff_process.rs b/crates/celox-sv-analyzer/src/ast/ff_process.rs index ec988f583ed..0b24fc075c2 100644 --- a/crates/celox-sv-analyzer/src/ast/ff_process.rs +++ b/crates/celox-sv-analyzer/src/ast/ff_process.rs @@ -78,6 +78,7 @@ fn ff_process_from_procedure( } Ok((!events.is_empty()).then(|| { let mut process = FfProcess::new(events, body); + process.always_ff = procedure.kind == celox_sv_syntax::ProcedureKind::AlwaysFf; process.suspendable = procedure.kind == celox_sv_syntax::ProcedureKind::Always; process })) diff --git a/crates/celox-sv-analyzer/src/ast/instances.rs b/crates/celox-sv-analyzer/src/ast/instances.rs index 780b010cff8..5b878ebaefe 100644 --- a/crates/celox-sv-analyzer/src/ast/instances.rs +++ b/crates/celox-sv-analyzer/src/ast/instances.rs @@ -86,12 +86,13 @@ fn instances_from_native_declaration( const_env, ¶meter_types_from_const_env(const_env), ); - let value = expr_to_const( + let value = expr_to_index_const( &syntax_tree.state, substitute_expr_idents( const_expr_to_expr(value), &packed_dimensions.parameter_values, ), + packed_dimensions, ) .ok_or_else(|| { AnalyzerError::Unsupported(format!( diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 8043ee03782..fcc19b24952 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -958,12 +958,18 @@ pub enum CombProcessKind { #[derive(Debug, Clone, PartialEq, Eq)] pub struct FfProcess { + always_ff: bool, creation_order: usize, events: Vec, body: Vec, } impl FfProcess { + /// Whether the source used the restricted always_ff procedure. + pub fn is_always_ff(&self) -> bool { + self.always_ff + } + /// Position among elaborated module items, shared across process kinds. pub fn creation_order(&self) -> usize { self.creation_order @@ -971,6 +977,7 @@ impl FfProcess { pub(crate) fn new(events: Vec, body: Vec) -> Self { Self { + always_ff: false, creation_order: 0, events, body, @@ -1370,6 +1377,7 @@ impl From for FfProcess { .map(|stmt| stmt.map(&mut Into::into, &mut Into::into)) .collect(), ); + result.always_ff = process.is_always_ff(); result.creation_order = process.creation_order(); result } diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/constant_selects.rs b/crates/celox-sv-analyzer/src/source_tree/tests/constant_selects.rs index 8bcd579c6ae..518261d1f11 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/constant_selects.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/constant_selects.rs @@ -82,9 +82,20 @@ fn native_lightweight_value_indices_drive_instance_overrides() { let value = module.instances()[0].parameter_overrides()[0] .value() .unwrap(); - let ConstExpr::Select { bit, .. } = value else { - panic!("{value:?}") + let bit = match value { + ConstExpr::Select { bit, .. } => bit, + ConstExpr::SelectRange { + msb, + lsb, + signed: false, + .. + } if msb == lsb => lsb, + _ => panic!("{value:?}"), }; + assert_eq!( + crate::typecheck::eval_const_expr(&value.clone().into(), &HashMap::default()), + Some(1) + ); assert!(matches!( bit.as_ref(), ConstExpr::Binary { diff --git a/crates/celox-test-suite/src/sv/cases/aggregate_regressions.vtest b/crates/celox-test-suite/src/sv/cases/aggregate_regressions.vtest new file mode 100644 index 00000000000..751266d2394 --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/aggregate_regressions.vtest @@ -0,0 +1,265 @@ +(group aggregate_regressions (category regression)) + +(case continuous_nested_concatenated_targets + (four_state) + (source "concat_targets.sv" #" + module Top(input logic [15:0] data, + output wire [3:0] a, b, output wire [7:0] c, swapped); + assign {{a,b},c} = data; + assign {swapped[3:0],swapped[7:4]} = data[7:0]; + endmodule + "#) + (top Top) + (for value (list 0 0xabcd 0xffff 0x1234) + (modify (set data value)) + (assert_eq a (& (>> value 12) 15)) + (assert_eq b (& (>> value 8) 15)) + (assert_eq c (& value 255)) + (assert_eq swapped (| (<< (& value 15) 4) (& (>> value 4) 15))))) + +(case concatenated_runtime_index + (four_state) + (source "concat_index.sv" #" + module Top(input logic [3:0][7:0] data, input logic sel, ptr, + output wire [7:0] y); + assign y=data[{sel,ptr}]; + endmodule + "#) + (top Top) + (modify (set data 0x44332211)) + (for index (range 0 4) + (modify (set sel (>> index 1)) (set ptr (& index 1))) + (assert_eq y (* (+ index 1) 0x11))) + (modify (set sel (fourstate 1 1))) + (assert (== (xmask (get y)) 255))) + +(case concatenated_static_loop_initializer + (source "concat_loop.sv" #" + module Top(input logic [3:0] x, output wire [3:0] y); + function automatic [3:0] f(input logic [3:0] value); + logic [3:0] mask; integer i; + i=0; + for(mask={1'b1,{3{1'b0}}};mask!=0;mask=mask>>1) begin + f[i]=value[i]; i=i+1; + end + endfunction + assign y=f(x); + endmodule + "#) + (top Top) + (for value (range 0 16) + (modify (set x value)) + (assert_eq y value))) + +(case parameter_element_forwarding + (source "parameter_element.sv" #" + module Child #(parameter A=16)(output wire [7:0] y); + localparam W=$clog2(A+1); + wire [W-1:0] value=W'(A); + assign y=value; + endmodule + module Parent #(parameter N=2, V={32'd8,32'd16})(output wire [N*8-1:0] y); + localparam [N-1:0][31:0] WORDS=V; + for(genvar n=0;n> 10 index) 1))) + (modify (set i 4)) + (assert (== (xmask (get y)) 1)) + (modify (set i (fourstate 7 7))) + (assert (== (xmask (get y)) 1))) + +(case independent_clock_memory_writers + (four_state) + (source "dual_clock_memory.sv" #" + module Top(input logic a_clk,b_clk,a_en,b_en, + input logic[1:0] a_addr,b_addr, input logic[7:0] a_data,b_data, + output wire[7:0] q0,q1,q2,q3); + logic[7:0] mem[4]; + initial for(integer i=0;i<4;i=i+1) mem[i]=0; + always @(posedge a_clk) if(a_en) mem[a_addr]<=a_data; + always @(posedge b_clk) if(b_en) mem[b_addr]<=b_data; + assign q0=mem[0]; assign q1=mem[1]; assign q2=mem[2]; assign q3=mem[3]; + endmodule + "#) + (top Top) + (run_until 0) + (modify (set a_clk 0) (set b_clk 0) (set a_en 1) (set b_en 1) + (set a_addr 0) (set b_addr 1) (set a_data 0x12) (set b_data 0x34)) + (modify (set a_clk 1) (set b_clk 1)) + (assert_eq q0 0x12) (assert_eq q1 0x34) + (modify (set a_clk 0) (set b_clk 0) (set a_addr 2) (set b_addr 3) + (set a_data 0x56) (set b_data 0x78)) + (modify (set a_clk 1)) + (run_until 1) + (modify (set a_clk 0)) + (assert_eq q0 0x12) (assert_eq q1 0x34) (assert_eq q2 0x56) (assert_eq q3 0) + (modify (set b_clk 1)) + (run_until 2) + (modify (set b_clk 0)) + (assert_eq q2 0x56) (assert_eq q3 0x78) + ; Concurrent processes may enqueue competing NBAs in either order (4.6/4.7). + ; A complete word wins; untouched elements retain their previous values. + (modify (set a_clk 0) (set b_clk 0) (set a_addr 2) (set b_addr 2) + (set a_data 0x9a) (set b_data 0xbc)) + (modify (set a_clk 1) (set b_clk 1)) + (run_until 3) + (assert (|| (== (get q2) 0x9a) (== (get q2) 0xbc))) + (assert_eq q0 0x12) (assert_eq q1 0x34) (assert_eq q3 0x78) + (modify (set a_clk 0) (set b_clk 0) (set a_en 0) (set b_addr 3) + (set b_data (fourstate 0xa5 0xff))) + (modify (set b_clk 1)) + (run_until 4) + (assert_eq (xmask (get q3)) 0xff) + (modify (set b_clk 0) (set a_en 1) (set b_en 0) (set a_addr 0) (set a_data 0x42)) + (modify (set a_clk 1)) + (run_until 5) + (assert_eq q0 0x42) (assert_eq q1 0x34) + (assert_eq (xmask (get q3)) 0xff)) + +(case independent_clock_byte_writers + (four_state) + (source "dual_clock_bytes.sv" #" + module Top(input logic a_clk,b_clk, input logic[1:0] en, + input logic[2:0] addr, input logic[15:0] data, + output wire[15:0] q0,q1); + localparam BYTE_W=8; + logic[15:0] mem[2]; + initial begin mem[0]=0; mem[1]=0; end + always @(posedge a_clk) begin + for(integer i=0;i<2;i=i+1) + if(en[i]) mem[addr][BYTE_W*i+:BYTE_W]<=data[BYTE_W*i+:BYTE_W]; + end + always @(posedge b_clk) if(en[0]) mem[1]<=16'h1234; + assign q0=mem[0]; assign q1=mem[1]; + endmodule + "#) + (top Top) + (run_until 0) + (modify (set a_clk 0) (set b_clk 0) (set en 3) (set addr 0) (set data 0xabcd)) + (modify (set a_clk 1) (set b_clk 1)) + (run_until 1) + (assert_eq q0 0xabcd) (assert_eq q1 0x1234) + (modify (set a_clk 0) (set en 2) (set data 0x5678)) + (modify (set a_clk 1)) + (run_until 2) + (assert_eq q0 0x56cd) + (modify (set a_clk 0) (set en 3) (set addr 2) (set data 0xffff)) + (modify (set a_clk 1)) + (run_until 3) + (assert_eq q0 0x56cd) (assert_eq q1 0x1234) + (modify (set a_clk 0) (set addr (fourstate 7 7))) + (modify (set a_clk 1)) + (run_until 4) + (assert_eq q0 0x56cd) (assert_eq q1 0x1234)) + +(case coincident_disjoint_byte_writers + (four_state) + (source "shared_bytes.sv" #" + module Top(input logic a_clk,b_clk, input logic[1:0] addr, + input logic[15:0] data, output wire[15:0] q0,q1); + logic[15:0] mem[2]; + initial begin mem[0]=0; mem[1]=0; end + always @(posedge a_clk) mem[addr][15:8]<=data[15:8]; + always @(posedge b_clk) mem[addr][7:0]<=data[7:0]; + assign q0=mem[0]; assign q1=mem[1]; + endmodule + "#) + (top Top) + (run_until 0) + (modify (set a_clk 0) (set b_clk 0) (set addr 0) (set data 0xabcd)) + (modify (set a_clk 1) (set b_clk 1)) + (run_until 1) + (assert_eq q0 0xabcd) (assert_eq q1 0) + (modify (set a_clk 0) (set b_clk 0) (set addr 1) (set data 0x1234)) + (modify (set a_clk 1) (set b_clk 1)) + (run_until 2) + (assert_eq q0 0xabcd) (assert_eq q1 0x1234)) + +(case shared_memory_reads_pre_edge_values + (four_state) + (source "shared_snapshot.sv" #" + module Top(input bit a_clk,b_clk, input bit[1:0] addr, + input bit[7:0] data, output wire[31:0] q); + logic[7:0] mem[4]; + initial begin mem[0]=1; mem[1]=2; mem[2]=3; mem[3]=4; end + always @(posedge a_clk) + for(integer i=0;i<4;i=i+1) mem[i]<=mem[(i+3)%4]; + always @(posedge b_clk) mem[addr]<=data; + assign q={mem[3],mem[2],mem[1],mem[0]}; + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq q 0x04030201) + (modify (set a_clk 0) (set b_clk 0) (set addr 0) (set data 0x55)) + (modify (set a_clk 1)) + (run_until 1) + (assert_eq q 0x03020104) + (modify (set a_clk 0) (set b_clk 1)) + (run_until 2) + (assert_eq q 0x03020155) + (modify (set b_clk 0) (set a_clk 1)) + (run_until 3) + (assert_eq q 0x02015503)) + + +(case masked_feed_forward_dependencies + (four_state) + (source "masked_dependencies.sv" #" + module Top(input logic [3:0] enable, output wire [3:0] grant, grant_swapped); + for (genvar n=0; n<4; n=n+1) begin:g + assign grant[n] = enable[n] && ((grant & (4'b1111 >> (4-n))) == 0); + assign grant_swapped[n] = enable[n] && (((4'b1111 >> (4-n)) & grant_swapped) == 0); + end + endmodule + "#) + (top Top) + (for value (range 0 16) + (modify (set enable value)) + (assert_eq grant (& value (- 16 value))) + (assert_eq grant_swapped (& value (- 16 value)))) + (modify (set enable (fourstate 8 8))) + (assert_eq grant (fourstate 8 8)) + (assert_eq grant_swapped (fourstate 8 8))) + + +(case continuous_function_dynamic_scratch_write + (four_state) + (source "continuous_function_scratch.sv" #" + module Top(input logic [2:0] index, input logic value, output wire [7:0] y); + function automatic [7:0] f(input logic [2:0] position, input logic data); + f=0; + f[position]=data; + endfunction + assign y=f(index,value); + endmodule + "#) + (top Top) + (modify (set value 1)) + (for position (range 0 8) + (modify (set index position)) + (assert_eq y (<< 1 position))) + (modify (set index (fourstate 7 7))) + (assert_eq y 0)) diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index 76c42a71d52..fb9e4950d4a 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -7,6 +7,10 @@ pub(super) struct Group { } pub(super) const GROUPS: &[Group] = &[ + Group { + file: "src/sv/cases/aggregate_regressions.vtest", + text: include_str!("aggregate_regressions.vtest"), + }, Group { file: "src/sv/cases/random_plusargs.vtest", text: include_str!("random_plusargs.vtest"), diff --git a/crates/celox-test-suite/verification/sv/icarus.json b/crates/celox-test-suite/verification/sv/icarus.json index 1dedf339e68..c92647951db 100644 --- a/crates/celox-test-suite/verification/sv/icarus.json +++ b/crates/celox-test-suite/verification/sv/icarus.json @@ -1,5 +1,6 @@ { "case_files": [ + "icarus/aggregate_regressions.json", "icarus/always_comb.json", "icarus/generate.json", "icarus/hierarchy.json", diff --git a/crates/celox-test-suite/verification/sv/icarus/aggregate_regressions.json b/crates/celox-test-suite/verification/sv/icarus/aggregate_regressions.json new file mode 100644 index 00000000000..443bf824a93 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/icarus/aggregate_regressions.json @@ -0,0 +1,50 @@ +{ + "cases": [ + { + "category": "Regression", + "detail": "Icarus 13.0 reports that packed array parameters are not supported, or fails a cast size that depends on a type alias dimension. Verilator passes or reports these four-state cases as unsupported.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_packed_array_parameters", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 reports that packed array parameters are not supported, or fails a cast size that depends on a type alias dimension. Verilator passes or reports these four-state cases as unsupported.", + "upstream": [] + }, + "name": "aggregate_regressions::parameter_element_forwarding", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Regression", + "detail": "Icarus 13.0 reports that packed array parameters are not supported, or fails a cast size that depends on a type alias dimension. Verilator passes or reports these four-state cases as unsupported.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_unsupported", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_packed_array_parameters", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 reports that packed array parameters are not supported, or fails a cast size that depends on a type alias dimension. Verilator passes or reports these four-state cases as unsupported.", + "upstream": [] + }, + "name": "aggregate_regressions::parameter_runtime_element_bit", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 40f8787d4b0..bae9f681e4d 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -134,7 +134,9 @@ "review_regressions::preserves_use_site_dimensions_in_function_alias_types", "system_functions::dimensions_is_independent_of_unknown_values", "system_functions::isunbounded_restores_procedural_parameter_type_metadata", - "types::packed_parameters_of_signed_named_types_have_signed_elements" + "types::packed_parameters_of_signed_named_types_have_signed_elements", + "aggregate_regressions::parameter_element_forwarding", + "aggregate_regressions::parameter_runtime_element_bit" ] } }, diff --git a/crates/celox/src/diagnostic_policy.rs b/crates/celox/src/diagnostic_policy.rs index a5e56e04cb0..181e0a112e6 100644 --- a/crates/celox/src/diagnostic_policy.rs +++ b/crates/celox/src/diagnostic_policy.rs @@ -71,7 +71,10 @@ impl DiagnosticPolicy { pub(crate) fn level(&self, code: &str) -> DiagnosticLevel { self.0.get(code).copied().unwrap_or( - if matches!(code, "mixed_timescale" | "unpacked_port_default") { + if matches!( + code, + "mixed_timescale" | "unpacked_port_default" | "multiple_always_ff_drivers" + ) { DiagnosticLevel::Error } else { DiagnosticLevel::Warn diff --git a/crates/celox/tests/diagnostic_policy.rs b/crates/celox/tests/diagnostic_policy.rs index f50e0db70f8..b4a830de12a 100644 --- a/crates/celox/tests/diagnostic_policy.rs +++ b/crates/celox/tests/diagnostic_policy.rs @@ -176,3 +176,41 @@ mod sv { ); } } + +#[cfg(feature = "systemverilog")] +#[test] +fn overlapping_always_ff_memories_require_explicit_relaxation() { + const SOURCE: &str = r#"module Top(input bit a, b, input bit[1:0] x, y, + output wire[7:0] q); + logic[7:0] mem[4]; + always_ff @(posedge a) mem[x] <= 8'h12; + always_ff @(posedge b) mem[y] <= 8'h34; + assign q=mem[0]; + endmodule"#; + let build = |level| { + celox::Simulation::from_sv_sources( + vec![(SOURCE, std::path::Path::new("shared_ff_memory.sv"))], + "Top", + ) + .diagnostic_policy(policy("multiple_always_ff_drivers", level)) + .build_cranelift() + }; + let error = build(DiagnosticLevel::Error).err().unwrap().to_string(); + assert!(error.contains("multiple variable drivers"), "{error}"); + for level in [DiagnosticLevel::Warn, DiagnosticLevel::Allow] { + let sim = build(level).unwrap(); + assert_eq!( + sim.warnings().len(), + usize::from(level == DiagnosticLevel::Warn) + ); + } + let error = celox::Simulation::from_sv_sources( + vec![(SOURCE, std::path::Path::new("shared_ff_memory.sv"))], + "Top", + ) + .build_cranelift() + .err() + .unwrap() + .to_string(); + assert!(error.contains("multiple variable drivers"), "{error}"); +} diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 67750546b12..d6d4f49497c 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -8694,3 +8694,141 @@ fn timed_task_edge_drivers_of_package_variables_are_checked_across_instances() { "{error}" ); } + +mod aggregate_regressions { + sv_backends! { + fn continuous_function_dynamic_scratch_write(sim) { @case "aggregate_regressions::continuous_function_dynamic_scratch_write"; } + fn masked_feed_forward_dependencies(sim) { @case "aggregate_regressions::masked_feed_forward_dependencies"; } + fn shared_memory_reads_pre_edge_values(sim) { @case "aggregate_regressions::shared_memory_reads_pre_edge_values"; } + fn coincident_disjoint_byte_writers(sim) { @case "aggregate_regressions::coincident_disjoint_byte_writers"; } + fn independent_clock_byte_writers(sim) { @case "aggregate_regressions::independent_clock_byte_writers"; } + + fn continuous_nested_concatenated_targets(sim) { @case "aggregate_regressions::continuous_nested_concatenated_targets"; } + fn concatenated_runtime_index(sim) { @case "aggregate_regressions::concatenated_runtime_index"; } + fn concatenated_static_loop_initializer(sim) { @case "aggregate_regressions::concatenated_static_loop_initializer"; } + fn parameter_element_forwarding(sim) { @case "aggregate_regressions::parameter_element_forwarding"; } + fn parameter_runtime_element_bit(sim) { @case "aggregate_regressions::parameter_runtime_element_bit"; } + fn independent_clock_memory_writers(sim) { @case "aggregate_regressions::independent_clock_memory_writers"; } + } +} + +#[test] +fn shared_ff_memories_keep_native_sparse_next_state() { + use celox_design::{SPARSE_WORKING_REGION, STABLE_REGION, WORKING_REGION}; + use celox_sir::SIRInstruction; + + let source = r#"module Top(input bit a, b, en, + input bit [11:0] addr, input bit [7:0] data, output wire [7:0] q); + logic [7:0] mem[4096]; + always @(posedge a) if (en) begin mem[0] <= data; mem[2] <= data; end + always @(posedge b) if (en) mem[addr] <= data; + assign q = mem[addr]; + endmodule"#; + for level in [ + celox::OptLevel::O0, + celox::OptLevel::O1, + celox::OptLevel::O2, + ] { + let result = Simulator::from_sv_sources(vec![(source, Path::new("sparse_ram.sv"))], "Top") + .opt_level(level) + .trace_pre_optimized_sir() + .build_with_trace(); + let mut sim = result.res.unwrap(); + let memory = sim.program().get_addr(&[], &["mem"]).unwrap(); + let program = result.trace.pre_optimized_sir.unwrap(); + let mut sparse_writes = 0; + let mut sparse_commits = 0; + for instruction in program + .sir + .eval_apply_ffs + .values() + .flatten() + .flat_map(|unit| unit.blocks.values()) + .flat_map(|block| &block.instructions) + { + match instruction { + SIRInstruction::Store(address, ..) if address.absolute_addr() == memory => { + assert_eq!(address.region, SPARSE_WORKING_REGION); + sparse_writes += 1; + } + SIRInstruction::Commit(source, destination, offset, width, _) + if destination.absolute_addr() == memory => + { + assert_ne!(source.region, WORKING_REGION); + assert_ne!(destination.region, WORKING_REGION); + assert_eq!(destination.region, STABLE_REGION); + assert_eq!(source.region, SPARSE_WORKING_REGION); + assert_eq!(*offset, celox_sir::SIROffset::Static(0)); + assert_eq!(*width, 4096 * 8); + sparse_commits += 1; + } + _ => {} + } + } + assert!(sparse_writes >= 3); + assert_eq!(sparse_commits, 2, "one memory commit per clock domain"); + let a = sim.event("a"); + let b = sim.event("b"); + let en = sim.signal("en"); + let addr = sim.signal("addr"); + let data = sim.signal("data"); + let q = sim.signal("q"); + for (event, index, value) in [(a, 0u32, 0x12u32), (b, 4095, 0x34), (a, 2, 0x56)] { + sim.modify(|io| { + io.set(en, 1u8); + io.set(addr, index); + io.set(data, value); + }) + .unwrap(); + sim.tick(event).unwrap(); + assert_eq!(sim.get(q), value.into()); + } + sim.modify(|io| io.set(addr, 4095u32)).unwrap(); + assert_eq!(sim.get(q), 0x34u32.into()); + } +} + +#[test] +fn rejects_overlapping_continuous_concatenation_drivers() { + for declaration in ["wire [7:0] q", "logic [7:0] q"] { + let source = format!( + "module Top(output {declaration}); assign {{q[7:0],q[3:0]}}=12'habc; endmodule" + ); + let error = cranelift_build_error(&source); + assert!( + error.contains("multiple net drivers") || error.contains("multiple variable drivers"), + "{error}" + ); + } +} + +#[test] +fn masked_reads_preserve_observer_sensitivity_and_real_self_dependencies() { + for mask in ["1'b1", "1'bx", "1'bz"] { + let source = format!("module Top(output logic q); always_comb q=q & {mask}; endmodule"); + let error = four_state_cranelift_build_error(&source); + assert!( + error.contains("latch inference inside always_comb"), + "{error}" + ); + } + let source = r#"module Top(input logic a, output logic y); + always_comb begin y=a & 1'b0; $display("tick"); end + endmodule"#; + let mut sim = + Simulator::from_sv_sources(vec![(source, Path::new("masked_observer.sv"))], "Top") + .four_state(true) + .build_cranelift() + .unwrap(); + let a = sim.signal("a"); + sim.drain_runtime_events(); + for value in [1u8, 0] { + sim.modify(|io| io.set(a, value)).unwrap(); + assert_eq!( + sim.drain_runtime_events(), + vec![celox::RuntimeEvent::Display { + message: b"tick".to_vec() + }] + ); + } +} diff --git a/docs/guide/celox-toml.md b/docs/guide/celox-toml.md index 7709d31d8b9..97239f5edcc 100644 --- a/docs/guide/celox-toml.md +++ b/docs/guide/celox-toml.md @@ -154,6 +154,13 @@ explicit settings remain effective, and the global precision includes default scopes. Syntax errors, unsupported constructs and invalid precision declarations remain errors. +`multiple_always_ff_drivers` defaults to `error` for shared memories written by +an `always_ff` and another edge process (IEEE 1800-2023 §9.2.2.4). With `warn` +or `allow`, Celox stages their nonblocking writes in sparse next-state storage +and commits dirty chunks. Ordinary `always` procedures can share a memory +without this diagnostic. Simultaneous +writes to the same bits from different processes have no portable ordering. + Project simulator constructors load this table alongside `Veryl.toml`. Native compilation also supports standalone SystemVerilog projects: diff --git a/docs/ja/guide/celox-toml.md b/docs/ja/guide/celox-toml.md index df0b71e3556..e50629a9358 100644 --- a/docs/ja/guide/celox-toml.md +++ b/docs/ja/guide/celox-toml.md @@ -132,6 +132,8 @@ memory_file_word_count = "error" エラーの緩和は、コンパイラが継続時の動作を定義している診断に対応します。現在の対象は `mixed_timescale` です。IEEE 1800-2023 §3.14.2.3 が求める時間単位・精度の明示指定の一貫性を検査し、既定では `error` になります。`warn` または `allow` を選ぶと、未指定部分には Celox の既定値(単位 1ns、精度 1ps)を適用します。明示した値は維持し、全体の精度には既定値を使うスコープも含めます。構文エラー、未対応の構文、不正な精度指定は引き続きエラーになります。 +`multiple_always_ff_drivers` は、`always_ff` と別のエッジプロセスが同じメモリへ書く場合に既定で `error` になります(IEEE 1800-2023 §9.2.2.4)。`warn` または `allow` では、非ブロッキング代入の変更範囲を次状態領域に保持してコミットします。通常の `always` 同士による共有にはこの診断は出ません。異なるプロセスが同時に同じビットへ書く順序は、移植可能な動作として保証されません。 + プロジェクトのシミュレータ生成時は `Veryl.toml` と同じ場所の設定を読み込みます。CLI は単独の SystemVerilog プロジェクトにも対応します。 ```sh