diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 7348d82eaf3..47ea5cbd3d4 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -19,20 +19,20 @@ chapter-10/10.6.1--assign-deassign.sv 2state fail chapter-10/10.6.1--assign-deassign.sv 4state fail chapter-10/10.6.2--force-release.sv 2state fail chapter-10/10.6.2--force-release.sv 4state fail -chapter-11/11.10--string_bit_array-sim.sv 2state fail -chapter-11/11.10--string_bit_array-sim.sv 4state fail -chapter-11/11.10--string_bit_array.sv 2state fail -chapter-11/11.10--string_bit_array.sv 4state fail -chapter-11/11.10.1--string_compare.sv 2state fail -chapter-11/11.10.1--string_compare.sv 4state fail +chapter-11/11.10--string_bit_array-sim.sv 2state pass +chapter-11/11.10--string_bit_array-sim.sv 4state pass +chapter-11/11.10--string_bit_array.sv 2state pass +chapter-11/11.10--string_bit_array.sv 4state pass +chapter-11/11.10.1--string_compare.sv 2state pass +chapter-11/11.10.1--string_compare.sv 4state pass chapter-11/11.10.1--string_concat.sv 2state fail chapter-11/11.10.1--string_concat.sv 4state fail -chapter-11/11.10.1--string_copy.sv 2state fail -chapter-11/11.10.1--string_copy.sv 4state fail -chapter-11/11.10.3--empty_string-sim.sv 2state fail -chapter-11/11.10.3--empty_string-sim.sv 4state fail -chapter-11/11.10.3--empty_string.sv 2state fail -chapter-11/11.10.3--empty_string.sv 4state fail +chapter-11/11.10.1--string_copy.sv 2state pass +chapter-11/11.10.1--string_copy.sv 4state pass +chapter-11/11.10.3--empty_string-sim.sv 2state pass +chapter-11/11.10.3--empty_string-sim.sv 4state pass +chapter-11/11.10.3--empty_string.sv 2state pass +chapter-11/11.10.3--empty_string.sv 4state pass chapter-11/11.11--min_max_avg_delay.sv 2state pass chapter-11/11.11--min_max_avg_delay.sv 4state pass chapter-11/11.12--let_construct.sv 2state fail @@ -693,8 +693,8 @@ chapter-20/20.15--dist_poisson.sv 2state fail chapter-20/20.15--dist_poisson.sv 4state fail chapter-20/20.15--dist_t.sv 2state fail chapter-20/20.15--dist_t.sv 4state fail -chapter-20/20.15--dist_uniform.sv 2state fail -chapter-20/20.15--dist_uniform.sv 4state fail +chapter-20/20.15--dist_uniform.sv 2state pass +chapter-20/20.15--dist_uniform.sv 4state pass chapter-20/20.15--random.sv 2state pass chapter-20/20.15--random.sv 4state pass chapter-20/20.2--exit.sv 2state pass @@ -815,10 +815,10 @@ chapter-21/21.4--readmemb.sv 2state pass chapter-21/21.4--readmemb.sv 4state pass chapter-21/21.4--readmemh.sv 2state pass chapter-21/21.4--readmemh.sv 4state pass -chapter-21/21.6--test.sv 2state fail -chapter-21/21.6--test.sv 4state fail -chapter-21/21.6--value.sv 2state fail -chapter-21/21.6--value.sv 4state fail +chapter-21/21.6--test.sv 2state pass +chapter-21/21.6--test.sv 4state pass +chapter-21/21.6--value.sv 2state pass +chapter-21/21.6--value.sv 4state pass chapter-21/21.7--dumpfile.sv 2state fail chapter-21/21.7--dumpfile.sv 4state fail chapter-21/21.7--dumpports.sv 2state fail @@ -1077,14 +1077,14 @@ chapter-5/5.7.2-real-token.sv 2state fail chapter-5/5.7.2-real-token.sv 4state fail chapter-5/5.8-time-literals.sv 2state fail chapter-5/5.8-time-literals.sv 4state fail -chapter-5/5.9-string-assignment.sv 2state fail -chapter-5/5.9-string-assignment.sv 4state fail +chapter-5/5.9-string-assignment.sv 2state pass +chapter-5/5.9-string-assignment.sv 4state pass chapter-5/5.9-string-basics.sv 2state pass chapter-5/5.9-string-basics.sv 4state pass chapter-5/5.9-string-broken-line.sv 2state pass chapter-5/5.9-string-broken-line.sv 4state pass -chapter-5/5.9-string-word-assignment.sv 2state fail -chapter-5/5.9-string-word-assignment.sv 4state fail +chapter-5/5.9-string-word-assignment.sv 2state pass +chapter-5/5.9-string-word-assignment.sv 4state pass chapter-5/5.9.1-string-special-chars.sv 2state pass chapter-5/5.9.1-string-special-chars.sv 4state pass chapter-6/6.10--implicit_continuous_assignment.sv 2state fail diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 4b6de2abf08..c2b97a6f147 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -250,6 +250,9 @@ pub enum ProcessStatus { /// It resumes at the point stored in [`ProcessSlots::resume`] when the /// simulation continues. Stop, + /// A synchronous host operation. The delay slot holds its family and + /// local site index; the same process resumes after the host responds. + HostRequest, } impl ProcessStatus { @@ -266,6 +269,7 @@ impl ProcessStatus { Self::Nba => 7, Self::Yield => 8, Self::Stop => 9, + Self::HostRequest => 10, } } @@ -280,11 +284,103 @@ impl ProcessStatus { 7 => Some(Self::Nba), 8 => Some(Self::Yield), 9 => Some(Self::Stop), + 10 => Some(Self::HostRequest), _ => None, } } } +/// Family of a synchronous host operation performed by a process kernel. +/// Each family numbers its request sites independently. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum HostRequestKind { + Plusargs, + FileIo, + Vcd, +} + +impl HostRequestKind { + /// Encode a request in the process's existing 64-bit delay slot. + pub const fn encode(self, site: u32) -> u64 { + let family = match self { + Self::Plusargs => 1u64, + Self::FileIo => 2, + Self::Vcd => 3, + }; + (family << 32) | site as u64 + } + + /// Decode a request, rejecting unknown families and reserved bits. + pub const fn decode(request: u64) -> Option<(Self, u32)> { + let family = match request >> 32 { + 1 => Self::Plusargs, + 2 => Self::FileIo, + 3 => Self::Vcd, + _ => return None, + }; + Some((family, request as u32)) + } +} + +/// A state slot exchanged with a synchronous host operation. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct HostRequestValue { + pub id: A, + pub width: usize, + pub signed: bool, + pub is_string: bool, +} + +impl HostRequestValue { + pub fn map(&self, map: &mut impl FnMut(A) -> B) -> HostRequestValue { + HostRequestValue { + id: map(self.id), + width: self.width, + signed: self.signed, + is_string: self.is_string, + } + } +} + +/// One synchronous host request of a process. Sites are numbered within +/// each process and family in their declaration order. Argument slots are +/// evaluated by the kernel before it suspends; result slots are written by +/// the host before the kernel resumes. `operation` and `strings` are the +/// operation family's stable, backend-independent descriptor. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct HostRequestSite { + pub process: usize, + /// This request belongs to an edge procedure lowered to a scheduled kernel. + pub requires_timed_simulation: bool, + pub kind: HostRequestKind, + pub operation: u32, + pub args: Vec>, + pub results: Vec>, + pub strings: Vec, +} + +impl HostRequestSite { + pub fn map(&self, mut map: impl FnMut(A) -> B) -> HostRequestSite { + HostRequestSite { + process: self.process, + requires_timed_simulation: self.requires_timed_simulation, + kind: self.kind, + operation: self.operation, + args: self.args.iter().map(|value| value.map(&mut map)).collect(), + results: self + .results + .iter() + .map(|value| value.map(&mut map)) + .collect(), + strings: self.strings.clone(), + } + } + + pub fn slots(&self) -> impl Iterator + '_ { + self.args.iter().chain(&self.results).map(|value| value.id) + } +} + /// State through which one process kernel exchanges control with the runtime. /// /// A process kernel is a resumable function. On entry it reads `resume` to @@ -602,6 +698,8 @@ pub struct RuntimeSchema { /// Nonblocking assignment sites of the process kernels, ordered like /// `wait_sites`. pub nba_sites: Vec>, + /// Synchronous host operations of the process kernels. + pub host_request_sites: Vec>, /// Canonical event domains whose evaluation commits the results of /// their blocking assignments, in the active region; their apply units /// commit only the nonblocking results. @@ -632,6 +730,7 @@ impl Default for RuntimeSchema { watches: Vec::new(), wait_sites: Vec::new(), nba_sites: Vec::new(), + host_request_sites: Vec::new(), active_commits: Vec::new(), time_slots: Vec::new(), } @@ -1217,6 +1316,54 @@ impl fmt::Display for RegionedAbsoluteAddrBase { mod tests { use super::*; + #[test] + fn host_request_encoding_keeps_families_and_full_site_indices_distinct() { + for kind in [ + HostRequestKind::Plusargs, + HostRequestKind::FileIo, + HostRequestKind::Vcd, + ] { + for site in [0, 1, u32::MAX] { + assert_eq!( + HostRequestKind::decode(kind.encode(site)), + Some((kind, site)) + ); + } + } + for invalid in [0, u32::MAX as u64, 4u64 << 32, 1u64 << 63] { + assert_eq!(HostRequestKind::decode(invalid), None); + } + assert_eq!( + ProcessStatus::from_code(10), + Some(ProcessStatus::HostRequest) + ); + } + + #[test] + fn host_request_mapping_relocates_operands_and_results() { + let value = |id| HostRequestValue { + id, + width: 17, + signed: true, + is_string: false, + }; + let site = HostRequestSite { + process: 2, + kind: HostRequestKind::Plusargs, + requires_timed_simulation: false, + operation: 1, + args: vec![value(3u32)], + results: vec![value(5)], + strings: vec!["COUNT=%d".into()], + }; + let relocated = site.map(|id| id + 10); + assert_eq!(relocated.slots().collect::>(), vec![13, 15]); + assert_eq!(relocated.process, 2); + assert_eq!(relocated.args[0].width, 17); + assert!(relocated.results[0].signed); + assert_eq!(relocated.strings, site.strings); + } + #[test] fn bit_access_splits_only_at_internal_boundaries() { let access = BitAccess::new(4, 11); diff --git a/crates/celox-design/src/schedule.rs b/crates/celox-design/src/schedule.rs index 2dd817f85d3..e7af72a6efd 100644 --- a/crates/celox-design/src/schedule.rs +++ b/crates/celox-design/src/schedule.rs @@ -59,6 +59,7 @@ pub struct ProcessModel { pub slots: ProcessSlots, pub waits: Vec>>, pub nbas: Vec>, + pub host_requests: Vec>, } /// One term of a wait site. @@ -98,6 +99,7 @@ impl ScheduleModel { slots: *slots, waits: Vec::new(), nbas: Vec::new(), + host_requests: Vec::new(), }) .collect(); for site in &schema.wait_sites { @@ -115,6 +117,9 @@ impl ScheduleModel { for site in &schema.nba_sites { processes[site.process].nbas.push(site.clone()); } + for site in &schema.host_request_sites { + processes[site.process].host_requests.push(site.clone()); + } let waited = schema .wait_sites .iter() diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index dde70afe4f0..4c9fa3cfe8e 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -21,8 +21,8 @@ //! [`WaitSite`]: celox_design::WaitSite use celox_design::{ - NbaSite, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, ProcessSlots, ProcessStatus, - RegionedVarAddrBase, STABLE_REGION, + HostRequestKind, NbaSite, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, ProcessSlots, + ProcessStatus, RegionedVarAddrBase, STABLE_REGION, }; use celox_sir::{ BlockId, ExecutionUnit, RegisterId, SIRBuilder, SIRInstruction, SIROffset, SIRSwitchCase, @@ -162,6 +162,17 @@ impl ProcessKernelBuilder { self.suspend(ProcessStatus::Stop) } + /// Perform a synchronous host operation, then continue at a new resume + /// point. Arguments and results live in the request site's state slots. + pub fn host_request( + &mut self, + kind: HostRequestKind, + site: u32, + ) -> Result<(), ProcessKernelError> { + self.store_delay_constant(kind.encode(site)); + self.suspend(ProcessStatus::HostRequest) + } + /// Suspend at wait site `site` of this process. The open block /// afterwards is the site's resume point: the caller lowers the wait's /// condition there and ends it with [`Self::wake_if`]. diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index 0f573973e72..9c7848e6839 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1924,6 +1924,7 @@ pub fn lower_frontend_artifact( counter_slots, wait_sites, nba_sites, + host_request_sites: Vec::new(), time_slot: None, }; let symbolic = SymbolicRtl { diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs index 8b73c5620ca..57723894725 100644 --- a/crates/celox-frontend-core/src/symbolic/artifact.rs +++ b/crates/celox-frontend-core/src/symbolic/artifact.rs @@ -117,6 +117,8 @@ pub struct SimModule { /// Nonblocking sites of the module's processes; `process` indexes /// [`Self::processes`]. pub nba_sites: Vec>, + /// Synchronous host operations of the module processes. + pub host_request_sites: Vec>, /// The variable through which the module's code reads the simulation /// time; see `RuntimeSchema::time_slots`. pub time_slot: Option, diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 9c90dab595b..487b7e05f77 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -10,10 +10,10 @@ use crate::{ }; use celox_design::{ BitAccess, CombDerivedClock, CounterKind, CounterSlots, DomainKind, ElaboratedDesign, - EventTopology, EventWatch, ExternFunction, GateOp, InitialStateValue, InstanceId, ModuleId, - NbaSite, ProcessSlots, RegionedAbsoluteAddrBase, RegionedStateAddr, RuntimeCombObserver, - RuntimeErrorInfo, RuntimeEventKind, RuntimeEventSite, RuntimeSchema, STABLE_REGION, StateAddr, - StateObjectId, TriggerSet, VarAtomBase, VariableMetadata, WaitSite, + EventTopology, EventWatch, ExternFunction, GateOp, HostRequestSite, InitialStateValue, + InstanceId, ModuleId, NbaSite, ProcessSlots, RegionedAbsoluteAddrBase, RegionedStateAddr, + RuntimeCombObserver, RuntimeErrorInfo, RuntimeEventKind, RuntimeEventSite, RuntimeSchema, + STABLE_REGION, StateAddr, StateObjectId, TriggerSet, VarAtomBase, VariableMetadata, WaitSite, }; use celox_sir::{ BasicBlock, ExecutionUnit, LaneUnit, ParallelSirProgram, SIRInstruction, SIRTerminator, @@ -1322,6 +1322,7 @@ pub fn schedule_symbolic_rtl( let TimingMetadata { wait_sites, nba_sites, + host_request_sites, time_slots, .. } = timing; @@ -1557,6 +1558,10 @@ pub fn schedule_symbolic_rtl( wait_sites.iter().map(|site| site.map(project)).collect(); let nba_sites: Vec> = nba_sites.iter().map(|site| site.map(project)).collect(); + let host_request_sites: Vec> = host_request_sites + .iter() + .map(|site| site.map(project)) + .collect(); let active_commits: Vec = active_commits.into_iter().map(project).collect(); let time_slots: Vec = time_slots.into_iter().map(project).collect(); // The runtime reads counters, the signals waits watch and staged @@ -1580,6 +1585,7 @@ pub fn schedule_symbolic_rtl( .flat_map(|site| [Some(site.value), site.offset, site.pending]) .flatten(), ) + .chain(host_request_sites.iter().flat_map(|site| site.slots())) .collect(); // A package variable's state object maps back to the package's own // variable, not to one of its aliases. @@ -1626,6 +1632,7 @@ pub fn schedule_symbolic_rtl( watches, wait_sites, nba_sites, + host_request_sites, active_commits, time_slots, }, @@ -2805,6 +2812,7 @@ struct TimingMetadata { counter_slots: Vec>, wait_sites: Vec>, nba_sites: Vec>, + host_request_sites: Vec>, time_slots: Vec, } @@ -2961,6 +2969,7 @@ fn relocate_timing( counter_slots: Vec::new(), wait_sites: Vec::new(), nba_sites: Vec::new(), + host_request_sites: Vec::new(), time_slots: Vec::new(), }; for (&instance, module) in instances { @@ -2981,6 +2990,17 @@ fn relocate_timing( process: process_index[&(instance, site.process)], ..site.map(locate) })); + metadata + .host_request_sites + .extend( + module + .host_request_sites + .iter() + .map(|site| HostRequestSite { + process: process_index[&(instance, site.process)], + ..site.map(locate) + }), + ); metadata.time_slots.extend(module.time_slot.map(locate)); } metadata diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 66e5d5607c9..c0fa018adc5 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -2381,18 +2381,19 @@ fn lower_module_with_overrides( ) }; mark_ff_event_domains(&event_vars, &mut variables); - let (initial_values, processes, wait_sites, nba_sites) = lower_initial_processes( - module, - &mut variables, - &mut name_to_id, - &constants, - ¶meter_types, - four_state, - &mut runtime_event_sites, - &mut runtime_errors, - &mut extern_functions, - warnings, - )?; + let (initial_values, processes, wait_sites, nba_sites, host_request_sites) = + lower_initial_processes( + module, + &mut variables, + &mut name_to_id, + &constants, + ¶meter_types, + four_state, + &mut runtime_event_sites, + &mut runtime_errors, + &mut extern_functions, + warnings, + )?; initial_memory_values.extend(initial_values); let shared_variables = variables @@ -2493,6 +2494,7 @@ fn lower_module_with_overrides( counter_slots: Vec::new(), wait_sites, nba_sites, + host_request_sites, time_slot: name_to_id.get(TIME_SLOT).copied(), }, variables, @@ -3225,11 +3227,12 @@ fn lower_initial_processes( Vec, Vec>, Vec>, + Vec>, ), sv::AnalyzerError, > { if module.initial_processes().is_empty() { - return Ok((Vec::new(), Vec::new(), Vec::new(), Vec::new())); + return Ok((Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new())); } let mut values = Vec::new(); let mut runtime = Vec::new(); @@ -3284,7 +3287,7 @@ fn lower_initial_processes( } } if runtime.is_empty() { - return Ok((values, Vec::new(), Vec::new(), Vec::new())); + return Ok((values, Vec::new(), Vec::new(), Vec::new(), Vec::new())); } let mut next_id = SourceVarId( @@ -3342,6 +3345,7 @@ fn lower_initial_processes( pm.extern_functions = std::mem::take(extern_functions); let mut wait_sites = Vec::new(); let mut nba_sites = Vec::new(); + let mut host_request_sites = Vec::new(); let processes = runtime .into_iter() .zip(slots) @@ -3354,6 +3358,10 @@ fn lower_initial_processes( )?; wait_sites.extend(kernel.wait_sites); nba_sites.extend(kernel.nba_sites); + host_request_sites.extend(kernel.host_request_sites.into_iter().map(|mut site| { + site.process = index; + site + })); Ok(SymbolicProcess { kernel: kernel.unit, slots, @@ -3363,7 +3371,13 @@ fn lower_initial_processes( *runtime_event_sites = std::mem::take(&mut pm.runtime_event_sites); *runtime_errors = std::mem::take(&mut pm.runtime_errors); *extern_functions = std::mem::take(&mut pm.extern_functions); - Ok((values, processes?, wait_sites, nba_sites)) + Ok(( + values, + processes?, + wait_sites, + nba_sites, + host_request_sites, + )) } fn lower_comb_processes( @@ -5200,6 +5214,9 @@ fn lower_bit_vector_function_slt( SystemFunction::Time | SystemFunction::Stime | SystemFunction::Random + | SystemFunction::DistUniform + | SystemFunction::TestPlusargs + | SystemFunction::ValuePlusargs | SystemFunction::Urandom | SystemFunction::UrandomRange | SystemFunction::Timeunit diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index ed33b0b0180..7fab801035a 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -66,6 +66,7 @@ pub(super) struct Ff<'p, 'a> { wait_sites: Vec>, /// The nonblocking assignment sites of the process, by local index. nba_sites: Vec>, + host_request_sites: Vec>, direct: bool, } @@ -114,6 +115,7 @@ impl<'p, 'a> Ff<'p, 'a> { process: 0, wait_sites: Vec::new(), nba_sites: Vec::new(), + host_request_sites: Vec::new(), } } @@ -830,6 +832,20 @@ impl<'p, 'a> Ff<'p, 'a> { args, .. } => self.urandom_range(args)?, + Expr::Call { + callee: + sv::ir::Callee::System( + function @ (sv::ir::SystemFunction::TestPlusargs + | sv::ir::SystemFunction::ValuePlusargs), + ), + args, + .. + } => self.plusargs(*function, args)?, + Expr::Call { + callee: sv::ir::Callee::System(sv::ir::SystemFunction::DistUniform), + args, + .. + } => self.dist_uniform(args)?, Expr::Call { callee: sv::ir::Callee::System(sv::ir::SystemFunction::Random), args, @@ -1390,6 +1406,308 @@ impl<'p, 'a> Ff<'p, 'a> { Ok(result) } + /// Annex N's uniform transform, represented as an exact rational. The + /// largest product has 79 bits, so 96-bit temporaries avoid overflow. + fn dist_uniform( + &mut self, + args: &[Option], + ) -> Result { + use sv::ir::{BinaryOp as B, Expr as E}; + let seed = args + .first() + .and_then(Option::as_ref) + .ok_or_else(|| unsupported("seed of `$dist_uniform`"))?; + let (lvalues, seed_read) = self.capture_system_actual(seed)?; + let seed_width = self + .m + .comparison_width(&seed_read, &seed_read) + .ok_or_else(|| unsupported("integral seed of `$dist_uniform`"))?; + let seed_signed = self.expr_signed(seed); + let original = self + .host_hidden( + "dist_original_seed", + &seed_read, + seed_width, + seed_signed, + true, + )? + .1; + let mut bound = |index| -> Result { + let value = self.hoist( + args.get(index) + .and_then(Option::as_ref) + .ok_or_else(|| unsupported("bounds of `$dist_uniform`"))?, + )?; + let value = E::Resize { + expr: Box::new(value), + width: 32, + signed: true, + }; + self.hidden("dist_bound", &value, true) + }; + let start = bound(1)?; + let end = bound(2)?; + let current = self.int_formal(original.clone()); + let current = self.hidden("dist_old_seed", ¤t, false)?; + // The distribution's inout formal is int. Only the final copyout + // writes the caller's actual, whose selector was captured once. + let formal = self.hidden("dist_seed_formal", ¤t, true)?; + let full = self.random(Some(&formal))?; + let next = E::Binary { + left: Box::new(E::Binary { + left: Box::new(E::Mux { + condition: Box::new(E::Binary { + left: Box::new(current.clone()), + op: B::Eq, + right: Box::new(E::Literal("32'd0".into())), + }), + then_expr: Box::new(E::Literal("32'd259341593".into())), + else_expr: Box::new(current.clone()), + }), + op: B::Mul, + right: Box::new(E::Literal("32'd69069".into())), + }), + op: B::Add, + right: Box::new(E::Literal("32'd1".into())), + }; + let next = self.hidden("dist_next_seed", &next, false)?; + let lit = |n: i128| { + if n < 0 { + E::Unary { + op: sv::ir::UnaryOp::Minus, + expr: Box::new(E::Literal(format!("96'sd{}", -n))), + } + } else { + E::Literal(format!("96'sd{n}")) + } + }; + let bin = |left, op, right| E::Binary { + left: Box::new(left), + op, + right: Box::new(right), + }; + let wide = |value| E::Resize { + expr: Box::new(value), + width: 96, + signed: true, + }; + let mux = |condition, then_expr, else_expr| E::Mux { + condition: Box::new(condition), + then_expr: Box::new(then_expr), + else_expr: Box::new(else_expr), + }; + let start = wide(start); + let end = wide(end); + let invalid = bin(start.clone(), B::Ge, end.clone()); + // If end is INT_MAX, Annex N shifts the lower bound down by one, + // and adds one after the uniform transform. + let shifted = bin(end.clone(), B::Eq, lit(i32::MAX as i128)); + let shifted_value = mux(shifted.clone(), lit(1), lit(0)); + let a = bin(start.clone(), B::Sub, shifted_value.clone()); + let span = bin(bin(end.clone(), B::Sub, start.clone()), B::Add, lit(1)); + // Extract the 23-bit mantissa before converting to signed wide + // arithmetic. Widening the raw seed as signed would sign-extend its + // high bit, and a logical shift would then retain those high ones. + let m = wide(E::Resize { + expr: Box::new(bin(next, B::Shr, E::Literal("32'd9".into()))), + width: 32, + signed: false, + }); + let fraction = bin( + bin(m.clone(), B::Mul, lit(8_388_608)), + B::Add, + bin(lit(8_388_608), B::Add, m), + ); + let denominator = lit(1i128 << 46); + let numerator = bin( + bin(a, B::Mul, denominator.clone()), + B::Add, + bin(span, B::Mul, fraction), + ); + let numerator = bin( + numerator, + B::Add, + bin(shifted_value, B::Mul, denominator.clone()), + ); + let numerator = self + .host_hidden("dist_numerator", &numerator, 96, true, false)? + .1; + let negative_integral = bin( + bin(numerator.clone(), B::Lt, lit(0)), + B::LogicAnd, + bin( + bin(numerator.clone(), B::BitAnd, lit((1i128 << 46) - 1)), + B::Eq, + lit(0), + ), + ); + let value = bin( + bin(numerator, B::Sar, lit(46)), + B::Sub, + mux(negative_integral, lit(1), lit(0)), + ); + let value = self.host_hidden("dist_value", &value, 96, true, false)?.1; + let value = mux( + bin(value.clone(), B::Lt, start.clone()), + start.clone(), + mux(bin(value.clone(), B::Gt, end.clone()), end.clone(), value), + ); + let is_full = bin( + bin(start.clone(), B::Eq, lit(i32::MIN as i128)), + B::LogicAnd, + bin(end, B::Eq, lit(i32::MAX as i128)), + ); + let value = mux(invalid.clone(), start, mux(is_full, wide(full), value)); + // A degenerate/reversed interval returns start without consuming seed. + let next = E::Resize { + expr: Box::new(formal), + width: seed_width, + signed: true, + }; + let restored = mux(invalid, original, next); + match lvalues.as_slice() { + [lvalue] => self.assign(lvalue, &restored)?, + parts => self.assign_concat(parts, &restored)?, + } + Ok(E::Resize { + expr: Box::new(value), + width: 32, + signed: true, + }) + } + + /// Capture an inout/output actual's reference before reading or writing + /// it, including selectors changed by the call or by other selectors. + fn capture_system_actual( + &mut self, + expr: &sv::ir::Expr, + ) -> Result<(Vec, sv::ir::Expr), sv::AnalyzerError> { + use sv::ir::{Expr, LValue}; + let parts = + lvalue_from_expr(expr).ok_or_else(|| unsupported("integral output/inout actual"))?; + let signed = self.expr_signed(expr); + let mut captured = Vec::new(); + for part in parts { + let part = self.hoist_lvalue(&part)?; + captured.push(self.freeze_lvalue(part)?); + } + let reads = captured + .iter() + .map(|part| match part { + LValue::Ident(name) => Expr::Ident(name.clone()), + LValue::Select { name, msb, lsb, .. } => Expr::Select { + expr: Box::new(Expr::Ident(name.clone())), + msb: msb.clone(), + lsb: lsb.clone(), + signed, + }, + }) + .collect::>(); + let read = if reads.len() == 1 { + reads.into_iter().next().unwrap() + } else { + Expr::Concat(reads) + }; + Ok((captured, read)) + } + + fn host_hidden( + &mut self, + purpose: &str, + expr: &sv::ir::Expr, + width: usize, + signed: bool, + four_state: bool, + ) -> Result<(SourceVarId, sv::ir::Expr), sv::AnalyzerError> { + let value = self.eval(expr, Some((width, signed)))?; + let (id, name) = self.m.temp(purpose, width, signed, four_state); + self.store(id, SIROffset::Static(0), width, value); + Ok((id, sv::ir::Expr::Ident(name))) + } + + fn plusargs( + &mut self, + function: sv::ir::SystemFunction, + args: &[Option], + ) -> Result { + use celox_design::{HostRequestKind, HostRequestSite, HostRequestValue}; + use sv::ir::Expr; + if self.kernel.is_none() { + return Err(unsupported(format!( + "{} outside a timed process", + function.name() + ))); + } + let query = self.hoist( + args.first() + .and_then(Option::as_ref) + .ok_or_else(|| unsupported("plusargs query"))?, + )?; + let width = self + .m + .comparison_width(&query, &query) + .ok_or_else(|| unsupported("packed plusargs query"))?; + let (query_id, _) = self.host_hidden("plusargs_query", &query, width, false, true)?; + let value_query = function == sv::ir::SystemFunction::ValuePlusargs; + let mut results = Vec::new(); + let (ret_id, ret_name) = self.m.temp("plusargs_result", 32, true, false); + results.push(HostRequestValue { + id: ret_id, + width: 32, + signed: true, + is_string: false, + }); + let target = if value_query { + let expr = args + .get(1) + .and_then(Option::as_ref) + .ok_or_else(|| unsupported("plusargs destination"))?; + let (lvalues, captured) = self.capture_system_actual(expr)?; + let width = self + .m + .comparison_width(expr, expr) + .ok_or_else(|| unsupported("integral plusargs destination"))?; + let (id, result) = self.host_hidden("plusargs_value", &captured, width, false, true)?; + results.push(HostRequestValue { + id, + width, + signed: false, + is_string: false, + }); + Some((lvalues, result)) + } else { + None + }; + let site = self + .host_request_sites + .iter() + .filter(|site| site.kind == HostRequestKind::Plusargs) + .count() as u32; + self.host_request_sites.push(HostRequestSite { + process: 0, + kind: HostRequestKind::Plusargs, + requires_timed_simulation: false, + operation: u32::from(value_query), + args: vec![HostRequestValue { + id: query_id, + width, + signed: false, + is_string: true, + }], + results, + strings: Vec::new(), + }); + self.with_kernel(|kernel| kernel.host_request(HostRequestKind::Plusargs, site)) + .map_err(kernel_error)?; + if let Some((lvalues, result)) = target { + match lvalues.as_slice() { + [lvalue] => self.assign(lvalue, &result)?, + parts => self.assign_concat(parts, &result)?, + } + } + Ok(Expr::Ident(ret_name)) + } + fn store(&mut self, id: SourceVarId, offset: SIROffset, width: usize, value: RegisterId) { let value = if let Some((enabled, forced)) = self.m.force_controls(id) { let condition = self.b.alloc_bit(1, false); @@ -3367,6 +3685,7 @@ impl Ff<'_, '_> { unit, wait_sites: self.wait_sites, nba_sites: self.nba_sites, + host_request_sites: self.host_request_sites, }) } @@ -3743,6 +4062,7 @@ pub(super) struct KernelUnit { pub unit: ExecutionUnit, pub wait_sites: Vec>, pub nba_sites: Vec>, + pub host_request_sites: Vec>, } /// Iterations, as a power of two, between the yields of a kernel loop that diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 1be7086e744..b0a0ce5fea2 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -607,6 +607,7 @@ pub(crate) fn project_module_with_ids( counter_slots: Vec::new(), wait_sites: Vec::new(), nba_sites: Vec::new(), + host_request_sites: Vec::new(), time_slot: None, }, ids, diff --git a/crates/celox-napi/src/lib.rs b/crates/celox-napi/src/lib.rs index a96640a9df6..aa4b99a5079 100644 --- a/crates/celox-napi/src/lib.rs +++ b/crates/celox-napi/src/lib.rs @@ -78,6 +78,8 @@ pub struct NapiOptimizeOptions { #[napi(object)] pub struct NapiOptions { pub four_state: Option, + /// Ordered SystemVerilog command-line arguments (leading `+` optional). + pub plusargs: Option>, pub vcd: Option, /// Optimization level preset: "O0", "O1", or "O2". /// Takes precedence over `optimize` and `optimize_options`. @@ -119,6 +121,7 @@ pub struct NapiOptions { struct ParsedOptionsCommon { diagnostic_policy: celox::DiagnosticPolicy, four_state: bool, + plusargs: Vec, optimize_options: celox::OptimizeOptions, vcd: Option, false_loops: Vec<( @@ -381,6 +384,7 @@ fn parse_options_common(options: &Option) -> Result) -> Result Ok(ParsedOptionsCommon { diagnostic_policy: Default::default(), four_state: false, + plusargs: Vec::new(), optimize_options: celox::OptimizeOptions::all(), vcd: None, false_loops: Vec::new(), @@ -635,8 +640,10 @@ fn apply_options<'a, T>( mut builder: celox::SimulatorBuilder<'a, T>, opts: &ParsedOptions, ) -> celox::SimulatorBuilder<'a, T> { - builder = builder.diagnostic_policy(opts.diagnostic_policy.clone()); - builder = builder.four_state(opts.four_state); + builder = builder + .diagnostic_policy(opts.diagnostic_policy.clone()) + .four_state(opts.four_state) + .plusargs(opts.plusargs.clone()); builder = builder.optimize_options(opts.optimize_options.clone()); builder = builder.threads(opts.optimize_options.parallel_lanes() as usize); builder = builder.cranelift_options(opts.cranelift_options); @@ -3789,6 +3796,7 @@ mod tests { common: ParsedOptionsCommon { diagnostic_policy: Default::default(), four_state: false, + plusargs: Vec::new(), optimize_options: celox::OptimizeOptions::all(), vcd: None, false_loops: vec![], @@ -3929,6 +3937,7 @@ mod tests { let options = Some(NapiOptions { vcd: Some(path.to_str().unwrap().to_owned()), four_state: None, + plusargs: None, opt_level: None, pass_overrides: None, optimize: None, diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index 46c19a270c8..8e4ab97d86b 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -6,6 +6,7 @@ mod edge; mod error; mod event_buffer; pub mod parallel; +pub mod plusargs; mod reflection; mod schedule; pub mod scheduler; diff --git a/crates/celox-runtime/src/plusargs.rs b/crates/celox-runtime/src/plusargs.rs new file mode 100644 index 00000000000..46db5433360 --- /dev/null +++ b/crates/celox-runtime/src/plusargs.rs @@ -0,0 +1,281 @@ +//! IEEE 1800-2023 21.6 command-line arguments. Argument order is significant. +use num_bigint::BigUint; + +#[derive(Clone, Debug, Default)] +pub struct Plusargs(pub Vec); + +impl Plusargs { + /// Match a prefix, ignoring a single leading `+` on configured arguments. + pub fn test(&self, query: &[u8]) -> bool { + self.find(query).is_some() + } + + fn find(&self, query: &[u8]) -> Option<&[u8]> { + self.0.iter().find_map(|arg| { + arg.strip_prefix('+') + .unwrap_or(arg) + .as_bytes() + .strip_prefix(query) + }) + } + + /// Return no value for an unmatched query, preserving the caller's target. + /// A conversion containing an illegal character returns an all-X value. + pub fn value(&self, query: &[u8], width: usize) -> Result, String> { + let percent = query + .iter() + .position(|b| *b == b'%') + .ok_or("$value$plusargs requires a conversion")?; + let mut format = &query[percent + 1..]; + if format.first() == Some(&b'0') { + format = &format[1..]; + } + if format.len() != 1 { + return Err("$value$plusargs requires exactly one trailing conversion".into()); + } + let conversion = format[0].to_ascii_lowercase(); + let radix = match conversion { + b'b' => 2, + b'o' => 8, + b'h' | b'x' => 16, + b'd' => 10, + b's' => 0, + b'e' | b'f' | b'g' => { + return Err("real conversion of $value$plusargs is unsupported".into()); + } + _ => return Err("unsupported conversion of $value$plusargs".into()), + }; + let Some(input) = self.find(&query[..percent]) else { + return Ok(None); + }; + let mask = (BigUint::from(1u8) << width) - BigUint::from(1u8); + if radix == 0 { + return Ok(Some(( + BigUint::from_bytes_be(input) & &mask, + BigUint::default(), + ))); + } + let mut digits = input; + while digits.first().is_some_and(u8::is_ascii_whitespace) { + digits = &digits[1..]; + } + let negative = digits.first() == Some(&b'-'); + let signed = negative || digits.first() == Some(&b'+'); + if signed { + digits = &digits[1..]; + } + // Separators may follow a digit, but cannot replace the first digit + // (IEEE 1800-2023 5.7.1). Validate before discarding separators. + if digits.first() == Some(&b'_') { + return Ok(Some((BigUint::default(), mask))); + } + let compact: Vec<_> = digits.iter().copied().filter(|b| *b != b'_').collect(); + let digits = compact.as_slice(); + // A single decimal unknown digit denotes an entire X/Z value; + // a sign followed by an unknown digit is not a decimal input field + // (21.3.4.3, Table 21-7). + if radix == 10 && !signed && digits.len() == 1 { + match digits[0] { + b'x' | b'X' => return Ok(Some((BigUint::default(), mask))), + b'z' | b'Z' | b'?' => return Ok(Some((mask.clone(), mask))), + _ => {} + } + } + if radix != 10 + && digits + .iter() + .any(|b| matches!(b, b'x' | b'X' | b'z' | b'Z' | b'?')) + { + let bits = match radix { + 2 => 1, + 8 => 3, + _ => 4, + }; + let mut value = BigUint::default(); + let mut unknown = BigUint::default(); + for &digit in digits { + value <<= bits; + unknown <<= bits; + match digit { + b'x' | b'X' => unknown |= BigUint::from((1u8 << bits) - 1), + b'z' | b'Z' | b'?' => { + let group = BigUint::from((1u8 << bits) - 1); + value |= &group; + unknown |= group; + } + _ => match (digit as char).to_digit(radix) { + Some(digit) => value |= BigUint::from(digit), + None => return Ok(Some((BigUint::default(), mask))), + }, + } + } + // IEEE 1800-2023 11.4.3: negation of a value with any X/Z + // bit produces an entirely unknown result. Apply it before + // narrowing, including unknown digits above the target width. + if negative { + return Ok(Some((BigUint::default(), mask))); + } + return Ok(Some((value & &mask, unknown & mask))); + } + let value = if digits.is_empty() { + Some(BigUint::default()) + } else { + BigUint::parse_bytes(digits, radix) + }; + match value { + Some(value) => { + let value = value & &mask; + let value = if negative && value != BigUint::default() { + (&mask + BigUint::from(1u8)) - value + } else { + value + }; + Ok(Some((value, BigUint::default()))) + } + None => Ok(Some((BigUint::default(), mask))), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + #[test] + fn negative_nondecimal_unknowns_propagate_through_negation() { + for (format, input, width) in [ + ("%h", "-1x", 32), + ("%x", "-1Z", 65), + ("%o", "-7?", 17), + ("%b", "-10x", 8), + ("%h", "-x10", 4), + ] { + let args = Plusargs(vec![format!("+number={input}")]); + let mask = (BigUint::from(1u8) << width) - BigUint::from(1u8); + assert_eq!( + args.value(format!("number={format}").as_bytes(), width) + .unwrap(), + Some((BigUint::default(), mask)), + "{input} as {format}" + ); + } + // The sign must not change the existing positive four-state parser, + // and known negative magnitudes still use ordinary two's complement. + let args = Plusargs(vec!["+x=1x".into(), "+z=1z".into(), "+negative=-1f".into()]); + assert_eq!( + args.value(b"x=%h", 8).unwrap(), + Some((16u32.into(), 15u32.into())) + ); + assert_eq!( + args.value(b"z=%h", 8).unwrap(), + Some((31u32.into(), 15u32.into())) + ); + assert_eq!( + args.value(b"negative=%h", 8).unwrap(), + Some((225u32.into(), 0u32.into())) + ); + } + + #[test] + fn decimal_unknown_digits_retain_their_four_state_value() { + for (input, z) in [ + ("x", false), + ("X", false), + ("z", true), + ("Z", true), + ("?", true), + ("z_", true), + ] { + let args = Plusargs(vec![format!("+number={input}")]); + let mask = (BigUint::from(1u8) << 65usize) - BigUint::from(1u8); + assert_eq!( + args.value(b"number=%D", 65).unwrap(), + Some((if z { mask.clone() } else { BigUint::default() }, mask)), + "{input}" + ); + } + for input in [ + "+z", "-z", "+Z", "-Z", "+x", "-x", "+X", "-X", "+?", "-?", "zz", "1z", "z1", + ] { + let args = Plusargs(vec![format!("+number={input}")]); + assert_eq!( + args.value(b"number=%d", 8).unwrap(), + Some((0u32.into(), 255u32.into())), + "{input}" + ); + } + } + + #[test] + fn numeric_separators_follow_the_first_digit() { + for format in ["%d", "%h", "%o", "%b"] { + for input in ["_12", "-_12", "+_12", "___", " _1", "-_x"] { + let args = Plusargs(vec![format!("+number={input}")]); + assert_eq!( + args.value(format!("number={format}").as_bytes(), 8) + .unwrap(), + Some((0u32.into(), 255u32.into())), + "{input} as {format}" + ); + } + let args = Plusargs(vec!["+number=1__0_".into()]); + let expected = match format { + "%d" => 10, + "%h" => 16, + "%o" => 8, + _ => 2, + }; + assert_eq!( + args.value(format!("number={format}").as_bytes(), 8) + .unwrap(), + Some((BigUint::from(expected as u32), BigUint::default())) + ); + } + let args = Plusargs(vec!["+number=-1_2_".into(), "+text=_12".into()]); + assert_eq!( + args.value(b"number=%d", 8).unwrap(), + Some((244u32.into(), 0u32.into())) + ); + assert_eq!( + args.value(b"text=%s", 24).unwrap(), + Some((0x5f3132u32.into(), 0u32.into())) + ); + } + + #[test] + fn ordered_prefixes_and_conversions() { + let args = Plusargs(vec![ + "+HELLO".into(), + "+n=-12".into(), + "+n=9".into(), + "+hex=ab".into(), + "+bad=12!".into(), + "+s=abc".into(), + "+empty=".into(), + ]); + assert!(args.test(b"HE")); + assert!(!args.test(b"LO")); + assert!(!args.test(b"+HE")); + assert_eq!( + args.value(b"n=%d", 8).unwrap(), + Some((244u32.into(), 0u32.into())) + ); + assert_eq!( + args.value(b"hex=%0H", 4).unwrap(), + Some((11u32.into(), 0u32.into())) + ); + assert_eq!( + args.value(b"bad=%d", 8).unwrap(), + Some((0u32.into(), 255u32.into())) + ); + assert_eq!( + args.value(b"s=%s", 16).unwrap(), + Some((0x6263u32.into(), 0u32.into())) + ); + assert_eq!( + args.value(b"empty=%d", 32).unwrap(), + Some((0u32.into(), 0u32.into())) + ); + assert_eq!(args.value(b"missing=%d", 32).unwrap(), None); + assert!(args.value(b"real=%f", 32).is_err()); + } +} diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index bee04388f19..ce323f5dec7 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -144,6 +144,11 @@ impl ResolvedSchedule { .collect() }) .collect(), + host_requests: process + .host_requests + .iter() + .map(|site| site.map(|id| resolve(&id))) + .collect(), nba_sites: process .nbas .iter() diff --git a/crates/celox-runtime/src/simulation/host.rs b/crates/celox-runtime/src/simulation/host.rs index 95e99bd1a6a..d583777dca6 100644 --- a/crates/celox-runtime/src/simulation/host.rs +++ b/crates/celox-runtime/src/simulation/host.rs @@ -23,6 +23,24 @@ pub trait UnitExecutor { fn run_process(&mut self, index: usize) -> Result<(), Halt> { Ok(self.backend_mut().run_process(index)?) } + + /// Perform a synchronous request after a kernel has stored its + /// arguments and before that kernel resumes. The timestamp is the + /// current scheduler time in the design's precision units. + fn host_request( + &mut self, + request: &celox_design::HostRequestSite, + _timestamp: u64, + ) -> Result<(), Halt> { + Err(SimulatorErrorCode::Runtime { + message: format!( + "host does not support {:?} request {}", + request.kind, request.operation + ), + signals: Vec::new(), + } + .into()) + } } /// What a timed step tells the host around the units it executes. Every diff --git a/crates/celox-runtime/src/simulation/process.rs b/crates/celox-runtime/src/simulation/process.rs index 849d5a95819..d117a3a0d94 100644 --- a/crates/celox-runtime/src/simulation/process.rs +++ b/crates/celox-runtime/src/simulation/process.rs @@ -1,7 +1,7 @@ //! The process phase of a round: running ready kernels and filing them //! where they resume. -use celox_design::ProcessStatus; +use celox_design::{HostRequestKind, ProcessStatus}; use super::SimulationState; use super::host::SimulationExecutor; @@ -59,6 +59,20 @@ impl SimulationState { self.charge(*returns, Some(process))?; return Ok(true); } + Some(ProcessStatus::HostRequest) => { + let (kind, index) = HostRequestKind::decode(delay()) + .ok_or(SimulatorErrorCode::InternalError)?; + let request = self.model.processes[process] + .host_requests + .iter() + .filter(|site| site.kind == kind) + .nth(index as usize) + .ok_or(SimulatorErrorCode::InternalError)?; + executor.host_request(request, current_time)?; + *returns += 1; + self.charge(*returns, Some(process))?; + return Ok(true); + } // The process continues after the `$stop`, first, when the // simulation does. Some(ProcessStatus::Stop) => { diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs index c0da3a86a8c..15f0fa38bc0 100644 --- a/crates/celox-runtime/src/timing.rs +++ b/crates/celox-runtime/src/timing.rs @@ -136,6 +136,7 @@ pub struct ProcessRefs { pub wait_sites: Vec>, /// Nonblocking sites by local index. pub nba_sites: Vec, + pub host_requests: Vec>, } impl ProcessRefs { @@ -146,6 +147,7 @@ impl ProcessRefs { delay, wait_sites: Vec::new(), nba_sites: Vec::new(), + host_requests: Vec::new(), } } } diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index 700cf2a3394..2599b2e1306 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -296,10 +296,14 @@ pub(in crate::ast) fn bind_value( continue; } ExprKind::Literal(text) => { - if typecheck::integral_literal_type_metadata(text).is_none() { - return Err(unsupported("primary literal")); + if let Some(packed) = packed_string_literal(text) { + values.push(Expr::Literal(packed)); + } else { + if typecheck::integral_literal_type_metadata(text).is_none() { + return Err(unsupported("primary literal")); + } + values.push(Expr::Literal(text.clone())); } - values.push(Expr::Literal(text.clone())); continue; } ExprKind::Name(name) if !name.spelling.starts_with('$') => { @@ -463,7 +467,7 @@ pub(in crate::ast) fn bind_value( } if function.is_effectful() && args.iter().filter_map(|arg| arg.value).any(|id| { matches!(&native.expression(ungroup(id, native)).kind, ExprKind::Literal(text) - if typecheck::integral_literal_type_metadata(text).is_none()) + if typecheck::integral_literal_type_metadata(text).is_none() && packed_string_literal(text).is_none()) }) { return Err(unsupported(format!("integral argument of `{name}`"))); } @@ -718,6 +722,9 @@ pub(in crate::ast) fn bind_value( function, SystemFunction::Urandom | SystemFunction::Random + | SystemFunction::DistUniform + | SystemFunction::TestPlusargs + | SystemFunction::ValuePlusargs | SystemFunction::UrandomRange ) { for (position, arg) in operands.iter().enumerate() { @@ -742,7 +749,9 @@ pub(in crate::ast) fn bind_value( { return Err(AnalyzerError::InvalidSystemTfCall { name: name.clone(), - detail: "seed must be an integral variable".into(), + detail: + "output/inout argument must be an integral variable" + .into(), }); } } @@ -1112,3 +1121,102 @@ pub(in crate::ast) fn selected_lvalue( }; Ok(lvalue) } + +/// String literals in integral contexts are unsigned packed arrays of bytes +/// (IEEE 1800-2023 5.9). Keep the semantic IR integral, including escapes. +fn packed_string_literal(text: &str) -> Option { + let text = if let Some(text) = text.strip_prefix("\"\"\"") { + text.strip_suffix("\"\"\"")? + } else { + text.strip_prefix('"')?.strip_suffix('"')? + }; + let mut input = text.bytes().peekable(); + let mut bytes = Vec::new(); + while let Some(byte) = input.next() { + if byte != b'\\' { + bytes.push(byte); + continue; + } + let escaped = input.next()?; + let value = match escaped { + b'n' => b'\n', + b't' => b'\t', + b'v' => 11, + b'f' => 12, + b'a' => 7, + b'\\' => b'\\', + b'"' => b'"', + b'\n' => continue, + b'\r' if input.peek() == Some(&b'\n') => { + input.next(); + continue; + } + b'0'..=b'7' => { + let mut value = escaped - b'0'; + for _ in 0..2 { + if let Some(&digit @ b'0'..=b'7') = input.peek() { + input.next(); + value = value.wrapping_mul(8).wrapping_add(digit - b'0'); + } else { + break; + } + } + value + } + b'x' => { + let mut value = 0u8; + let mut count = 0; + for _ in 0..2 { + if let Some(digit) = input.peek().and_then(|byte| (*byte as char).to_digit(16)) + { + input.next(); + value = value * 16 + digit as u8; + count += 1; + } else { + break; + } + } + if count == 0 { + return None; + } + value + } + other => other, + }; + bytes.push(value); + } + let width = (bytes.len() * 8).max(8); + Some(format!( + "{}'h{}", + width, + num_bigint::BigUint::from_bytes_be(&bytes).to_str_radix(16) + )) +} + +#[cfg(test)] +mod string_literal_tests { + use super::packed_string_literal; + + #[test] + fn packed_string_literal_triple_delimiters_preserve_content() { + assert_eq!(packed_string_literal("\"\"\"\"\"\""), Some("8'h0".into())); + assert_eq!( + packed_string_literal("\"\"\"A\"B\nC\"\"\""), + Some("40'h4122420a43".into()) + ); + assert_eq!( + packed_string_literal("\"\"\"A\r\nB\"\"\""), + Some("32'h410d0a42".into()) + ); + } + + #[test] + fn packed_string_literal_escaped_newlines_ignore_lf_and_crlf() { + for delimiter in ["\"", "\"\"\""] { + for newline in ["\n", "\r\n"] { + let literal = format!("{delimiter}ab\\{newline}cd{delimiter}"); + assert_eq!(packed_string_literal(&literal), Some("32'h61626364".into())); + } + } + } +} diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index da85b26d31d..a8048bc1555 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -56,6 +56,12 @@ pub enum SystemFunction { Isunknown, /// `$random` (20.14.1), with the algorithm of Annex N. Random, + /// `$dist_uniform` (20.14.2). + DistUniform, + /// Command-line prefix query (21.6). + TestPlusargs, + /// Command-line value query (21.6). + ValuePlusargs, /// `$urandom` (18.13.1). Urandom, /// `$urandom_range` (18.13.2). @@ -99,6 +105,9 @@ impl SystemFunction { Self::Onehot0 => "$onehot0", Self::Isunknown => "$isunknown", Self::Random => "$random", + Self::DistUniform => "$dist_uniform", + Self::TestPlusargs => "$test$plusargs", + Self::ValuePlusargs => "$value$plusargs", Self::Urandom => "$urandom", Self::UrandomRange => "$urandom_range", } @@ -128,7 +137,15 @@ impl SystemFunction { /// Whether each call has an effect, so that copies of one call made by /// the analyzer must not run it twice. pub fn is_effectful(self) -> bool { - matches!(self, Self::Random | Self::Urandom | Self::UrandomRange) + matches!( + self, + Self::Random + | Self::DistUniform + | Self::TestPlusargs + | Self::ValuePlusargs + | Self::Urandom + | Self::UrandomRange + ) } /// Whether a call reads the state of the simulation: it has an effect, @@ -141,7 +158,8 @@ impl SystemFunction { /// Whether the call writes argument `position` back, as `$random(seed)` /// updates its seed variable. pub fn writes_argument(self, position: usize) -> bool { - self == Self::Random && position == 0 + (matches!(self, Self::Random | Self::DistUniform) && position == 0) + || (self == Self::ValuePlusargs && position == 1) } /// The width and signedness of a call that is lowered as an integral @@ -156,7 +174,9 @@ impl SystemFunction { | Self::Countbits | Self::Countones => Some((32, true)), Self::Onehot | Self::Onehot0 | Self::Isunknown | Self::Isunbounded => Some((1, false)), - Self::Random => Some((32, true)), + Self::Random | Self::DistUniform | Self::TestPlusargs | Self::ValuePlusargs => { + Some((32, true)) + } Self::Urandom | Self::UrandomRange | Self::Stime => Some((32, false)), Self::Time => Some((64, false)), Self::Signed @@ -586,7 +606,7 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ unsupported("$load_coverage_db", Task), // 20.14 Probabilistic distribution functions function(SystemFunction::Random, 0, Some(1)), - unsupported("$dist_uniform", Function), + function(SystemFunction::DistUniform, 3, Some(3)), unsupported("$dist_normal", Function), unsupported("$dist_exponential", Function), unsupported("$dist_poisson", Function), @@ -732,8 +752,8 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ unsupported("$writememb", Task), unsupported("$writememh", Task), // 21.6 Command line input - unsupported("$test$plusargs", Function), - unsupported("$value$plusargs", Function), + function(SystemFunction::TestPlusargs, 1, Some(1)), + function(SystemFunction::ValuePlusargs, 2, Some(2)), // 21.7 Value change dump (VCD) files unsupported("$dumpfile", Task), unsupported("$dumpvars", Task), diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 726d2354627..d4a759ab0b7 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -345,6 +345,13 @@ records the native-runner result; the case stays enabled on all Celox backends. ## SystemVerilog suite +The new `$dist_uniform` seed-width case is excluded for Verilator 5.052 and +Icarus 13.0. Verilator generates an invalid C++ reference binding for converted +seed arguments; Icarus rejects the `shortint` seed at startup. IEEE 1800-2023 +20.14.2 permits an integral seed variable. The unchanged case passes Celox's +backends; the source and observed failures are retained in +[`sv_dist_uniform_seed_width.json`](verification/repros/sv_dist_uniform_seed_width.json). + The SystemVerilog suite's exclusions are listed in [`verification/sv/limitations.json`](verification/sv/limitations.json), with the failures observed before them in [`verification/sv/limitations/`](verification/sv/limitations). A case is excluded for a tool only when the expected value follows IEEE 1800 and the tool either cannot run the design or disagrees with the standard; where the two tools disagree with each other, the entry says so. The `indexed_select::constant_part_select_indices_of_concatenations` case also diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index d6dbc7e3d4a..4a9c5568c8c 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/random_plusargs.vtest", + text: include_str!("random_plusargs.vtest"), + }, Group { file: "src/sv/cases/always_comb.vtest", text: include_str!("always_comb.vtest"), diff --git a/crates/celox-test-suite/src/sv/cases/random_plusargs.vtest b/crates/celox-test-suite/src/sv/cases/random_plusargs.vtest new file mode 100644 index 00000000000..b6eb9eebb3a --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/random_plusargs.vtest @@ -0,0 +1,114 @@ +(group random_plusargs (category sequential)) + +; IEEE 1800-2023 20.14.2, Annex N: explicit seeds, inclusive bounds, +; replay, full int interval, and degenerate bounds without advancing seed. +(case dist_uniform_bounds_seed_and_replay + (source "dist_uniform.sv" #" + module Top(input logic clk, output logic ok); + int seed, replay, a, b, full_seed, full_value; + always_ff @(posedge clk) begin + seed = 17; replay = 17; ok = 1; + for (int i = 0; i < 3; i++) begin + a = $dist_uniform(seed, -17, 23); + b = $dist_uniform(replay, -17, 23); + ok &= a >= -17 && a <= 23 && a == b && seed == replay; + end + seed = 17; + a = $dist_uniform(seed, 7, 7); + ok &= a == 7 && seed == 17; + a = $dist_uniform(seed, 9, -9); + ok &= a == 9 && seed == 17; + seed = 17; full_seed = 17; + a = $dist_uniform(seed, -2147483648, 2147483647); + full_value = $dist_uniform(full_seed, -2147483648, 2147483647); + ok &= a == full_value && seed == full_seed; + seed = 17; + a = $dist_uniform(seed, 2147483640, 2147483647); + ok &= a >= 2147483640 && a <= 2147483647; + end + endmodule + "#) + (top Top) + (tick clk) + (assert_eq ok 1)) + +; No plusargs are configured by this portable case. Missing values preserve +; their destinations, including calls used inside a larger expression. +(case plusargs_absent_preserves_destination + (source "plusargs_absent.sv" #" + module Top(output logic ok); + int target, found; + initial begin + target = 123; + found = $value$plusargs("CELOX_ABSENT_UNIQUE=%d", target); + ok = found == 0 && target == 123 && !$test$plusargs("CELOX_ABSENT_UNIQUE"); + end + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq ok 1)) + +; IEEE 1800-2023 5.9: string literals are unsigned packed bytes, including +; escaped characters, when an integral expression consumes them. +(case packed_string_literals_preserve_bytes_and_unsignedness + (source "packed_strings.sv" #" + module Top(output logic ok); + logic [23:0] bytes; + initial begin + bytes = {"A", "\101", "\x42"}; + ok = bytes == 24'h414142 && "\n\t" == 16'h0a09; + ok &= "\377" > 0 && ("\377" >> 7) == 1; + end + endmodule + "#) + (top Top) + (eval) + (assert_eq ok 1)) + +(case dist_uniform_converts_wide_and_signed_seeds_to_int_formals + (source "dist_uniform_seed_width.sv" #" + module Top(input logic clk, output logic ok); + longint wide; + shortint narrow; + int reference_seed, a, b, c; + always_ff @(posedge clk) begin + wide = 64'h12345678ffffffff; narrow = -1; reference_seed = -1; + a = $dist_uniform(wide, -100, 100); + b = $dist_uniform(narrow, -100, 100); + c = $dist_uniform(reference_seed, -100, 100); + ok = a == b && b == c && wide[31:0] == reference_seed; + ok &= narrow == reference_seed[15:0]; + end + endmodule + "#) + (top Top) + (tick clk) + (assert_eq ok 1)) + +; Fixed Annex N reference vectors corroborated with Icarus. Checking only +; bounds and replay would also accept an implementation that always returned +; the lower bound. +(case dist_uniform_reference_sequence + (source "dist_reference.sv" #" + module Top(output logic ok); + int seed, value; + initial begin + ok = 1; seed = 17; + value = $dist_uniform(seed, -17, 23); + ok &= value == -17 && seed == 1174174; + value = $dist_uniform(seed, -17, 23); + ok &= value == 19 && seed == -505354617; + value = $dist_uniform(seed, -17, 23); + ok &= value == -9 && seed == 861173020; + value = $dist_uniform(seed, -17, 23); + ok &= value == 17 && seed == -642763923; + seed = 0; + value = $dist_uniform(seed, 2147483640, 2147483647); + ok &= value == 2147483644 && seed == -1844104698; + end + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq ok 1)) diff --git a/crates/celox-test-suite/verification/repros/sv_dist_uniform_seed_width.json b/crates/celox-test-suite/verification/repros/sv_dist_uniform_seed_width.json new file mode 100644 index 00000000000..7cb65c9b004 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_dist_uniform_seed_width.json @@ -0,0 +1,24 @@ +{ + "standard": "IEEE 1800-2023 20.14.2 (Distribution functions)", + "case": "random_plusargs::dist_uniform_converts_wide_and_signed_seeds_to_int_formals", + "source": "\n module Top(input logic clk, output logic ok);\n longint wide;\n shortint narrow;\n int reference_seed, a, b, c;\n always_ff @(posedge clk) begin\n wide = 64'h12345678ffffffff; narrow = -1; reference_seed = -1;\n a = $dist_uniform(wide, -100, 100);\n b = $dist_uniform(narrow, -100, 100);\n c = $dist_uniform(reference_seed, -100, 100);\n ok = a == b && b == c && wide[31:0] == reference_seed;\n ok &= narrow == reference_seed[15:0];\n end\n endmodule\n ", + "expected": "ok = 1 after the rising edge; the integer seed formal truncates or sign-extends the input and copies the updated seed back to its declared width.", + "celox": "The unchanged shared case passes native, native-parallel, Cranelift, Cranelift-parallel and Wasmtime.", + "verilator": { + "version": "Verilator 5.052", + "phase": "compile", + "status": "compile_error", + "detail": [ + "Vdut___024root__0.cpp:146:43: error: cannot bind non-const lvalue reference of type \u2018IData&\u2019 {aka \u2018unsigned int&\u2019} to an rvalue of type \u2018IData\u2019 {aka \u2018unsigned int\u2019}", + "Vdut___024root__0.cpp:148:56: error: cannot bind non-const lvalue reference of type \u2018IData&\u2019 {aka \u2018unsigned int&\u2019} to an rvalue of type \u2018IData\u2019 {aka \u2018unsigned int\u2019}" + ], + "note": "Generated calls pass a cast or sign-extension temporary to VL_DIST_UNIFORM(IData&), which requires an lvalue." + }, + "icarus": { + "version": "Icarus Verilog 13.0", + "phase": "execute", + "status": "runtime_error", + "detail": "ERROR: /source_0.sv:9: $dist_uniform's seed must be an integer/time variable or a register." + }, + "review": "Clause 20.14.2 permits an integral seed variable and describes inout seed updating. longint and shortint are integral types. These are narrowly retained external-tool limitations for new executable coverage; no baseline summary or unrelated evidence is refreshed." +} diff --git a/crates/celox-test-suite/verification/sv/icarus.json b/crates/celox-test-suite/verification/sv/icarus.json index 3633efb3b55..1dedf339e68 100644 --- a/crates/celox-test-suite/verification/sv/icarus.json +++ b/crates/celox-test-suite/verification/sv/icarus.json @@ -9,6 +9,7 @@ "icarus/operators.json", "icarus/packed_structs.json", "icarus/procedural.json", + "icarus/random_plusargs.json", "icarus/review_regressions.json", "icarus/synthesizable.json", "icarus/system_functions.json", diff --git a/crates/celox-test-suite/verification/sv/icarus/random_plusargs.json b/crates/celox-test-suite/verification/sv/icarus/random_plusargs.json new file mode 100644 index 00000000000..1356f4716e6 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/icarus/random_plusargs.json @@ -0,0 +1,27 @@ +{ + "cases": [ + { + "category": "Sequential", + "detail": "Icarus rejects the shortint seed at startup with \"$dist_uniform's seed must be an integer/time variable or a register.\" IEEE 1800-2023 20.14.2 permits an integral seed variable; shortint is integral. Celox passes the unchanged width-conversion case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_runtime_limitation", + "evidence": [ + "verification/repros/sv_dist_uniform_seed_width.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_dist_uniform_seed_width", + "observed_version": "Icarus Verilog 13.0", + "phase": "execute", + "reason": "Icarus rejects the shortint seed at startup with \"$dist_uniform's seed must be an integer/time variable or a register.\" IEEE 1800-2023 20.14.2 permits an integral seed variable; shortint is integral. Celox passes the unchanged width-conversion case.", + "upstream": [] + }, + "name": "random_plusargs::dist_uniform_converts_wide_and_signed_seeds_to_int_formals", + "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 47af22ce678..40f8787d4b0 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1451,5 +1451,39 @@ "timing::timed_task_automatic_calls_keep_separate_storage" ] } + }, + { + "id": "sv_verilator_dist_uniform_seed_width", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Verilator 5.052", + "reason": "$dist_uniform with longint or shortint seed variables generates C++ that passes cast temporaries to VL_DIST_UNIFORM(IData&); compilation fails because a non-const lvalue reference cannot bind to an rvalue. IEEE 1800-2023 20.14.2 permits an integral seed variable. Celox passes the unchanged width-conversion case.", + "upstream": [], + "evidence": [ + "verification/repros/sv_dist_uniform_seed_width.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "random_plusargs::dist_uniform_converts_wide_and_signed_seeds_to_int_formals" + ] + } + }, + { + "id": "sv_icarus_dist_uniform_seed_width", + "category": "simulator_runtime_limitation", + "phase": "execute", + "observed_version": "Icarus Verilog 13.0", + "reason": "Icarus rejects the shortint seed at startup with \"$dist_uniform's seed must be an integer/time variable or a register.\" IEEE 1800-2023 20.14.2 permits an integral seed variable; shortint is integral. Celox passes the unchanged width-conversion case.", + "upstream": [], + "evidence": [ + "verification/repros/sv_dist_uniform_seed_width.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "random_plusargs::dist_uniform_converts_wide_and_signed_seeds_to_int_formals" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/verilator.json b/crates/celox-test-suite/verification/sv/verilator.json index ed19732a9a2..b7fcf38862e 100644 --- a/crates/celox-test-suite/verification/sv/verilator.json +++ b/crates/celox-test-suite/verification/sv/verilator.json @@ -9,6 +9,7 @@ "verilator/operators.json", "verilator/packed_structs.json", "verilator/procedural.json", + "verilator/random_plusargs.json", "verilator/review_regressions.json", "verilator/synthesizable.json", "verilator/system_functions.json", diff --git a/crates/celox-test-suite/verification/sv/verilator/random_plusargs.json b/crates/celox-test-suite/verification/sv/verilator/random_plusargs.json new file mode 100644 index 00000000000..9afb22cd6c5 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/verilator/random_plusargs.json @@ -0,0 +1,27 @@ +{ + "cases": [ + { + "category": "Sequential", + "detail": "$dist_uniform with longint or shortint seed variables generates C++ that passes cast temporaries to VL_DIST_UNIFORM(IData&); compilation fails because a non-const lvalue reference cannot bind to an rvalue. IEEE 1800-2023 20.14.2 permits an integral seed variable. Celox passes the unchanged width-conversion case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/repros/sv_dist_uniform_seed_width.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_dist_uniform_seed_width", + "observed_version": "Verilator 5.052", + "phase": "compile", + "reason": "$dist_uniform with longint or shortint seed variables generates C++ that passes cast temporaries to VL_DIST_UNIFORM(IData&); compilation fails because a non-const lvalue reference cannot bind to an rvalue. IEEE 1800-2023 20.14.2 permits an integral seed variable. Celox passes the unchanged width-conversion case.", + "upstream": [] + }, + "name": "random_plusargs::dist_uniform_converts_wide_and_signed_seeds_to_int_formals", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 568a1ca1c40..40c8163bbda 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -403,6 +403,7 @@ pub(crate) struct NativeRuntimeSchema { pub(crate) watches: Vec>, pub(crate) wait_sites: Vec>, pub(crate) nba_sites: Vec>, + pub(crate) host_request_sites: Vec>, pub(crate) active_commits: Vec, pub(crate) time_slots: Vec, } @@ -514,6 +515,7 @@ impl NativeProgramImage { watches: self.runtime_schema.watches.clone(), wait_sites: self.runtime_schema.wait_sites.clone(), nba_sites: self.runtime_schema.nba_sites.clone(), + host_request_sites: self.runtime_schema.host_request_sites.clone(), active_commits: self.runtime_schema.active_commits.clone(), time_slots: self.runtime_schema.time_slots.clone(), }, @@ -2407,6 +2409,7 @@ fn compile_program( watches: sir.runtime().runtime_schema.watches.clone(), wait_sites: sir.runtime().runtime_schema.wait_sites.clone(), nba_sites: sir.runtime().runtime_schema.nba_sites.clone(), + host_request_sites: sir.runtime().runtime_schema.host_request_sites.clone(), active_commits: sir.runtime().runtime_schema.active_commits.clone(), time_slots: sir.runtime().runtime_schema.time_slots.clone(), }, diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 5af6f77a7f9..dd60c803cf1 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 16; +const CONTAINER_VERSION: u16 = 17; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 220ac82b9e8..9ab79b28354 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -107,6 +107,23 @@ impl UnitExecutor for Simulator { self.runtime_finish() } + fn host_request( + &mut self, + request: &celox_design::HostRequestSite, + timestamp: u64, + ) -> Result<(), Halt> { + match request.kind { + celox_design::HostRequestKind::Plusargs => { + self.run_plusargs_request(request, timestamp) + } + _ => Err(celox_runtime::SimulatorErrorCode::Runtime { + message: format!("unsupported host request family {:?}", request.kind), + signals: Vec::new(), + } + .into()), + } + } + fn run_process(&mut self, index: usize) -> Result<(), Halt> { self.backend .run_process(index) diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index e13deea5aa7..a75588d58cd 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -119,6 +119,7 @@ mod host { /// State objects as state files name them, built on first use. pub(super) state_schema: std::sync::OnceLock>, pub(crate) diagnostics: crate::RuntimeDiagnostics, + pub(crate) plusargs: celox_runtime::plusargs::Plusargs, tick_timing_ticks: u64, tick_timing_eval_apply_ns: u64, tick_timing_eval_comb_ns: u64, @@ -735,6 +736,7 @@ mod host { checkpoint_fingerprint: std::sync::OnceLock::new(), state_schema: std::sync::OnceLock::new(), diagnostics: crate::RuntimeDiagnostics::default(), + plusargs: celox_runtime::plusargs::Plusargs::default(), tick_timing_ticks: 0, tick_timing_eval_apply_ns: 0, tick_timing_eval_comb_ns: 0, @@ -815,6 +817,58 @@ mod host { .restore_initial_state(initial_memory_values); } + pub(crate) fn run_plusargs_request( + &mut self, + site: &celox_design::HostRequestSite, + _timestamp: u64, + ) -> Result<(), celox_runtime::Halt> { + let query_signal = site.args[0].id; + let (query_value, query_mask) = self.backend.get_four_state(query_signal); + if query_mask != BigUint::default() { + return Err(celox_runtime::Halt::Error( + crate::RuntimeErrorCode::Runtime { + message: "plusargs query contains X or Z bits".into(), + signals: Vec::new(), + }, + )); + } + let query = query_value.to_bytes_be(); + let query = query + .iter() + .position(|byte| *byte != 0) + .map_or(&[][..], |start| &query[start..]); + let matched = if site.operation == 0 { + self.plusargs.test(query) + } else { + let target = site.results[1].id; + match self + .plusargs + .value(query, target.width) + .map_err(|message| { + celox_runtime::Halt::Error(crate::RuntimeErrorCode::Runtime { + message, + signals: Vec::new(), + }) + })? { + Some((value, mask)) => { + if self.backend.layout().four_state && target.is_4state { + self.backend.set_four_state(target, value, mask); + } else { + let width_mask = + (BigUint::from(1u8) << target.width) - BigUint::from(1u8); + self.backend + .set_wide(target, value & (&width_mask ^ (mask & &width_mask))); + } + true + } + None => false, + } + }; + self.backend + .set_wide(site.results[0].id, BigUint::from(u8::from(matched))); + Ok(()) + } + pub(crate) fn apply_testbench_memory_writes( &mut self, signal: SignalRef, diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index a76a0547bbf..586c325d7dd 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1525,6 +1525,8 @@ mod host { pub allow_always_ff_function_effects: bool, /// Where the C functions of DPI-C imports are found. pub dpi: crate::DpiSymbols, + /// Ordered command-line arguments for SystemVerilog plusargs queries. + pub plusargs: Vec, } /// A code-generated native program that has not been loaded into @@ -1564,6 +1566,7 @@ mod host { let mut sim = Simulator::with_backend_and_program(backend, program, warnings); sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); + sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); if let Some(path) = vcd_path { if sim.layout().unpacked_arrays.values().any(|array| { !array.element_width.is_multiple_of(8) @@ -1718,6 +1721,7 @@ mod host { tier_promotion: TierPromotion::Always, allow_always_ff_function_effects: false, dpi: crate::DpiSymbols::default(), + plusargs: Vec::new(), } } } @@ -1852,6 +1856,17 @@ mod host { self } + /// Set the ordered arguments queried by `$test$plusargs` and + /// `$value$plusargs`. A leading `+` is optional on each argument. + /// Queries currently require a timed procedural process, such as an + /// `initial` block executed by [`crate::Simulation`]. Value queries + /// support integral conversions and `%s` into packed integral targets; + /// real conversions and dynamic strings are unsupported. + pub fn plusargs(mut self, arguments: impl IntoIterator>) -> Self { + self.options.plusargs = arguments.into_iter().map(Into::into).collect(); + self + } + pub fn four_state(mut self, enable: bool) -> Self { self.options.four_state = enable; self @@ -2609,6 +2624,7 @@ mod host { Simulator::with_backend_and_program(backend, laid_out.into_runtime(), warnings); sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); + sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( @@ -2661,6 +2677,7 @@ mod host { Simulator::with_backend_and_program(backend, laid_out.into_runtime(), warnings); sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); + sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( @@ -2716,6 +2733,7 @@ mod host { Simulator::with_backend_and_program(backend, laid_out.into_runtime(), warnings); sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); + sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( @@ -2785,6 +2803,7 @@ mod host { Simulator::with_backend_and_program(backend, laid_out.into_runtime(), warnings); sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); + sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( @@ -2992,6 +3011,7 @@ mod host { Simulator::with_backend_and_program(backend, laid_out.into_runtime(), warnings); sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); + sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( @@ -3180,6 +3200,7 @@ mod host { sim.components .set_injected(self.injected_components.clone()); sim.diagnostics = self.options.diagnostics.clone(); + sim.plusargs = celox_runtime::plusargs::Plusargs(self.options.plusargs.clone()); sim.apply_initial_values(); sim.modify(|_| {}).map_err(|error| { SimulatorError::from(error).with_warnings(std::mem::take(&mut sim.warnings)) @@ -3377,6 +3398,7 @@ mod host { ); sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); + sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( diff --git a/crates/celox/src/testbench_compile.rs b/crates/celox/src/testbench_compile.rs index 0b35bd886ff..d24f9981047 100644 --- a/crates/celox/src/testbench_compile.rs +++ b/crates/celox/src/testbench_compile.rs @@ -10,7 +10,7 @@ pub(crate) fn project_observability( let (sites, read_variables) = celox_frontend_veryl::collect_testbench_observability(lookup, source)?; runtime_schema.runtime_event_sites.extend(sites); - runtime_schema.testbench_read_roots = read_variables; + runtime_schema.testbench_read_roots.extend(read_variables); Ok(()) } diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 515c2e3202f..35ef965f311 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -431,6 +431,21 @@ sv_backends! { } } + fn packed_string_literals_preserve_bytes_and_unsignedness(sim) { + @case "random_plusargs::packed_string_literals_preserve_bytes_and_unsignedness"; + } + fn dist_uniform_converts_wide_and_signed_seeds_to_int_formals(sim) { + @case "random_plusargs::dist_uniform_converts_wide_and_signed_seeds_to_int_formals"; + } + fn dist_uniform_reference_sequence(sim) { + @case "random_plusargs::dist_uniform_reference_sequence"; + } + fn dist_uniform_bounds_seed_and_replay(sim) { + @case "random_plusargs::dist_uniform_bounds_seed_and_replay"; + } + fn plusargs_absent_preserves_destination(sim) { + @case "random_plusargs::plusargs_absent_preserves_destination"; + } fn urandom_reseeds_and_shares_the_calling_process_stream(sim) { @case "system_functions::urandom_reseeds_and_shares_the_calling_process_stream"; } diff --git a/crates/celox/tests/shared_jit_cache.rs b/crates/celox/tests/shared_jit_cache.rs index 04445164739..0ea1dda00d7 100644 --- a/crates/celox/tests/shared_jit_cache.rs +++ b/crates/celox/tests/shared_jit_cache.rs @@ -655,6 +655,25 @@ fn native_program_image_rejects_corrupt_appended_payload() { ); } +/// Version 17 adds synchronous host requests to the runtime metadata. +#[test] +fn native_program_image_rejects_v16_before_decoding_host_request_schema() { + let sim = Simulator::builder(ADDER, "Top").build().unwrap(); + let mut encoded = sim + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let trailer_start = encoded.len() - NATIVE_IMAGE_TRAILER_SIZE; + encoded[trailer_start + NATIVE_IMAGE_VERSION_OFFSET + ..trailer_start + NATIVE_IMAGE_VERSION_OFFSET + 2] + .copy_from_slice(&16u16.to_le_bytes()); + assert!(matches!( + celox::NativeProgramImage::discover_appended(&encoded), + Err(NativeImageContainerError::UnsupportedVersion(16)) + )); +} + #[test] fn native_program_image_rejects_v3_before_decoding_changed_schema() { let sim = Simulator::builder(ADDER, "Top").build().unwrap(); diff --git a/crates/celox/tests/sv_plusargs.rs b/crates/celox/tests/sv_plusargs.rs new file mode 100644 index 00000000000..1ec753fbd58 --- /dev/null +++ b/crates/celox/tests/sv_plusargs.rs @@ -0,0 +1,289 @@ +#![cfg(feature = "systemverilog")] +use std::path::Path; + +const SOURCE: &str = r#" +module Top(output logic ok); + logic [127:0] query, text; + logic [7:0] value, missing, bad; + int found; + initial begin + query = "number=%d"; + value = 0; missing = 91; bad = 0; + found = $value$plusargs(query, value); + ok = found == 1 && value == 244; + ok &= $test$plusargs("HEL") && !$test$plusargs("LO"); + ok &= !$value$plusargs("absent=%d", missing) && missing == 91; + ok &= $value$plusargs("text=%s", text) && text == "hello"; + ok &= $value$plusargs("bad=%d", bad) && $isunknown(bad); + end +endmodule +"#; + +macro_rules! run_plusargs { + ($name:ident, $backend:ident) => { + #[test] + fn $name() { + let mut sim = + celox::Simulation::from_sv_sources(vec![(SOURCE, Path::new("plusargs.sv"))], "Top") + .four_state(true) + .plusargs([ + "+HELLO", + "+number=-12", + "+number=8", + "+text=hello", + "+bad=oops", + ]) + .$backend() + .unwrap(); + sim.run_until(0).unwrap(); + let ok = sim.signal("ok"); + assert_eq!(sim.get(ok), 1u8.into()); + } + }; +} +run_plusargs!(plusargs_interpreter, build_interpreter); +run_plusargs!(plusargs_cranelift, build); +#[cfg(target_arch = "x86_64")] +run_plusargs!(plusargs_native, build_native); +run_plusargs!(plusargs_wasm, build_wasm); + +#[test] +fn plusargs_two_state_coerces_unknown_and_high_impedance_digits_to_zero() { + let source = r#" + module Top(output logic ok); + logic [7:0] value; + initial begin + ok = $value$plusargs("value=%h", value) && value == 8'h10; + ok &= $value$plusargs("invalid=%d", value) && value == 0; + end + endmodule + "#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("plusargs_two_state.sv"))], + "Top", + ) + .plusargs(["+value=1z", "+invalid=nope"]) + .build_interpreter() + .unwrap(); + sim.run_until(0).unwrap(); + let ok = sim.signal("ok"); + assert_eq!(sim.get(ok), 1u8.into()); +} + +#[test] +fn plusargs_rejects_an_unknown_packed_query() { + let source = r#" + module Top(output logic ok); + logic [7:0] query; + initial begin query = 8'hxx; ok = $test$plusargs(query); end + endmodule + "#; + let mut sim = + celox::Simulation::from_sv_sources(vec![(source, Path::new("plusargs_unknown.sv"))], "Top") + .four_state(true) + .build_interpreter() + .unwrap(); + assert!( + sim.run_until(0) + .unwrap_err() + .to_string() + .contains("plusargs query contains X or Z") + ); +} + +macro_rules! negative_unknown_plusargs_backend { + ($name:ident, $backend:ident) => { + #[test] + fn $name() { + let source = r#" + module Top(output logic ok, + output logic [31:0] hex_value, + output logic [16:0] octal_value, + output logic [7:0] binary_value, known_value, positive_value); + initial begin + ok = $value$plusargs("negative_hex=%h", hex_value); + ok &= $value$plusargs("negative_octal=%o", octal_value); + ok &= $value$plusargs("negative_binary=%b", binary_value); + ok &= $value$plusargs("known=%h", known_value); + ok &= $value$plusargs("positive=%h", positive_value); + end + endmodule + "#; + for four_state in [true, false] { + let mut simulation = celox::Simulation::from_sv_sources( + vec![(source, Path::new("negative_unknown_plusargs.sv"))], + "Top", + ) + .four_state(four_state) + .plusargs([ + "+negative_hex=-1x", + "+negative_octal=-7z", + "+negative_binary=-1?", + "+known=-1f", + "+positive=1x", + ]) + .$backend() + .unwrap(); + simulation.run_until(0).unwrap(); + let ok = simulation.signal("ok"); + assert_eq!(simulation.get(ok), 1u8.into()); + for (name, width) in [("hex_value", 32), ("octal_value", 17), ("binary_value", 8)] { + let signal = simulation.signal(name); + let expected_mask = if four_state { + (celox::BigUint::from(1u8) << width) - celox::BigUint::from(1u8) + } else { + celox::BigUint::default() + }; + assert_eq!( + simulation.get_four_state(signal), + (celox::BigUint::default(), expected_mask), + "{name}, four_state={four_state}" + ); + } + let known = simulation.signal("known_value"); + assert_eq!(simulation.get(known), 225u32.into()); + let positive = simulation.signal("positive_value"); + assert_eq!( + simulation.get_four_state(positive), + ( + 16u32.into(), + if four_state { + 15u32.into() + } else { + 0u32.into() + } + ) + ); + } + } + }; +} +negative_unknown_plusargs_backend!(negative_unknown_plusargs_interpreter, build_interpreter); +negative_unknown_plusargs_backend!(negative_unknown_plusargs_cranelift, build); +#[cfg(target_arch = "x86_64")] +negative_unknown_plusargs_backend!(negative_unknown_plusargs_native, build_native); +negative_unknown_plusargs_backend!(negative_unknown_plusargs_wasm, build_wasm); + +macro_rules! decimal_and_separator_plusargs_backend { + ($name:ident, $backend:ident) => { + #[test] + fn $name() { + let source = r#" + module Top(output logic ok, + output logic [15:0] z_lower, z_upper, question, x_lower, x_upper, + signed_z, signed_x, leading, signed_leading, separators, interior); + initial begin + ok = $value$plusargs("zl=%d", z_lower); + ok &= $value$plusargs("zu=%D", z_upper); + ok &= $value$plusargs("question=%d", question); + ok &= $value$plusargs("xl=%d", x_lower); + ok &= $value$plusargs("xu=%d", x_upper); + ok &= $value$plusargs("sz=%d", signed_z); + ok &= $value$plusargs("sx=%d", signed_x); + ok &= $value$plusargs("leading=%d", leading); + ok &= $value$plusargs("signed_leading=%h", signed_leading); + ok &= $value$plusargs("separators=%d", separators); + ok &= $value$plusargs("interior=%d", interior); + end + endmodule + "#; + for four_state in [true, false] { + let mut simulation = celox::Simulation::from_sv_sources( + vec![(source, Path::new("decimal_and_separator_plusargs.sv"))], + "Top", + ) + .four_state(four_state) + .plusargs([ + "+zl=z", + "+zu=Z", + "+question=?", + "+xl=x", + "+xu=X", + "+sz=-z", + "+sx=+x", + "+leading=_12", + "+signed_leading=-_12", + "+separators=___", + "+interior=1_2_3_4_", + ]) + .$backend() + .unwrap(); + simulation.run_until(0).unwrap(); + let ok = simulation.signal("ok"); + assert_eq!(simulation.get(ok), 1u8.into()); + for name in [ + "z_lower", + "z_upper", + "question", + "x_lower", + "x_upper", + "signed_z", + "signed_x", + "leading", + "signed_leading", + "separators", + ] { + let signal = simulation.signal(name); + let z = matches!(name, "z_lower" | "z_upper" | "question"); + let value = if four_state && z { 65535u32 } else { 0 }; + let mask = if four_state { 65535u32 } else { 0 }; + assert_eq!( + simulation.get_four_state(signal), + (value.into(), mask.into()), + "{name}, four_state={four_state}" + ); + } + let interior = simulation.signal("interior"); + assert_eq!(simulation.get(interior), 1234u32.into()); + } + } + }; +} +decimal_and_separator_plusargs_backend!( + decimal_and_separator_plusargs_interpreter, + build_interpreter +); +decimal_and_separator_plusargs_backend!(decimal_and_separator_plusargs_cranelift, build); +#[cfg(target_arch = "x86_64")] +decimal_and_separator_plusargs_backend!(decimal_and_separator_plusargs_native, build_native); +decimal_and_separator_plusargs_backend!(decimal_and_separator_plusargs_wasm, build_wasm); + +// These sources exercise literal decoding through both packed assignments and +// the runtime plusargs query transport, including physical CRLF continuations. +macro_rules! packed_string_literals_backend { + ($name:ident, $backend:ident) => { + #[test] + fn $name() { + let source = concat!( + "module Top(output logic ok);\n", + " logic [39:0] text; int value;\n", + " initial begin\n", + " text = \"\"\"A\"B\nC\"\"\";\n", + " ok = text == 40'h4122420a43;\n", + " ok &= $value$plusargs(\"\"\"number=%d\"\"\", value) && value == 17;\n", + " ok &= $test$plusargs(\"ab\\\r\ncd\");\n", + " ok &= $test$plusargs(\"\"\"ab\\\r\ncd\"\"\");\n", + " ok &= $test$plusargs(\"ab\\\ncd\");\n", + " ok &= $test$plusargs(\"\"\"ab\\\ncd\"\"\");\n", + " text = \"ab\\\r\ncd\";\n", + " ok &= text == 40'h0061626364;\n", + " end\nendmodule\n", + ); + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("packed_string_literals.sv"))], + "Top", + ) + .plusargs(["+number=17", "+abcd"]) + .$backend() + .unwrap(); + sim.run_until(0).unwrap(); + let ok = sim.signal("ok"); + assert_eq!(sim.get(ok), 1u8.into()); + } + }; +} +packed_string_literals_backend!(packed_string_literals_interpreter, build_interpreter); +packed_string_literals_backend!(packed_string_literals_cranelift, build); +#[cfg(target_arch = "x86_64")] +packed_string_literals_backend!(packed_string_literals_native, build_native); +packed_string_literals_backend!(packed_string_literals_wasm, build_wasm); diff --git a/crates/celox/tests/sv_system_actuals.rs b/crates/celox/tests/sv_system_actuals.rs new file mode 100644 index 00000000000..004776cb6f3 --- /dev/null +++ b/crates/celox/tests/sv_system_actuals.rs @@ -0,0 +1,53 @@ +#![cfg(feature = "systemverilog")] +use std::path::Path; +const SOURCE: &str = r#" +module Top(output logic ok); + int calls; + int seeds[0:3]; + longint wide; + int value, found; + function automatic int index(); + calls = calls + 1; + return calls - 1; + endfunction + initial begin + seeds[0]=17; seeds[1]=91; seeds[2]=92; seeds[3]=93; calls=0; + value = $dist_uniform(seeds[index()], -17, 23); + ok = calls == 1 && value == -17 && seeds[0] == 1174174; + ok &= seeds[1] == 91 && seeds[2] == 92 && seeds[3] == 93; + wide = 64'h12345678abcdef01; + value = $dist_uniform(wide, 7, 7); + ok &= value == 7 && wide == 64'h12345678abcdef01; + value = $dist_uniform(wide, 9, -9); + ok &= value == 9 && wide == 64'h12345678abcdef01; + calls = 0; + found = $value$plusargs("number=%d", seeds[index()]); + ok &= calls == 1 && found == 1 && seeds[0] == 42 && seeds[1] == 91; + calls = 0; + found = $value$plusargs("missing=%d", seeds[index()]); + ok &= calls == 1 && found == 0 && seeds[0] == 42 && seeds[1] == 91; + end +endmodule +"#; +macro_rules! actuals_backend { + ($name:ident,$backend:ident) => { + #[test] + fn $name() { + let mut sim = celox::Simulation::from_sv_sources( + vec![(SOURCE, Path::new("system_actuals.sv"))], + "Top", + ) + .plusargs(["+number=42"]) + .$backend() + .unwrap(); + sim.run_until(0).unwrap(); + let ok = sim.signal("ok"); + assert_eq!(sim.get(ok), 1u8.into()); + } + }; +} +actuals_backend!(system_actuals_interpreter, build_interpreter); +actuals_backend!(system_actuals_cranelift, build); +#[cfg(target_arch = "x86_64")] +actuals_backend!(system_actuals_native, build_native); +actuals_backend!(system_actuals_wasm, build_wasm); diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 2aae06290e8..16879f41136 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -66,9 +66,10 @@ as waits written directly in a process. | Area | Supported | | --- | --- | | System functions | `$timeunit`, `$timeprecision`, `$bits`, `$size`, `$left`, `$right`, `$low`, `$high`, `$increment`, `$dimensions`, `$unpacked_dimensions`, `$clog2`, `$countbits`, `$countones`, `$onehot`, `$onehot0`, `$isunknown`, `$isunbounded` in expressions, constant expressions and as statements; `$signed`, `$unsigned` in expressions, constant expressions and as statements | -| Random numbers | `$urandom`, `$urandom_range` and `$random` in clocked processes, `always_comb`, `always @*`, `initial` blocks and their subroutines; an optional integral seed of `$urandom`, a seed variable of `$random`, and a separate stream per process | +| Random numbers | `$urandom`, `$urandom_range`, `$random` and `$dist_uniform` in clocked processes, `always_comb`, `always @*`, `initial` blocks and their subroutines; an optional integral seed of `$urandom`, a seed variable of `$random`, and a separate stream per process | | Simulation time | `$time` and `$stime` in clocked and combinational processes, continuous assignments, `initial` blocks and their subroutines | | System tasks | `$printtimescale`, `$display`, `$write` and their `b` / `o` / `h` forms, `$error`, `$warning`, `$info`, `$fatal`, `$finish`, `$stop`, `$exit` in `always` processes, subroutines and `initial` blocks; `$readmemh` / `$readmemb` there and in `initial` blocks; Veryl's `$assert` and `$assert_continue` | +| Command-line arguments | `$test$plusargs` and `$value$plusargs` in timed `initial` blocks and their subroutines | | State | two-state and four-state simulation | Every construct above is covered by tests that compare the result with a @@ -327,6 +328,18 @@ given by a pattern) are variables that hold their value from the start of the simulation; they cannot be used where an elaboration-time constant is required. +### Command-line arguments + +Use `Simulation::from_sv_sources` for plusargs queries in `initial` blocks +and their subroutines. Queries from combinational and edge-triggered processes +are currently unsupported. + +Supply ordered arguments with `.plusargs(["+COUNT=12", "+TRACE"])`. +`$test$plusargs` matches a prefix; `$value$plusargs` supports integer conversions +and `%s` into packed integral variables. The first matching argument wins, and +an unmatched value query preserves its destination. Real conversions and dynamic +strings are unsupported. + ## Time and precision {#time-and-precision} `$timeunit` and `$timeprecision` return a signed 32-bit exponent in seconds @@ -395,6 +408,10 @@ argument, each process continues its own seed, which starts at 0, so a design whose one process calls `$random` matches simulators that keep one seed for the whole design. +`$dist_uniform(seed, start, end)` uses the Annex N uniform distribution, updates +its integral seed variable and includes both bounds. Equal or reversed bounds +return `start` without advancing the seed. + ## Mixing Veryl and SystemVerilog {#mixed-language} `Simulator::from_mixed_sources`combines both source lists in one simulation. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index f6ef9baeff8..c4758baa9e3 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -61,9 +61,10 @@ package/`$unit` の static 引数を持つ時間待ち task と、static task | 領域 | サポート内容 | | --- | --- | | システム関数 | `$timeunit`、`$timeprecision`、`$bits`、`$size`、`$clog2`、`$countbits`、`$countones`、`$onehot`、`$onehot0`、`$isunknown`、`$isunbounded` は式・定数式の中と文として。`$signed`、`$unsigned` は式の中と文として | -| 乱数 | `$urandom`、`$urandom_range`、`$random` はクロックで起動するプロセス、`always_comb`、`always @*`、`initial` とそれらから呼ぶサブルーチンで使用可能。`$urandom` の任意の整数式によるシード、`$random` のシード変数、プロセスごとに独立した乱数列 | +| 乱数 | `$urandom`、`$urandom_range`、`$random`、`$dist_uniform` はクロックで起動するプロセス、`always_comb`、`always @*`、`initial` とそれらから呼ぶサブルーチンで使用可能。`$urandom` の任意の整数式によるシード、`$random` のシード変数、プロセスごとに独立した乱数列 | | シミュレーション時刻 | `$time` と `$stime` はクロックで起動するプロセス、組合せプロセス、継続代入、`initial` とそれらから呼ぶサブルーチンで使用可能 | | システムタスク | `always` 系のプロセスとサブルーチンの `$printtimescale`、`$display`、`$write` とその `b` / `o` / `h` 形、`$error`、`$warning`、`$info`、`$fatal`、`$finish`、`$stop`、`$exit`。`initial` ブロックでも使えます。`$readmemh` / `$readmemb` はそれらと `initial` ブロック。Veryl の `$assert` と `$assert_continue` | +| コマンドライン引数 | `$test$plusargs` と `$value$plusargs` は時間付き `initial` とそこから呼ぶサブルーチンで使用可能 | | 状態 | 2 値・4 値シミュレーション | 上記の各構文は、ソフトウェアモデルと結果を比較するテストで確認しています。Veryl が出力する @@ -233,6 +234,19 @@ Celox は program ブロックを持たず、それ以外からの呼び出し その呼び出し位置でコンパイル警告(`Simulator::warnings()`)を出します。定数関数内の呼び出しも同様です。 関数宣言内の呼び出しは、その関数を使わなくても警告します。定数評価が実行したかどうかには依存しません。 +### コマンドライン引数 + +`initial` とそのサブルーチンからの plusargs 検索には `Simulation::from_sv_sources` +を使います。組合せプロセスとエッジで起動するプロセスからの検索は未対応です。 + +引数は `.plusargs(["+COUNT=12", "+TRACE"])` で順序を保って渡します。 +`$test$plusargs` は前方一致で検索し、`$value$plusargs` は整数変換と packed 整数変数への +`%s` を扱います。最初に一致した引数を使い、未一致の場合は書き込み先の値を保持します。 +real 変換と動的 string は未対応です。 + +`$dist_uniform(seed, start, end)` は Annex N の一様分布を使い、整数の seed 変数を更新します。 +両端を含み、境界が同じ値か逆順なら seed を進めず `start` を返します。 + ## 時刻と精度 {#time-and-precision} `$timeunit` と `$timeprecision` は秒を基準とする指数を32ビットの符号付き整数で diff --git a/packages/celox/src/napi-helpers.ts b/packages/celox/src/napi-helpers.ts index 0dea70c46d1..dda3e4d67ce 100644 --- a/packages/celox/src/napi-helpers.ts +++ b/packages/celox/src/napi-helpers.ts @@ -106,6 +106,7 @@ export interface NapiOptimizeOptions { } export interface NapiOptions { + plusargs?: string[]; fourState?: boolean; vcd?: string; optLevel?: string; @@ -358,6 +359,10 @@ export function buildNapiOpts( const napiOpts: NapiOptions = {}; let hasOpt = false; + if (options.plusargs) { + napiOpts.plusargs = options.plusargs; + hasOpt = true; + } if (options.fourState) { napiOpts.fourState = options.fourState; hasOpt = true; diff --git a/packages/celox/src/plusargs-options.test.ts b/packages/celox/src/plusargs-options.test.ts new file mode 100644 index 00000000000..2ff263ba797 --- /dev/null +++ b/packages/celox/src/plusargs-options.test.ts @@ -0,0 +1,44 @@ +import { expect, test } from "vitest"; +import { + buildNapiOpts, + createSimulatorBridge, + loadNativeAddon, +} from "./napi-helpers.js"; +import { Simulator } from "./simulator.js"; + +test("plusargs preserve ordering and leading plus signs across the NAPI boundary", () => { + const plusargs = ["+flag", "+number=1", "+number=2"]; + expect(buildNapiOpts({ plusargs })).toEqual({ plusargs }); + expect(buildNapiOpts({ plusargs: [] })).toEqual({ plusargs: [] }); +}); + +test("the native addon accepts ordered plusargs options", () => { + const simulator = Simulator.create<{ a: bigint; readonly value: bigint }>( + { + __celox_module: true, + name: "Top", + sources: [ + { + path: "Top.veryl", + content: + "module Top (a: input logic<8>, value: output logic<8>) { assign value = a; }", + }, + ], + ports: { + a: { direction: "input", type: "logic", width: 8 }, + value: { direction: "output", type: "logic", width: 8 }, + }, + events: [], + }, + { + plusargs: ["+flag", "+number=1", "+number=2"], + __nativeCreate: createSimulatorBridge(loadNativeAddon()), + }, + ); + try { + simulator.dut.a = 42n; + expect(simulator.dut.value).toBe(42n); + } finally { + simulator.dispose(); + } +}); diff --git a/packages/celox/src/types.ts b/packages/celox/src/types.ts index 0440dc99017..e2e83c33628 100644 --- a/packages/celox/src/types.ts +++ b/packages/celox/src/types.ts @@ -320,6 +320,8 @@ export interface OptimizeOptions { export interface SimulatorOptions { /** Enable 4-state (X) simulation. Default: false. */ fourState?: boolean; + /** Ordered SystemVerilog plusargs; the leading + is optional. */ + plusargs?: string[]; /** Path to write VCD waveform output. */ vcd?: string; /**