diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 47ea5cbd3d4..b6bbf98b178 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -791,8 +791,8 @@ chapter-21/21.3--fgetc.sv 2state fail chapter-21/21.3--fgetc.sv 4state fail chapter-21/21.3--fgets.sv 2state fail chapter-21/21.3--fgets.sv 4state fail -chapter-21/21.3--file.sv 2state fail -chapter-21/21.3--file.sv 4state fail +chapter-21/21.3--file.sv 2state pass +chapter-21/21.3--file.sv 4state pass chapter-21/21.3--fmonitor.sv 2state fail chapter-21/21.3--fmonitor.sv 4state fail chapter-21/21.3--fpos.sv 2state fail diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index c2b97a6f147..553e510abbf 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -390,6 +390,8 @@ impl HostRequestSite { /// checkpoints capture a suspended process. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct ProcessSlots { + /// This kernel originated from an edge procedure and must execute in Simulation. + pub requires_timed_simulation: bool, pub resume: A, pub status: A, pub delay: A, @@ -398,6 +400,7 @@ pub struct ProcessSlots { impl ProcessSlots { pub fn map(self, mut map: impl FnMut(A) -> B) -> ProcessSlots { ProcessSlots { + requires_timed_simulation: self.requires_timed_simulation, resume: map(self.resume), status: map(self.status), delay: map(self.delay), diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index 9c7848e6839..90b0f717afb 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1706,6 +1706,7 @@ fn lower_processes( for (index, process) in artifact.processes().iter().enumerate() { let name = |slot: &str| vec![format!("$process[{index}]"), slot.to_string()]; let slots = ProcessSlots { + requires_timed_simulation: false, resume: lowering .hidden .declare(name("resume"), PROCESS_RESUME_WIDTH, false), diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index c0fa018adc5..1d20712d092 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -1188,7 +1188,9 @@ fn initial_driver_ranges( }; let mut drivers = Vec::new(); for (driver_id, process) in module.initial_processes().iter().enumerate() { - if condition_is_active(process.condition(), constants, parameter_types) { + if !process.is_scheduled_edge() + && condition_is_active(process.condition(), constants, parameter_types) + { body_driver_ranges(&mut drivers, process.body(), driver_id, &scan); } } @@ -2162,6 +2164,61 @@ fn lower_module( ) } +fn needs_host_request( + module: &sv::ir::Module, + body: &[sv::ir::Stmt], + visited: &mut HashSet, +) -> bool { + let mut found = false; + let mut calls = Vec::new(); + for stmt in body { + stmt.walk(&mut |stmt| { + if let sv::ir::Stmt::SystemTask { task, .. } = stmt { + found |= task.is_host_request(); + } + procedural::stmt_calls(stmt, &mut calls); + }); + } + if found { + return true; + } + while let Some((callee, args)) = calls.pop() { + match callee { + sv::ir::Callee::System(function) if function.is_host_request() => return true, + sv::ir::Callee::Subroutine(name) => { + let Some(subroutine) = module.subroutines().iter().find(|sub| sub.name == name) + else { + continue; + }; + // Different calls can select different defaults, even when the + // subroutine body has already been inspected. + let omitted: Vec<_> = (0..subroutine.params.len()) + .map(|position| matches!(args.get(position), None | Some(None))) + .collect(); + if visited.insert(format!("defaults:{name}:{omitted:?}")) { + procedural::default_calls(subroutine, &args, &mut calls); + } + if visited.insert(format!("body:{name}")) + && needs_host_request(module, &subroutine.body, visited) + { + return true; + } + } + _ => {} + } + } + false +} + +/// An edge signal's role and the clock of the declaring process. Keep these +/// together when host requests move a process out of the retained FF list. +struct FfEventRole { + signal: String, + kind: DomainKind, + clock: String, + clock_kind: DomainKind, +} + /// `ff_parts` additionally keeps every `always_ff` process as an /// independently evaluated part, for lane-partitioned builds. fn lower_module_with_overrides( @@ -2173,6 +2230,38 @@ fn lower_module_with_overrides( warnings: &mut Vec, force_signals: &[String], ) -> Result { + let mut ff_event_roles = Vec::new(); + for process in module.ff_processes() { + let clock = clock_event_from_ff_process(process) + .ok_or_else(|| sv::AnalyzerError::Unsupported("always_ff event control".into()))?; + for event in process.events() { + let kind = match (event.signal() == clock.signal(), event.edge()) { + (true, sv::ir::FfEdge::Pos) => DomainKind::ClockPosedge, + (true, sv::ir::FfEdge::Neg) => DomainKind::ClockNegedge, + (false, sv::ir::FfEdge::Pos) => DomainKind::ResetAsyncHigh, + (false, sv::ir::FfEdge::Neg) => DomainKind::ResetAsyncLow, + }; + ff_event_roles.push(FfEventRole { + signal: event.signal().to_string(), + kind, + clock: clock.signal().to_string(), + clock_kind: match clock.edge() { + sv::ir::FfEdge::Pos => DomainKind::ClockPosedge, + sv::ir::FfEdge::Neg => DomainKind::ClockNegedge, + }, + }); + } + } + let scheduled = module + .ff_processes() + .iter() + .any(|process| needs_host_request(module, process.body(), &mut HashSet::default())) + .then(|| { + module.clone().schedule_edge_processes(|process| { + needs_host_request(module, process.body(), &mut HashSet::default()) + }) + }); + let module = scheduled.as_ref().unwrap_or(module); let mut package_variables = Vec::new(); let name = module.name().to_string(); let mut next_id = SourceVarId::default(); @@ -2372,7 +2461,7 @@ fn lower_module_with_overrides( four_state, warnings, ); - let blocks = lower_ff_processes(module, &mut pm, ff_parts)?; + let blocks = lower_ff_processes(module, &mut pm, ff_parts, &ff_event_roles)?; ( blocks, std::mem::take(&mut pm.runtime_event_sites), @@ -2381,6 +2470,7 @@ fn lower_module_with_overrides( ) }; mark_ff_event_domains(&event_vars, &mut variables); + let (initial_values, processes, wait_sites, nba_sites, host_request_sites) = lower_initial_processes( module, @@ -3297,8 +3387,10 @@ fn lower_initial_processes( .max() .unwrap_or_default(), ); - let slots: Vec<_> = (0..runtime.len()) - .map(|index| { + let slots: Vec<_> = runtime + .iter() + .enumerate() + .map(|(index, (process, _))| { let mut declare = |slot: &str, width: usize| { let id = next_var_id(&mut next_id); variables.insert( @@ -3322,6 +3414,7 @@ fn lower_initial_processes( id }; ProcessSlots { + requires_timed_simulation: process.is_scheduled_edge(), resume: declare("resume", PROCESS_RESUME_WIDTH), status: declare("status", PROCESS_STATUS_WIDTH), delay: declare("delay", PROCESS_DELAY_WIDTH), @@ -3360,6 +3453,10 @@ fn lower_initial_processes( nba_sites.extend(kernel.nba_sites); host_request_sites.extend(kernel.host_request_sites.into_iter().map(|mut site| { site.process = index; + // Repeating ordinary always processes also execute only in + // the timed scheduler. Keep this site requirement separate + // from the converted-FF startup marker on ProcessSlots. + site.requires_timed_simulation = process.repeats(); site })); Ok(SymbolicProcess { @@ -5219,6 +5316,7 @@ fn lower_bit_vector_function_slt( | SystemFunction::ValuePlusargs | SystemFunction::Urandom | SystemFunction::UrandomRange + | SystemFunction::Fopen | SystemFunction::Timeunit | SystemFunction::Timeprecision | SystemFunction::Isunbounded @@ -6885,6 +6983,7 @@ fn lower_ff_processes( module: &sv::ir::Module, pm: &mut procedural::ProcModule<'_>, ff_parts: bool, + ff_event_roles: &[FfEventRole], ) -> Result { let mut parallel_ff_parts = HashMap::<_, Vec<_>>::default(); let mut eval_only_ff_blocks = HashMap::default(); @@ -6933,7 +7032,43 @@ fn lower_ff_processes( } process_events.push(events); } - let mut event_vars = FfEventVars::new(process_events.iter().flatten().copied()); + // Select primary roles globally before creating copies for retained FFs. + // Scheduled processes still contribute clock/reset roles and must satisfy + // the same one-bit event restriction, even though they use wait sites. + let global_events = ff_event_roles + .iter() + .map(|role| { + let id = pm + .id(&role.signal) + .ok_or_else(|| sv::AnalyzerError::Unsupported("always_ff event control".into()))?; + if pm + .variables + .get(&id) + .is_some_and(|variable| variable.width != 1) + { + return Err(sv::AnalyzerError::Unsupported( + "multi-bit always_ff event signal".into(), + )); + } + Ok((id, role.kind)) + }) + .collect::, sv::AnalyzerError>>()?; + let mut event_vars = FfEventVars::new(global_events.into_iter()); + // Reflection must retain associations from scheduled host processes too. + // Resolve sensed roles just as retained FF trigger sets do, including aliases + // when one authored signal has more than one clock/reset role. + for role in ff_event_roles { + if matches!( + role.kind, + DomainKind::ResetAsyncHigh | DomainKind::ResetAsyncLow + ) { + let reset = pm.id(&role.signal).expect("validated FF event signal"); + let clock = pm.id(&role.clock).expect("validated FF clock signal"); + let reset = event_vars.sensed(pm, reset, role.kind); + let clock = event_vars.sensed(pm, clock, role.clock_kind); + reset_clock_map.entry(reset).or_insert(clock); + } + } let random_seeds = process_random_seeds(module); for ((index, process), events) in module.ff_processes().iter().enumerate().zip(process_events) { diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 7fab801035a..94bdcb8efe0 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -9,6 +9,8 @@ //! Expressions are lowered through SLT, which keeps their width and //! four-state semantics identical to the combinational lowering. +mod file_io; + use super::procedural::*; use super::*; use celox_design::{CounterKind, NbaSite, WaitSite}; @@ -816,6 +818,11 @@ impl<'p, 'a> Ff<'p, 'a> { return Ok(expr.clone()); } Ok(match expr { + Expr::Call { + callee: sv::ir::Callee::System(sv::ir::SystemFunction::Fopen), + args, + .. + } => self.fopen(args)?, Expr::Call { callee: sv::ir::Callee::System(sv::ir::SystemFunction::Urandom), args, @@ -2401,6 +2408,15 @@ impl<'p, 'a> Ff<'p, 'a> { args: &[sv::ir::SystemTaskArg], site: Option<&sv::ir::SourceSpan>, ) -> Result { + if matches!( + task, + sv::ir::SystemTask::Fclose + | sv::ir::SystemTask::Fdisplay(_) + | sv::ir::SystemTask::Fwrite(_) + | sv::ir::SystemTask::Writemem(_) + ) { + return self.file_task(task, args); + } if let sv::ir::SystemTask::Readmem(format) = task { let mut addresses = [None, None]; for (slot, arg) in addresses.iter_mut().zip(args.iter().skip(2)) { diff --git a/crates/celox-frontend-sv/src/lowering/ff/file_io.rs b/crates/celox-frontend-sv/src/lowering/ff/file_io.rs new file mode 100644 index 00000000000..4b9dfed5aa4 --- /dev/null +++ b/crates/celox-frontend-sv/src/lowering/ff/file_io.rs @@ -0,0 +1,164 @@ +use super::*; +use celox_design::{HostRequestKind, HostRequestSite, HostRequestValue}; + +impl Ff<'_, '_> { + fn file_io_arg( + &mut self, + arg: &sv::ir::SystemTaskArg, + ) -> Result, sv::AnalyzerError> { + let (reg, signed, is_string) = match arg { + sv::ir::SystemTaskArg::Expr(expr) => { + (self.eval(expr, None)?, self.expr_signed(expr), false) + } + sv::ir::SystemTaskArg::Str(text) => { + let bytes = unescape(text).into_bytes(); + let reg = self.b.alloc_bit((bytes.len() * 8).max(8), false); + self.b.emit(SIRInstruction::Imm( + reg, + SIRValue::new(BigUint::from_bytes_be(&bytes)), + )); + (reg, false, true) + } + _ => return Err(unsupported("empty file I/O argument")), + }; + let width = self.b.register(®).width(); + let four_state = matches!(self.b.register(®), celox_sir::RegisterType::Logic { .. }); + let (id, _) = self.m.temp("file_arg", width, signed, four_state); + self.store(id, SIROffset::Static(0), width, reg); + Ok(HostRequestValue { + id, + width, + signed, + is_string, + }) + } + + fn file_io_request( + &mut self, + operation: u32, + args: Vec>, + results: Vec>, + strings: Vec, + ) -> Result<(), sv::AnalyzerError> { + if self.kernel.is_none() { + return Err(unsupported("file I/O outside a scheduled process")); + } + let site = self + .host_request_sites + .iter() + .filter(|site| site.kind == HostRequestKind::FileIo) + .count() as u32; + self.host_request_sites.push(HostRequestSite { + process: 0, + requires_timed_simulation: false, + kind: HostRequestKind::FileIo, + operation, + args, + results, + strings, + }); + self.with_kernel(|kernel| kernel.host_request(HostRequestKind::FileIo, site)) + .map_err(|error| unsupported(error.to_string())) + } + + pub(super) fn fopen( + &mut self, + args: &[Option], + ) -> Result { + let mut values = Vec::new(); + for arg in args { + let expr = arg + .as_ref() + .ok_or_else(|| unsupported("omitted $fopen argument"))?; + values.push(self.file_io_arg(&sv::ir::SystemTaskArg::Expr(expr.clone()))?); + } + let (id, name) = self.m.temp("fopen", 32, false, false); + self.file_io_request( + 0, + values, + vec![HostRequestValue { + id, + width: 32, + signed: false, + is_string: false, + }], + Vec::new(), + )?; + Ok(sv::ir::Expr::Ident(name)) + } + + pub(super) fn file_task( + &mut self, + task: sv::ir::SystemTask, + args: &[sv::ir::SystemTaskArg], + ) -> Result { + use sv::ir::SystemTask; + if self.kernel.is_none() { + return Err(unsupported(format!("`{task}` outside a scheduled process"))); + } + match task { + SystemTask::Fclose => { + let descriptor = self.file_io_arg(&args[0])?; + self.file_io_request(1, vec![descriptor], Vec::new(), Vec::new())?; + } + SystemTask::Fdisplay(radix) | SystemTask::Fwrite(radix) => { + let descriptor = self.file_io_arg(&args[0])?; + let kind = SystemTaskKind::Print(RuntimeEventKind::Write, radix.letter()); + let (template, args) = system_task_template(&kind, &args[1..]); + let mut values = vec![descriptor]; + for arg in &args { + values.push(self.file_io_arg(arg)?); + } + let operation = if matches!(task, SystemTask::Fdisplay(_)) { + 3 + } else { + 2 + }; + self.file_io_request( + operation, + values, + Vec::new(), + vec![template.unwrap_or_default()], + )?; + } + SystemTask::Writemem(format) => { + let filename = self.file_io_arg(&args[0])?; + let Some(sv::ir::SystemTaskArg::Expr(sv::ir::Expr::Ident(name))) = args.get(1) + else { + return Err(unsupported(format!( + "`{task}` requires a static unpacked array" + ))); + }; + let id = self + .m + .id(name) + .ok_or_else(|| unsupported(format!("`{task}` array `{name}`")))?; + let (left, right, width) = self.m.file_memory_shape(id)?; + let mut addresses = Vec::new(); + for arg in args.iter().skip(2) { + addresses.push(self.file_io_arg(arg)?); + } + // The memory is a reference operand: snapshot after evaluating + // the value arguments, including any address-expression effects. + let mut values = vec![filename]; + let array = self.file_io_arg(&sv::ir::SystemTaskArg::Expr(sv::ir::Expr::Ident( + name.clone(), + )))?; + values.push(array); + values.extend(addresses); + self.file_io_request( + if format == sv::ir::MemoryFormat::Binary { + 5 + } else { + 4 + }, + values, + Vec::new(), + vec![left.to_string(), right.to_string(), width.to_string()], + )?; + } + _ => unreachable!(), + } + Ok(true) + } +} diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 56ef6cc6520..bf02ad0e9f6 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -483,6 +483,23 @@ impl<'a> ProcModule<'a> { self.warnings.push((kind, site.cloned())); } + pub fn file_memory_shape( + &self, + id: SourceVarId, + ) -> Result<(i128, i128, usize), sv::AnalyzerError> { + let Some(bounds) = self.unpacked_bounds.get(&id) else { + return Err(unsupported("$writemem requires a static unpacked array")); + }; + let Some(width) = unpacked_element_width(self.var(id)) else { + return Err(unsupported("$writemem packed element type")); + }; + let (left, right) = match bounds.as_slice() { + [bound] => *bound, + _ => (0, (self.var(id).width / width) as i128 - 1), + }; + Ok((left, right, width)) + } + /// Register a runtime event site and return its local number. pub fn event_site(&mut self, site: RuntimeEventSite) -> u32 { self.runtime_event_sites.push(site); @@ -908,7 +925,13 @@ pub(super) fn system_task_kind(task: sv::ir::SystemTask) -> Option SystemTaskKind::Fatal, SystemTask::Assert => SystemTaskKind::Assertion(RuntimeEventKind::AssertFatal), SystemTask::AssertContinue => SystemTaskKind::Assertion(RuntimeEventKind::AssertContinue), - SystemTask::Readmem(_) | SystemTask::Printtimescale | SystemTask::Exit => return None, + SystemTask::Readmem(_) + | SystemTask::Writemem(_) + | SystemTask::Fclose + | SystemTask::Fdisplay(_) + | SystemTask::Fwrite(_) + | SystemTask::Printtimescale + | SystemTask::Exit => return None, }) } diff --git a/crates/celox-runtime/src/file_io.rs b/crates/celox-runtime/src/file_io.rs new file mode 100644 index 00000000000..ef8c307cd70 --- /dev/null +++ b/crates/celox-runtime/src/file_io.rs @@ -0,0 +1,340 @@ +//! SystemVerilog file descriptors and multichannel descriptors (IEEE 1800-2023 21.3). +//! +//! A manager belongs to one simulation. No process-global descriptor table is used. +use std::collections::BTreeMap; +use std::fs::{File, OpenOptions}; +use std::io::{self, Write}; +use std::path::Path; + +use celox_testbench::{DisplayFormatArg, FieldSpec, format_sv_display_arg}; + +const FD_FLAG: u32 = 0x8000_0000; + +#[derive(Debug)] +pub struct FileIo { + channels: BTreeMap, + descriptors: BTreeMap, + stdin_open: bool, + stdout_open: bool, + stderr_open: bool, +} + +impl Default for FileIo { + fn default() -> Self { + Self { + channels: BTreeMap::new(), + descriptors: BTreeMap::new(), + stdin_open: true, + stdout_open: true, + stderr_open: true, + } + } +} + +impl FileIo { + /// Open an MCD when mode is absent, otherwise an FD. Failure returns zero, + /// as specified by 21.3.1. Closed channel numbers are reused. + pub fn open(&mut self, path: impl AsRef, mode: Option<&str>) -> u32 { + let mut options = OpenOptions::new(); + match mode.unwrap_or("w") { + "r" | "rb" => { + options.read(true); + } + "w" | "wb" => { + options.write(true).create(true).truncate(true); + } + "a" | "ab" => { + options.append(true).create(true); + } + "r+" | "r+b" | "rb+" => { + options.read(true).write(true); + } + "w+" | "w+b" | "wb+" => { + options.read(true).write(true).create(true).truncate(true); + } + "a+" | "a+b" | "ab+" => { + options.read(true).append(true).create(true); + } + _ => return 0, + } + let (table, key) = if mode.is_some() { + let Some(key) = (3..FD_FLAG).find(|key| !self.descriptors.contains_key(key)) else { + return 0; + }; + (&mut self.descriptors, key) + } else { + let Some(key) = (1..31) + .map(|bit| 1u32 << bit) + .find(|key| !self.channels.contains_key(key)) + else { + return 0; + }; + (&mut self.channels, key) + }; + let Ok(file) = options.open(path) else { + return 0; + }; + table.insert(key, file); + if mode.is_some() { key | FD_FLAG } else { key } + } + + /// Close every selected MCD channel, or one FD. Closing a standard stream + /// changes this simulation only; it never closes the host process stream. + pub fn close(&mut self, descriptor: u32) -> io::Result<()> { + if descriptor == 0 { + return Err(invalid_descriptor()); + } + if descriptor & FD_FLAG != 0 { + let key = descriptor & !FD_FLAG; + let standard_open = match key { + 0 => Some(&mut self.stdin_open), + 1 => Some(&mut self.stdout_open), + 2 => Some(&mut self.stderr_open), + _ => None, + }; + if let Some(open) = standard_open { + return if std::mem::replace(open, false) { + Ok(()) + } else { + Err(invalid_descriptor()) + }; + } + let Some(mut file) = self.descriptors.remove(&key) else { + return Err(invalid_descriptor()); + }; + return file.flush(); + } + let mut error = None; + if descriptor & 1 != 0 && !std::mem::replace(&mut self.stdout_open, false) { + error = Some(invalid_descriptor()); + } + for bit in 1..31 { + let key = 1u32 << bit; + if descriptor & key != 0 { + match self.channels.remove(&key) { + Some(mut file) => { + if let Err(err) = file.flush() { + error = Some(err); + } + } + None => error = Some(invalid_descriptor()), + } + } + } + error.map_or(Ok(()), Err) + } + + /// Write bytes in call order. MCD bit zero and FD stdout are returned to the + /// caller so they can use the simulator's ordinary output/event interface. + /// Stderr is written directly. All selected valid channels are attempted. + pub fn write(&mut self, descriptor: u32, bytes: &[u8]) -> io::Result { + if descriptor == 0 { + return Err(invalid_descriptor()); + } + if descriptor & FD_FLAG != 0 { + return match descriptor & !FD_FLAG { + 0 => Err(io::Error::new( + io::ErrorKind::PermissionDenied, + "STDIN is not writable", + )), + 1 if self.stdout_open => Ok(true), + 2 if self.stderr_open => { + io::stderr().lock().write_all(bytes)?; + Ok(false) + } + key => { + self.descriptors + .get_mut(&key) + .ok_or_else(invalid_descriptor)? + .write_all(bytes)?; + Ok(false) + } + }; + } + let mut error = None; + for bit in 1..31 { + let key = 1u32 << bit; + if descriptor & key != 0 { + let result = self + .channels + .get_mut(&key) + .ok_or_else(invalid_descriptor) + .and_then(|file| file.write_all(bytes)); + if let Err(err) = result { + error = Some(err); + } + } + } + if descriptor & 1 != 0 && !self.stdout_open { + error = Some(invalid_descriptor()); + } + error.map_or(Ok(descriptor & 1 != 0), Err) + } + + /// Write all selected channels and report stdout selection independently of + /// other channel errors, so callers can publish stdout before returning an error. + pub fn write_with_stdout(&mut self, descriptor: u32, bytes: &[u8]) -> (bool, io::Result<()>) { + let stdout = self.stdout_open + && (descriptor == FD_FLAG | 1 || descriptor & FD_FLAG == 0 && descriptor & 1 != 0); + let result = self.write(descriptor, bytes).map(|_| ()); + (stdout, result) + } + + /// Write a static unpacked memory snapshot, without address specifiers + /// (21.5.3). The caller supplies elements in the requested address order. + pub fn write_memory<'a>( + path: impl AsRef, + binary: bool, + words: impl IntoIterator>, + ) -> io::Result<()> { + let mut file = File::create(path)?; + for word in words { + file.write_all(&format_sv_display_arg( + &word, + if binary { 'b' } else { 'h' }, + FieldSpec::default(), + ))?; + file.write_all(b"\n")?; + } + file.flush() + } +} + +fn invalid_descriptor() -> io::Error { + io::Error::new( + io::ErrorKind::InvalidInput, + "invalid or closed SystemVerilog file descriptor", + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use num_bigint::BigUint; + + #[test] + fn descriptors_modes_channels_and_reuse() { + let dir = tempfile::tempdir().unwrap(); + let a = dir.path().join("a"); + let b = dir.path().join("b"); + let mut files = FileIo::default(); + let m1 = files.open(&a, None); + let m2 = files.open(&b, None); + assert_eq!((m1, m2), (2, 4)); + assert!(files.write(m1 | m2 | 1, b"both\n").unwrap()); + files.close(m1 | m2).unwrap(); + assert_eq!(std::fs::read(&a).unwrap(), b"both\n"); + assert_eq!(std::fs::read(&b).unwrap(), b"both\n"); + assert!(files.write(m1, b"closed").is_err()); + assert_eq!(files.open(&b, None), m1); + let fd = files.open(&a, Some("ab+")); + assert_eq!(fd, 0x8000_0003); + files.write(fd, b"appended").unwrap(); + files.close(fd).unwrap(); + assert_eq!(std::fs::read(&a).unwrap(), b"both\nappended"); + assert_eq!(files.open(dir.path().join("missing"), Some("r")), 0); + assert_eq!(files.open(&a, Some("bad")), 0); + assert!(files.write(0x8000_0000, b"stdin").is_err()); + } + + #[test] + fn stdout_selection_survives_mcd_errors_but_respects_closed_stdout() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("valid-channel.txt"); + let mut files = FileIo::default(); + let channel = files.open(&path, None); + assert_ne!(channel, 0); + let (stdout, result) = files.write_with_stdout(channel | 1 | (1 << 30), b"attempted"); + assert!(stdout); + assert!(result.is_err()); + files.close(channel).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), b"attempted"); + files.close(1).unwrap(); + let (stdout, result) = files.write_with_stdout(1 | channel, b"closed"); + assert!(!stdout); + assert!(result.is_err()); + let (stdout, result) = files.write_with_stdout(FD_FLAG | 1, b"closed"); + assert!(!stdout); + assert!(result.is_err()); + } + + #[test] + fn standard_file_descriptors_cannot_be_closed_twice() { + for descriptor in [FD_FLAG, FD_FLAG | 1, FD_FLAG | 2] { + let mut files = FileIo::default(); + files.close(descriptor).unwrap(); + assert_eq!( + files.close(descriptor).unwrap_err().kind(), + io::ErrorKind::InvalidInput + ); + assert!(files.write(descriptor, b"").is_err()); + } + } + + #[test] + fn stdout_fd_and_mcd_share_close_state_without_skipping_other_channels() { + for (first, repeated) in [(1, FD_FLAG | 1), (FD_FLAG | 1, 1)] { + let mut files = FileIo::default(); + files.close(first).unwrap(); + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("fanout.txt"); + let channel = files.open(&path, None); + files.write(channel, b"kept").unwrap(); + assert!(files.close(repeated).is_err()); + // An invalid stdout component must not skip closing valid MCDs. + assert!(files.close(channel | 1).is_err()); + assert!(files.write(channel, b"closed").is_err()); + assert_eq!(std::fs::read(path).unwrap(), b"kept"); + // Closing stdout must not affect the other standard stream. + files.close(FD_FLAG | 2).unwrap(); + } + } + + #[test] + fn zero_mcd_is_invalid_even_for_an_empty_write() { + let mut files = FileIo::default(); + assert_eq!( + files.write(0, b"").unwrap_err().kind(), + io::ErrorKind::InvalidInput + ); + let (stdout, result) = files.write_with_stdout(0, b"lost"); + assert!(!stdout); + assert_eq!(result.unwrap_err().kind(), io::ErrorKind::InvalidInput); + } + + #[test] + fn zero_mcd_cannot_be_closed() { + let mut files = FileIo::default(); + assert_eq!( + files.close(0).unwrap_err().kind(), + io::ErrorKind::InvalidInput + ); + // An invalid close must not close stdout or an unrelated valid file. + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("still-open.txt"); + let channel = files.open(&path, None); + assert!(files.close(0).is_err()); + assert!(files.write(channel | 1, b"open").unwrap()); + files.close(channel).unwrap(); + assert_eq!(std::fs::read(path).unwrap(), b"open"); + } + + #[test] + fn memories_preserve_four_state_and_overwrite() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("memory"); + let value = BigUint::from(0xa5u8); + let mask = BigUint::from(0xf0u8); + let word = || DisplayFormatArg { + value: &value, + mask: Some(&mask), + width: 8, + signed: false, + is_string: false, + }; + FileIo::write_memory(&path, true, [word()]).unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "xzxz0101\n"); + FileIo::write_memory(&path, false, [word()]).unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), "X5\n"); + } +} diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index 8e4ab97d86b..a2ebf2d979c 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -5,6 +5,7 @@ mod derived_tick; mod edge; mod error; mod event_buffer; +pub mod file_io; pub mod parallel; pub mod plusargs; mod reflection; diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index ce323f5dec7..a1fb1adb6e8 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -124,6 +124,7 @@ impl ResolvedSchedule { .processes .iter() .map(|process| ProcessRefs { + starts_with_event_wait: process.slots.requires_timed_simulation, status: resolve(&process.slots.status), delay: resolve(&process.slots.delay), wait_sites: process diff --git a/crates/celox-runtime/src/simulation/process.rs b/crates/celox-runtime/src/simulation/process.rs index d117a3a0d94..d79872e4096 100644 --- a/crates/celox-runtime/src/simulation/process.rs +++ b/crates/celox-runtime/src/simulation/process.rs @@ -13,7 +13,7 @@ impl SimulationState { /// whether it resumes at once (a queued nonblocking assignment or a /// yield), in which case the caller checks the state before running it /// again: the return separates the writes before and after it. - fn run_process( + pub(super) fn run_process( &mut self, executor: &mut E, current_time: u64, diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index c916423cd7e..3b4a5bec296 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -147,7 +147,22 @@ impl SimulationState { } else { Vec::new() }; - let ready = self.take_ready_processes(current_time); + let mut ready = self.take_ready_processes(current_time); + if current_time == 0 { + // Converted always_ff kernels have a leading event control rather + // than an initial body. Arm it before scheduled inputs change, as + // for ordinary FF domains; leave initial processes in their usual + // process phase and declaration order (IEEE 1800-2023 4.5, 9.2.2.4). + let mut returns = 0; + for &process in &ready { + if self.model.processes[process].starts_with_event_wait + && self.run_process(executor, current_time, process, &mut returns)? + { + return Err(SimulatorErrorCode::InternalError.into()); + } + } + ready.retain(|&process| !self.model.processes[process].starts_with_event_wait); + } self.step_round(executor, current_time, events_to_process, ready, true)?; self.end_time(executor, current_time) } diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs index 15f0fa38bc0..cdb307b4cfe 100644 --- a/crates/celox-runtime/src/timing.rs +++ b/crates/celox-runtime/src/timing.rs @@ -130,6 +130,9 @@ pub struct NbaSiteRefs { /// Control slots and sites of one process kernel. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ProcessRefs { + /// A converted edge procedure starts by registering its event control + /// before scheduled time-zero inputs are applied. + pub starts_with_event_wait: bool, pub status: SignalRef, pub delay: SignalRef, /// Wait sites by local index: their terms. @@ -143,6 +146,7 @@ impl ProcessRefs { /// A process without wait or nonblocking sites. pub fn new(status: SignalRef, delay: SignalRef) -> Self { Self { + starts_with_event_wait: false, status, delay, wait_sites: 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 2599b2e1306..65c00b72f49 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -725,6 +725,7 @@ pub(in crate::ast) fn bind_value( | SystemFunction::DistUniform | SystemFunction::TestPlusargs | SystemFunction::ValuePlusargs + | SystemFunction::Fopen | SystemFunction::UrandomRange ) { for (position, arg) in operands.iter().enumerate() { diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index a3c3e4ad7e9..6ebeb00ea0a 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -73,6 +73,51 @@ pub struct Module { } impl Module { + /// Represent selected edge procedures as scheduled processes. A host + /// request must finish synchronously before the following statement runs. + pub fn schedule_edge_processes(mut self, mut select: impl FnMut(&FfProcess) -> bool) -> Self { + let mut retained = Vec::new(); + for process in std::mem::take(&mut self.ff_processes) { + if !select(&process) { + retained.push(process); + continue; + } + let mut body = vec![Stmt::WaitEvent( + process + .events + .iter() + .map(|event| EventItem { + edge: match event.edge { + FfEdge::Pos => EventEdge::Pos, + FfEdge::Neg => EventEdge::Neg, + }, + expr: Expr::Ident(event.signal.clone()), + }) + .collect(), + )]; + body.extend(process.body); + self.initial_processes.push(InitialProcess { + creation_order: process.creation_order, + scheduled_edge: true, + condition: None, + body: vec![Stmt::Loop { + kind: LoopKind::Forever, + init: Vec::new(), + condition: None, + step: Vec::new(), + body, + }], + initializer: false, + synthetic: false, + repeats: true, + }); + } + self.ff_processes = retained; + self.initial_processes + .sort_by_key(|process| (!process.initializer, process.creation_order)); + self + } + #[allow(clippy::too_many_arguments)] pub(crate) fn new( id: ModuleId, @@ -921,6 +966,7 @@ impl FfProcess { #[derive(Debug, Clone, PartialEq, Eq)] pub struct InitialProcess { creation_order: usize, + scheduled_edge: bool, condition: Option, body: Vec, initializer: bool, @@ -930,6 +976,11 @@ pub struct InitialProcess { } impl InitialProcess { + /// This process represents an edge procedure requiring host services. + pub fn is_scheduled_edge(&self) -> bool { + self.scheduled_edge + } + /// Position among elaborated module items, shared across process kinds. pub fn creation_order(&self) -> usize { self.creation_order @@ -938,6 +989,7 @@ impl InitialProcess { pub(crate) fn new(condition: Option, body: Vec, initializer: bool) -> Self { Self { creation_order: 0, + scheduled_edge: false, condition, body, initializer, diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index a8048bc1555..064b943d65e 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -66,6 +66,8 @@ pub enum SystemFunction { Urandom, /// `$urandom_range` (18.13.2). UrandomRange, + /// `$fopen` (21.3.1). + Fopen, } /// An array query function that selects one bound of a dimension (20.7). @@ -79,6 +81,11 @@ pub enum ArrayQuery { } impl SystemFunction { + /// Calls that return through the timed scheduler's host boundary. + pub fn is_host_request(self) -> bool { + matches!(self, Self::Fopen | Self::TestPlusargs | Self::ValuePlusargs) + } + /// The name, with its leading `$`. pub const fn name(self) -> &'static str { match self { @@ -110,6 +117,7 @@ impl SystemFunction { Self::ValuePlusargs => "$value$plusargs", Self::Urandom => "$urandom", Self::UrandomRange => "$urandom_range", + Self::Fopen => "$fopen", } } @@ -144,6 +152,7 @@ impl SystemFunction { | Self::TestPlusargs | Self::ValuePlusargs | Self::Urandom + | Self::Fopen | Self::UrandomRange ) } @@ -177,7 +186,7 @@ impl SystemFunction { Self::Random | Self::DistUniform | Self::TestPlusargs | Self::ValuePlusargs => { Some((32, true)) } - Self::Urandom | Self::UrandomRange | Self::Stime => Some((32, false)), + Self::Urandom | Self::UrandomRange | Self::Stime | Self::Fopen => Some((32, false)), Self::Time => Some((64, false)), Self::Signed | Self::Unsigned @@ -220,6 +229,12 @@ pub enum SystemTask { Write(Radix), /// `$readmemb` and `$readmemh` (21.4). Readmem(MemoryFormat), + /// File output tasks (21.3). + Fclose, + Fdisplay(Radix), + Fwrite(Radix), + /// Memory snapshot output (21.5). + Writemem(MemoryFormat), /// Veryl's immediate assertions, emitted into SystemVerilog as calls of /// `$assert(condition, message...)`, which ends the simulation when the /// condition fails, and `$assert_continue`, which reports and continues. @@ -274,6 +289,14 @@ impl Radix { } impl SystemTask { + /// Tasks executed synchronously by the timed simulation host. + pub fn is_host_request(self) -> bool { + matches!( + self, + Self::Fclose | Self::Fdisplay(_) | Self::Fwrite(_) | Self::Writemem(_) + ) + } + /// The name, with its leading `$`. pub const fn name(self) -> &'static str { use Radix::{Binary, Decimal, Hexadecimal, Octal}; @@ -294,6 +317,17 @@ impl SystemTask { Self::Write(Binary) => "$writeb", Self::Write(Octal) => "$writeo", Self::Write(Hexadecimal) => "$writeh", + Self::Fclose => "$fclose", + Self::Fdisplay(Decimal) => "$fdisplay", + Self::Fdisplay(Binary) => "$fdisplayb", + Self::Fdisplay(Octal) => "$fdisplayo", + Self::Fdisplay(Hexadecimal) => "$fdisplayh", + Self::Fwrite(Decimal) => "$fwrite", + Self::Fwrite(Binary) => "$fwriteb", + Self::Fwrite(Octal) => "$fwriteo", + Self::Fwrite(Hexadecimal) => "$fwriteh", + Self::Writemem(MemoryFormat::Binary) => "$writememb", + Self::Writemem(MemoryFormat::Hexadecimal) => "$writememh", Self::Readmem(MemoryFormat::Binary) => "$readmemb", Self::Readmem(MemoryFormat::Hexadecimal) => "$readmemh", Self::Assert => "$assert", @@ -699,16 +733,56 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ unsupported("$monitoron", Task), unsupported("$monitoroff", Task), // 21.3 File input/output system tasks and system functions - unsupported("$fopen", Function), - unsupported("$fclose", Task), - unsupported("$fdisplay", Task), - unsupported("$fdisplayb", Task), - unsupported("$fdisplayo", Task), - unsupported("$fdisplayh", Task), - unsupported("$fwrite", Task), - unsupported("$fwriteb", Task), - unsupported("$fwriteo", Task), - unsupported("$fwriteh", Task), + function(SystemFunction::Fopen, 1, Some(2)), + task(SystemTask::Fclose, ProceduralAndInitial, 1, Some(1)), + task( + SystemTask::Fdisplay(Radix::Decimal), + ProceduralAndInitial, + 1, + None, + ), + task( + SystemTask::Fdisplay(Radix::Binary), + ProceduralAndInitial, + 1, + None, + ), + task( + SystemTask::Fdisplay(Radix::Octal), + ProceduralAndInitial, + 1, + None, + ), + task( + SystemTask::Fdisplay(Radix::Hexadecimal), + ProceduralAndInitial, + 1, + None, + ), + task( + SystemTask::Fwrite(Radix::Decimal), + ProceduralAndInitial, + 1, + None, + ), + task( + SystemTask::Fwrite(Radix::Binary), + ProceduralAndInitial, + 1, + None, + ), + task( + SystemTask::Fwrite(Radix::Octal), + ProceduralAndInitial, + 1, + None, + ), + task( + SystemTask::Fwrite(Radix::Hexadecimal), + ProceduralAndInitial, + 1, + None, + ), unsupported("$fstrobe", Task), unsupported("$fstrobeb", Task), unsupported("$fstrobeo", Task), @@ -749,8 +823,18 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ Some(4), ), // 21.5 Writing memory array data to a file - unsupported("$writememb", Task), - unsupported("$writememh", Task), + task( + SystemTask::Writemem(MemoryFormat::Binary), + ProceduralAndInitial, + 2, + Some(4), + ), + task( + SystemTask::Writemem(MemoryFormat::Hexadecimal), + ProceduralAndInitial, + 2, + Some(4), + ), // 21.6 Command line input function(SystemFunction::TestPlusargs, 1, Some(1)), function(SystemFunction::ValuePlusargs, 2, Some(2)), diff --git a/crates/celox-test-suite/src/sv/cases/file_io.vtest b/crates/celox-test-suite/src/sv/cases/file_io.vtest new file mode 100644 index 00000000000..62edd219a13 --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/file_io.vtest @@ -0,0 +1,37 @@ +(group file_io (category sequential)) + +(case stdout_preserves_format_and_call_order + (four_state) + (source "stdout_file_io.sv" #" + module Top(output bit done); + int fd; + initial begin + $display("before"); + $fwrite(32'h8000_0001, "fd:%0d,", 12); + $fdisplayh(1, "mcd:%h", 8'bxz010101); + $display("after"); + done = 1; + end + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq done 1) + (expect_output "before\nfd:12,mcd:X5\nafter\n")) + +(case edge_procedures_execute_requests_in_statement_order + (source "edge_file_io.sv" #" + module Top(output int count); + bit clk; + initial begin clk = 0; #1 clk = 1; #1 clk = 0; #1 clk = 1; end + always_ff @(posedge clk) begin + $fwrite(1, "ff:%0d,", count); + count = count + 1; + end + always @(negedge clk) $fdisplay(1, "neg:%0d", count); + endmodule + "#) + (top Top) + (run_until 3) + (assert_eq count 2) + (expect_output "ff:0,neg:1\nff:1,")) diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index 4a9c5568c8c..76c42a71d52 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -59,6 +59,10 @@ pub(super) const GROUPS: &[Group] = &[ file: "src/sv/cases/synthesizable.vtest", text: include_str!("synthesizable.vtest"), }, + Group { + file: "src/sv/cases/file_io.vtest", + text: include_str!("file_io.vtest"), + }, Group { file: "src/sv/cases/system_functions.vtest", text: include_str!("system_functions.vtest"), diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index dd60c803cf1..9b88368edf0 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 = 17; +const CONTAINER_VERSION: u16 = 18; 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 9ab79b28354..a1dabb941c0 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -107,6 +107,13 @@ impl UnitExecutor for Simulator { self.runtime_finish() } + fn run_process(&mut self, index: usize) -> Result<(), Halt> { + self.backend + .run_process(index) + .map_err(|e| self.decorate_runtime_error(e))?; + self.runtime_finish() + } + fn host_request( &mut self, request: &celox_design::HostRequestSite, @@ -116,20 +123,12 @@ impl UnitExecutor for Simulator { 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(), + celox_design::HostRequestKind::FileIo => self.run_file_io_request(request, timestamp), + celox_design::HostRequestKind::Vcd => { + Err(celox_runtime::SimulatorErrorCode::InternalError.into()) } - .into()), } } - - fn run_process(&mut self, index: usize) -> Result<(), Halt> { - self.backend - .run_process(index) - .map_err(|e| self.decorate_runtime_error(e))?; - self.runtime_finish() - } } impl TickExecutor for Simulator { diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index a75588d58cd..a7636bdcf46 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -32,6 +32,7 @@ pub use state_file::{StateError, StateMismatch, StateSchema}; #[cfg(feature = "host-runtime")] mod host { + mod file_io; use super::*; use std::sync::Arc; use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; @@ -102,6 +103,8 @@ mod host { pub(crate) backend: B, /// Dynamic testbench strings, keyed by the bound variable location. pub(crate) testbench_strings: celox_testbench::TestbenchStrings, + file_io: celox_runtime::file_io::FileIo, + pending_host_events: Arc>, pub(crate) program: RuntimeProgram, /// The program's scheduling facts. pub(crate) schedule: celox_design::schedule::ScheduleModel, @@ -188,6 +191,7 @@ mod host { buffer: Arc, layout: MemoryLayout, sites: Vec, + pending_host_events: Arc>, read_seq: u64, shared_read_seq: Arc, active: Arc, @@ -199,6 +203,8 @@ mod host { } pub fn drain_with_context(&mut self, ctx: RuntimeFormatContext<'_>) -> Vec { + let mut pending = self.pending_host_events.lock().unwrap(); + self.read_seq = self.shared_read_seq.load(Ordering::Acquire); let events = drain_raw_runtime_events_from_buffer( &self.buffer, &self.layout, @@ -206,6 +212,9 @@ mod host { &mut self.read_seq, ); self.shared_read_seq.store(self.read_seq, Ordering::Release); + pending.extend(events, self.layout.runtime_event_capacity); + let events = pending.drain(); + drop(pending); events .into_iter() .filter_map(|raw| render_raw_runtime_event(raw, &self.sites, ctx)) @@ -215,7 +224,6 @@ mod host { impl Drop for RuntimeEventDrain { fn drop(&mut self) { - self.shared_read_seq.store(self.read_seq, Ordering::Release); self.active.store(false, Ordering::Release); } } @@ -237,6 +245,10 @@ mod host { #[derive(Clone)] enum RawRuntimeEvent { + Host { + site: Box, + args: Vec, + }, Event { site_id: usize, args: Vec, @@ -246,6 +258,50 @@ mod host { }, } + /// A bounded continuation of the backend ring. Records remain unformatted + /// until the eventual consumer supplies its scope/time context. + #[derive(Default)] + struct PendingRuntimeEvents { + events: std::collections::VecDeque, + missed: u64, + } + + impl PendingRuntimeEvents { + fn extend(&mut self, events: impl IntoIterator, capacity: usize) { + for event in events { + self.push(event, capacity); + } + } + + fn push(&mut self, event: RawRuntimeEvent, capacity: usize) { + if let RawRuntimeEvent::Missed { count } = event { + // Ring overwrite means every older pending record also lies + // outside the latest `capacity` records of the combined stream. + self.missed += count + self.events.len() as u64; + self.events.clear(); + } else if capacity == 0 { + self.missed += 1; + } else { + if self.events.len() == capacity { + self.events.pop_front(); + self.missed += 1; + } + self.events.push_back(event); + } + } + + fn drain(&mut self) -> Vec { + let mut events = Vec::with_capacity(self.events.len() + usize::from(self.missed > 0)); + if self.missed > 0 { + events.push(RawRuntimeEvent::Missed { + count: std::mem::take(&mut self.missed), + }); + } + events.extend(self.events.drain(..)); + events + } + } + fn runtime_event_words_to_biguint(words: &[u64], width: usize) -> BigUint { let mut value = BigUint::from(0u8); for (idx, word) in words.iter().enumerate() { @@ -469,17 +525,25 @@ mod host { match raw { RawRuntimeEvent::Missed { count } => Some(RuntimeEvent::Missed { count }), RawRuntimeEvent::Event { site_id, args } => { - let site = sites.get(site_id)?; - let message = render_runtime_event_message(site, &args, ctx); - Some(match site.kind { - RuntimeEventKind::Display => RuntimeEvent::Display { message }, - RuntimeEventKind::Write => RuntimeEvent::Write { message }, - RuntimeEventKind::AssertContinue => RuntimeEvent::AssertContinue { message }, - RuntimeEventKind::AssertFatal => RuntimeEvent::AssertFatal { message }, - RuntimeEventKind::Finish => RuntimeEvent::Finish, - RuntimeEventKind::Stop => RuntimeEvent::Stop, - }) + Some(render_runtime_event(sites.get(site_id)?, &args, ctx)) } + RawRuntimeEvent::Host { site, args } => Some(render_runtime_event(&site, &args, ctx)), + } + } + + fn render_runtime_event( + site: &RuntimeEventSite, + args: &[RuntimeEventArgValue], + ctx: RuntimeFormatContext<'_>, + ) -> RuntimeEvent { + let message = render_runtime_event_message(site, args, ctx); + match site.kind { + RuntimeEventKind::Display => RuntimeEvent::Display { message }, + RuntimeEventKind::Write => RuntimeEvent::Write { message }, + RuntimeEventKind::AssertContinue => RuntimeEvent::AssertContinue { message }, + RuntimeEventKind::AssertFatal => RuntimeEvent::AssertFatal { message }, + RuntimeEventKind::Finish => RuntimeEvent::Finish, + RuntimeEventKind::Stop => RuntimeEvent::Stop, } } @@ -727,6 +791,8 @@ mod host { dirty: false, warnings, testbench_strings: Default::default(), + file_io: Default::default(), + pending_host_events: Default::default(), components: Default::default(), component_simulation: None, runtime_event_read_seq: Arc::new(AtomicU64::new(0)), @@ -1003,11 +1069,15 @@ mod host { &mut self, ctx: RuntimeFormatContext<'_>, ) -> Vec { - if self.runtime_event_read_seq.load(Ordering::Acquire) == self.runtime_event_write_seq() - { - return Vec::new(); - } - self.collect_backend_runtime_events() + let queue = Arc::clone(&self.pending_host_events); + let mut pending = queue.lock().unwrap(); + pending.extend( + self.collect_backend_runtime_events(), + self.backend.layout().runtime_event_capacity, + ); + let events = pending.drain(); + drop(pending); + events .into_iter() .filter_map(|raw| { render_raw_runtime_event( @@ -1019,6 +1089,24 @@ mod host { .collect() } + fn queue_host_runtime_event( + &mut self, + site: RuntimeEventSite, + args: Vec, + ) { + let queue = Arc::clone(&self.pending_host_events); + let mut pending = queue.lock().unwrap(); + let capacity = self.backend.layout().runtime_event_capacity; + pending.extend(self.collect_backend_runtime_events(), capacity); + pending.push( + RawRuntimeEvent::Host { + site: Box::new(site), + args, + }, + capacity, + ); + } + fn collect_backend_runtime_events(&mut self) -> Vec { let layout = self.backend.layout(); let mut read_seq = self.runtime_event_read_seq.load(Ordering::Acquire); @@ -1129,6 +1217,7 @@ mod host { buffer, layout: self.backend.layout().clone(), sites: self.program.runtime_schema.runtime_event_sites.clone(), + pending_host_events: Arc::clone(&self.pending_host_events), read_seq: self.runtime_event_read_seq.load(Ordering::Acquire), shared_read_seq: Arc::clone(&self.runtime_event_read_seq), active: Arc::clone(&self.runtime_event_drain_active), diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 586c325d7dd..a545b696018 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1550,6 +1550,28 @@ mod host { injected_components: crate::InjectedComponents, } + fn validate_untimed_host_requests( + program: &crate::ir::RuntimeProgram, + ) -> Result<(), SimulatorError> { + if program + .runtime_schema + .processes + .iter() + .any(|slots| slots.requires_timed_simulation) + || program + .runtime_schema + .host_request_sites + .iter() + .any(|site| site.requires_timed_simulation) + { + return Err(SimulatorError::from(crate::RuntimeErrorCode::Runtime { + message: "edge procedures using system file I/O or plusargs require Simulation; Simulator does not execute scheduled process kernels".into(), + signals: Vec::new(), + })); + } + Ok(()) + } + #[cfg(any( target_arch = "x86_64", feature = "arm64-codegen", @@ -1563,11 +1585,12 @@ mod host { vcd_path: Option, injected_components: crate::InjectedComponents, ) -> Result, SimulatorError> { + validate_untimed_host_requests(&program)?; 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 vcd_path.is_some() { if sim.layout().unpacked_arrays.values().any(|array| { !array.element_width.is_multiple_of(8) || array.element_stride != array.element_width / 8 @@ -1577,6 +1600,8 @@ mod host { )) .with_warnings(std::mem::take(&mut sim.warnings))); } + } + if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); let vcd_writer = crate::VcdWriter::new_with_time_precision( path, @@ -2594,6 +2619,7 @@ mod host { let (laid_out, mut warnings, options, vcd_path, injected_components) = self .into_laid_out_program(crate::backend::memory_layout::MemoryLayoutMode::Packed)?; + validate_untimed_host_requests(laid_out.runtime())?; if let Some(s) = phase_start { tracing::debug!( @@ -2662,6 +2688,7 @@ mod host { let (laid_out, mut warnings, options, vcd_path, injected_components) = self .into_laid_out_program(crate::backend::memory_layout::MemoryLayoutMode::Packed)?; + validate_untimed_host_requests(laid_out.runtime())?; if let Some(s) = phase_start { tracing::debug!( @@ -2719,6 +2746,7 @@ mod host { vcd_recording, ))? }; + validate_untimed_host_requests(laid_out.runtime())?; if let Some(s) = phase_start { tracing::debug!( @@ -2788,6 +2816,7 @@ mod host { vcd_recording, ))? }; + validate_untimed_host_requests(laid_out.runtime())?; if let Some(s) = phase_start { tracing::debug!( @@ -2837,6 +2866,7 @@ mod host { .into_laid_out_program( crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, )?; + validate_untimed_host_requests(laid_out.runtime())?; if let Some(start) = sir_start { tracing::debug!( "[phase-timing] into_laid_out_program total: {:?}", @@ -2880,6 +2910,7 @@ mod host { crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, Some(&mut trace), )?; + validate_untimed_host_requests(laid_out.runtime())?; if let Some(start) = sir_start { tracing::debug!( "[phase-timing] into_laid_out_program total: {:?}", @@ -3005,6 +3036,7 @@ mod host { ) -> Result, SimulatorError> { let (laid_out, mut warnings, options, vcd_path, injected_components) = self .into_laid_out_program(crate::backend::memory_layout::MemoryLayoutMode::Packed)?; + validate_untimed_host_requests(laid_out.runtime())?; let backend = crate::backend::wasm_runtime::WasmBackend::new(&laid_out, &options) .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; let mut sim = @@ -3157,6 +3189,7 @@ mod host { self.options.diagnostic_policy.apply(&mut warnings)?; let mut laid_out = program.into_laid_out_with_mode(self.options.four_state, layout_mode); + validate_untimed_host_requests(laid_out.runtime())?; if self.vcd_path.is_some() { laid_out.enable_vcd_tracking(); } @@ -3443,7 +3476,6 @@ mod host { ) { use crate::HashSet; let mut externally_live = HashSet::default(); - // Native testbench expressions bypass SIR and read simulator memory // directly. Their inputs are therefore external DSE roots just like // signals named with `live_signal()`. diff --git a/crates/celox/src/simulator/checkpoint.rs b/crates/celox/src/simulator/checkpoint.rs index b9c681a0a46..203cca1ce9e 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -123,6 +123,12 @@ pub enum CheckpointError { "checkpoints are not supported for designs with external components, whose state Celox cannot capture" )] ExternalComponents, + /// Source-driven files have host state that is + /// not represented in the saved HDL memory image. + #[error( + "checkpoints and state files are not supported for designs with SystemVerilog file I/O" + )] + ExternalSystemTasks, #[error("the checkpoint was taken from a different design")] DesignMismatch, /// A time-based simulation dumps VCD output at every step, so it cannot @@ -147,6 +153,7 @@ impl Simulator { /// Inputs written since the last evaluation are part of the saved state; /// combinational logic is settled again after a restore. pub fn checkpoint(&self) -> Result { + self.check_host_checkpoint_support()?; if !self.components.is_empty() { return Err(CheckpointError::ExternalComponents); } @@ -187,6 +194,7 @@ impl Simulator { /// Check every precondition of [`Self::restore`] without changing state. pub(crate) fn validate_restore(&self, checkpoint: &Checkpoint) -> Result<(), CheckpointError> { + self.check_host_checkpoint_support()?; if !self.components.is_empty() { return Err(CheckpointError::ExternalComponents); } @@ -196,6 +204,19 @@ impl Simulator { Ok(()) } + pub(crate) fn check_host_checkpoint_support(&self) -> Result<(), CheckpointError> { + if self + .program + .runtime_schema + .host_request_sites + .iter() + .any(|site| matches!(site.kind, celox_design::HostRequestKind::FileIo)) + { + return Err(CheckpointError::ExternalSystemTasks); + } + Ok(()) + } + /// Identity of the checkpointable state layout. Simulators with equal /// fingerprints can exchange checkpoints. pub fn state_fingerprint(&self) -> u64 { diff --git a/crates/celox/src/simulator/host/file_io.rs b/crates/celox/src/simulator/host/file_io.rs new file mode 100644 index 00000000000..8cc9f7fc278 --- /dev/null +++ b/crates/celox/src/simulator/host/file_io.rs @@ -0,0 +1,427 @@ +use super::*; +use celox_design::HostRequestSite; +use celox_runtime::{Halt, SimulatorErrorCode}; + +impl Simulator { + pub(crate) fn run_file_io_request( + &mut self, + site: &HostRequestSite, + timestamp: u64, + ) -> Result<(), Halt> { + let error = |message: String| { + Halt::Error(SimulatorErrorCode::Runtime { + message, + signals: Vec::new(), + }) + }; + let values: Vec<_> = site + .args + .iter() + .map(|arg| { + if arg.id.is_4state { + self.backend.get_four_state(arg.id) + } else { + (self.backend.get(arg.id), BigUint::default()) + } + }) + .collect(); + let number = |index: usize| -> Result { + let (value, mask) = &values[index]; + if *mask != BigUint::default() { + return Err(error("file I/O descriptor/address contains X or Z".into())); + } + Ok(value.to_u32_digits().first().copied().unwrap_or(0)) + }; + let string = |index: usize| -> Result { + let (value, mask) = &values[index]; + if *mask != BigUint::default() { + return Err(error("file I/O string contains X or Z".into())); + } + let bytes = value.to_bytes_be(); + let bytes = bytes + .into_iter() + .skip_while(|byte| *byte == 0) + .collect::>(); + String::from_utf8(bytes).map_err(|_| error("file I/O path or mode is not UTF-8".into())) + }; + match site.operation { + 0 => { + let path = string(0)?; + let mode = if site.args.len() > 1 { + Some(string(1)?) + } else { + None + }; + let descriptor = self.file_io.open(path, mode.as_deref()); + self.backend.set(site.results[0].id, descriptor); + } + 1 => self + .file_io + .close(number(0)?) + .map_err(|err| error(format!("$fclose: {err}")))?, + 2 | 3 => { + let args: Vec<_> = site + .args + .iter() + .zip(&values) + .skip(1) + .map(|(arg, (value, mask))| RuntimeEventArgValue { + values: value.to_u64_digits(), + masks: mask.to_u64_digits(), + width: arg.width, + signed: arg.signed, + is_string: arg.is_string, + }) + .collect(); + let process = &self.program.runtime_schema.processes[site.process]; + let scope = self + .program + .design + .instance(process.status.instance_id) + .map(|instance| { + let top = self + .program + .design + .root_instance() + .map(|root| root.module_name.as_str()) + .unwrap_or(""); + std::iter::once(top) + .chain(instance.display_path.iter().map(String::as_str)) + .filter(|part| !part.is_empty()) + .collect::>() + .join(".") + }); + let format = RuntimeEventSite { + kind: RuntimeEventKind::Write, + template: site.strings.first().cloned(), + sizing: DisplaySizing::Ieee, + scope, + arg_widths: Vec::new(), + arg_signed: Vec::new(), + arg_is_string: Vec::new(), + }; + let mut message = render_runtime_event_message( + &format, + &args, + RuntimeFormatContext { + tb_time: Some(timestamp), + ..Default::default() + }, + ); + if site.operation == 3 { + message.push(b'\n'); + } + let (stdout, write_result) = self.file_io.write_with_stdout(number(0)?, &message); + if stdout { + let mut format = format; + format.kind = if site.operation == 3 { + RuntimeEventKind::Display + } else { + RuntimeEventKind::Write + }; + self.queue_host_runtime_event(format, args); + } + write_result.map_err(|err| error(format!("file output: {err}")))?; + } + 4 | 5 => { + let path = string(0)?; + let left: i128 = site.strings[0] + .parse() + .map_err(|_| error("invalid memory metadata".into()))?; + let right: i128 = site.strings[1] + .parse() + .map_err(|_| error("invalid memory metadata".into()))?; + let width: usize = site.strings[2] + .parse() + .map_err(|_| error("invalid memory metadata".into()))?; + let address = |index: usize| -> Result { + let (value, mask) = &values[index]; + if *mask != BigUint::default() { + return Err(error("$writemem address contains X or Z".into())); + } + let mut value = num_bigint::BigInt::from(value.clone()); + let arg = &site.args[index]; + if arg.signed && arg.width > 0 && value.bit(arg.width as u64 - 1) { + value -= num_bigint::BigInt::from(1u8) << arg.width; + } + value + .try_into() + .map_err(|_| error("$writemem address exceeds supported range".into())) + }; + let start = if site.args.len() > 2 { + address(2)? + } else { + left.min(right) + }; + let finish = if site.args.len() > 3 { + address(3)? + } else { + left.max(right) + }; + if start < left.min(right) + || start > left.max(right) + || finish < left.min(right) + || finish > left.max(right) + { + return Err(error("$writemem address outside array bounds".into())); + } + let mask = (BigUint::from(1u8) << width) - BigUint::from(1u8); + let words: Vec<_> = (0..=start.abs_diff(finish)) + .map(|offset| { + let index = if start <= finish { + start + offset as i128 + } else { + start - offset as i128 + }; + let shift = index.abs_diff(left) as usize * width; + ( + (&values[1].0 >> shift) & &mask, + (&values[1].1 >> shift) & &mask, + ) + }) + .collect(); + celox_runtime::file_io::FileIo::write_memory( + path, + site.operation == 5, + words.iter().map(|(value, mask)| DisplayFormatArg { + value, + mask: Some(mask), + width, + signed: false, + is_string: false, + }), + ) + .map_err(|err| error(format!("$writemem: {err}")))?; + } + _ => return Err(error("unknown file I/O request".into())), + } + Ok(()) + } +} + +#[cfg(all( + test, + feature = "systemverilog", + any(target_arch = "x86_64", target_arch = "aarch64") +))] +mod tests { + #[test] + fn detached_drain_includes_host_messages_in_order_without_replaying_records() { + let source = r#"module Top; + initial begin + $display("before"); + $fwrite(1, "host"); + $display("after"); + end + endmodule"#; + let mut simulation = crate::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("drain.sv"))], + "Top", + ) + .build_native() + .unwrap(); + let mut drain = simulation.simulator.runtime_event_drain().unwrap(); + simulation.step().unwrap(); + assert_eq!( + drain.drain(), + vec![ + crate::RuntimeEvent::Display { + message: b"before".to_vec() + }, + crate::RuntimeEvent::Write { + message: b"host".to_vec() + }, + crate::RuntimeEvent::Display { + message: b"after".to_vec() + }, + ] + ); + drop(drain); + assert!(simulation.drain_runtime_events().is_empty()); + } +} + +#[cfg(all(test, feature = "systemverilog"))] +mod queue_tests { + use super::*; + use std::path::Path; + + const CONTEXT_SOURCE: &str = r#"module Top; + timeunit 1ps; timeprecision 1ps; + initial begin + #7; + $display("%m:%0t", $time); + $fwrite(1, "host:%0t,", $time); + $display("%m:%0t", $time); + end + endmodule"#; + + fn late_context(build: impl Fn(&str) -> crate::Simulation) { + for veryl_context in [false, true] { + for owned in [false, true] { + let mut simulation = build(CONTEXT_SOURCE); + if veryl_context { + // The legacy formatter consumes time from the drain context; + // IEEE %t instead consumes the captured expression operand. + for site in &mut simulation + .simulator + .program + .runtime_schema + .runtime_event_sites + { + site.sizing = DisplaySizing::Veryl; + site.template = Some("%m:%t".into()); + } + } + let mut drain = if owned { + simulation.simulator.runtime_event_drain() + } else { + None + }; + if owned && drain.is_none() { + continue; + } + simulation.run_until(7).unwrap(); + let context = RuntimeFormatContext { + scope: Some("caller"), + tb_time: Some(999), + }; + let events = if let Some(drain) = &mut drain { + drain.drain_with_context(context) + } else { + simulation + .simulator + .drain_runtime_events_with_context(context) + }; + let ordinary = if veryl_context { + b"caller:999".to_vec() + } else { + b"caller:7".to_vec() + }; + assert_eq!( + events, + vec![ + RuntimeEvent::Display { + message: ordinary.clone() + }, + RuntimeEvent::Write { + message: b"host:7,".to_vec() + }, + RuntimeEvent::Display { message: ordinary }, + ] + ); + drop(drain); + assert!(simulation.drain_runtime_events().is_empty()); + } + } + } + + fn bounded_output(build: impl Fn(&str) -> crate::Simulation) { + let capacity = celox_state_layout::RUNTIME_EVENT_CAPACITY; + for owned in [false, true] { + for scenario in 0..3 { + let count = if scenario == 1 { + capacity / 2 + 7 + } else { + capacity + 7 + }; + let body = match scenario { + 0 => "$fwrite(1, \"%0d,\", i);", + 1 => "$display(\"%0d\", i * 2); $fwrite(1, \"%0d,\", i * 2 + 1);", + _ => "$display(\"%0d\", i);", + }; + let prefix = if scenario == 2 { + "$fwrite(1, \"old\");" + } else { + "" + }; + let source = format!( + "module Top; initial begin {prefix} for (int i = 0; i < {count}; i++) begin {body} end end endmodule" + ); + let mut simulation = build(&source); + let mut drain = if owned { + simulation.simulator.runtime_event_drain() + } else { + None + }; + if owned && drain.is_none() { + continue; + } + simulation.run_until(0).unwrap(); + let events = if let Some(drain) = &mut drain { + drain.drain() + } else { + simulation.drain_runtime_events() + }; + let total = if scenario == 1 { + count * 2 + } else { + count + usize::from(scenario == 2) + }; + let missed = total - capacity; + assert_eq!( + events.first(), + Some(&RuntimeEvent::Missed { + count: missed as u64 + }) + ); + assert_eq!(events.len(), capacity + 1); + for (offset, event) in events.iter().skip(1).enumerate() { + let index = missed + offset; + let expected = match scenario { + 0 => RuntimeEvent::Write { + message: format!("{index},").into_bytes(), + }, + 1 if index % 2 == 1 => RuntimeEvent::Write { + message: format!("{index},").into_bytes(), + }, + 1 => RuntimeEvent::Display { + message: index.to_string().into_bytes(), + }, + _ => RuntimeEvent::Display { + message: (index - 1).to_string().into_bytes(), + }, + }; + assert_eq!(event, &expected, "scenario {scenario}, record {index}"); + } + drop(drain); + assert!(simulation.drain_runtime_events().is_empty()); + } + } + } + + macro_rules! regressions { + ($name:ident, $backend:ident) => { + mod $name { + use super::*; + #[test] + fn context_is_applied_at_the_eventual_drain() { + late_context(|source| { + crate::Simulation::from_sv_sources( + vec![(source, Path::new("queue_context.sv"))], + "Top", + ) + .$backend() + .unwrap() + }); + } + #[test] + fn stdout_and_normal_events_share_overwrite_capacity() { + bounded_output(|source| { + crate::Simulation::from_sv_sources( + vec![(source, Path::new("queue_capacity.sv"))], + "Top", + ) + .$backend() + .unwrap() + }); + } + } + }; + } + regressions!(interpreter, build_interpreter); + regressions!(cranelift, build_cranelift); + regressions!(wasm, build_wasm); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + regressions!(native, build_native); +} diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index ae3e0a3a821..b7b465d948e 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -245,6 +245,7 @@ impl Simulator { /// Combinational values are settled first, so the file shows the values /// a read would return. pub fn save_state(&mut self) -> Result { + self.check_host_checkpoint_support()?; if !self.testbench_strings.is_empty() { return Err(StateError::TestbenchStrings); } diff --git a/crates/celox/tests/frontends/systemverilog/file_io.rs b/crates/celox/tests/frontends/systemverilog/file_io.rs new file mode 100644 index 00000000000..9dcf2bfff61 --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/file_io.rs @@ -0,0 +1,196 @@ +use super::*; + +sv_backends! { + fn closing_standard_streams_twice_is_a_runtime_error(sim) { + @setup { + let source = r#"module Top(output bit done); + initial begin + $fclose(32'h8000_0001); + $fclose(32'h8000_0001); + done = 1; + end + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("repeat_standard_close.sv"))], "Top"); + assert!(sim.run_until(0).unwrap_err().to_string().contains("invalid or closed")); + let done = sim.signal("done"); + assert_eq!(sim.get(done), BigUint::from(0u8)); + } + + fn scheduled_resets_keep_their_associated_clock_in_reflection(sim) { + @setup { + let source = r#"module Top(input bit clk, rst_n, rst, reference_rst_n, + output bit low, high, reference); + always_ff @(posedge clk or negedge rst_n) begin + $fwrite(1, ""); + if (!rst_n) low <= 0; else low <= 1; + end + always_ff @(posedge clk or posedge rst) begin + $fwrite(1, ""); + if (rst) high <= 0; else high <= 1; + end + always_ff @(posedge clk or negedge reference_rst_n) + if (!reference_rst_n) reference <= 0; else reference <= 1; + endmodule"#; + } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("scheduled_reset_reflection.sv"))], "Top"); + let signals = sim.named_signals(); + for name in ["rst_n", "rst", "reference_rst_n"] { + let signal = signals.iter().find(|signal| signal.name == name).unwrap(); + assert_eq!(signal.associated_clock.as_deref(), Some("clk"), "{name}"); + } + assert!(signals.iter().find(|signal| signal.name == "clk").unwrap().associated_clock.is_none()); + } + + fn memory_snapshots_preserve_non_byte_element_layout(sim) { + @setup { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("narrow_memory"); + let source = format!(r#" + module Top; + logic [4:0] memory [3:1]; + initial begin + memory[3] = 5'b10101; + memory[2] = 5'bxz101; + memory[1] = 5'b00111; + $writememb("{}", memory, 3, 1); + end + endmodule + "#, path.display()); + } + @build celox::Simulation::from_sv_sources(vec![(&source, Path::new("narrow_memory.sv"))], "Top").four_state(true); + sim.run_until(0).unwrap(); + assert_eq!(std::fs::read(&path).unwrap(), b"10101\nxz101\n00111\n"); + } + fn file_output_formats_each_instance_scope(sim) { + @setup { let source = r#"module Child; initial $fdisplay(1, "%m"); endmodule module Top; Child first(); Child second(); endmodule"#; } + @build celox::Simulation::from_sv_sources(vec![(source, Path::new("file_scope.sv"))], "Top"); + sim.run_until(0).unwrap(); + assert_eq!(sim.drain_runtime_events(), vec![ + celox::RuntimeEvent::Display { message: b"Top.first".to_vec() }, + celox::RuntimeEvent::Display { message: b"Top.second".to_vec() }, + ]); + } + fn edge_procedures_execute_requests_in_statement_order(sim) { @case "file_io::edge_procedures_execute_requests_in_statement_order"; } + fn stdout_preserves_format_and_call_order(sim) { @case "file_io::stdout_preserves_format_and_call_order"; } + fn descriptors_distinguish_fd_mcd_and_reuse_channels(sim) { + @setup { + let dir = tempfile::tempdir().unwrap(); + let a = dir.path().join("mcd_a"); + let b = dir.path().join("mcd_b"); + let c = dir.path().join("mcd_c"); + let fd = dir.path().join("fd"); + let source = format!(r#" + module Top(output bit ok); + int a, b, c, fd; + initial begin + a = $fopen("{}"); + b = $fopen("{}"); + fd = $fopen("{}", "wb"); + ok = a != 0 && b != 0 && (a & b) == 0 && !a[31] && !b[31] && fd[31]; + $fdisplay(a | b, "shared:%0d", 37); + $fwrite(fd, "fd"); + $fclose(a); + c = $fopen("{}"); + ok = ok && a == c; + $fclose(b | c); + $fclose(fd); + end + endmodule + "#, a.display(), b.display(), fd.display(), c.display()); + } + @build celox::Simulation::from_sv_sources(vec![(&source, Path::new("file_descriptors.sv"))], "Top"); + sim.run_until(0).unwrap(); + let ok = sim.signal("ok"); + assert_eq!(sim.get(ok), BigUint::from(1u8)); + assert_eq!(std::fs::read(&a).unwrap(), b"shared:37\n"); + assert_eq!(std::fs::read(&b).unwrap(), b"shared:37\n"); + assert_eq!(std::fs::read(&fd).unwrap(), b"fd"); + assert!(std::fs::read(&c).unwrap().is_empty()); + } + + fn files_and_memory_are_written_at_runtime(sim) { + @setup { + let dir = tempfile::tempdir().unwrap(); + let output = dir.path().join("output"); + let hex = dir.path().join("hex"); + let bin = dir.path().join("bin"); + let source = format!(r#" + module Top(output bit done); + timeunit 1ps; timeprecision 1ps; + int fd; + logic [7:0] mem [5:3]; + initial begin + mem[5] = 8'h12; mem[4] = 8'h34; mem[3] = 8'h56; + #1; + fd = $fopen("{}", "w"); + $fdisplay(fd, "value=%h", mem[5]); + $fclose(fd); + fd = $fopen("{}", "a"); + $fwrite(fd, "tail"); + $fclose(fd); + $writememh("{}", mem, 5, 3); + mem[4] = 8'bxz010101; + $writememb("{}", mem, 4, 3); + done = 1; + end + endmodule + "#, output.display(), output.display(), hex.display(), bin.display()); + } + @build celox::Simulation::from_sv_sources(vec![(&source, Path::new("runtime_files.sv"))], "Top").four_state(true); + assert!(!output.exists()); + sim.run_until(0).unwrap(); + assert!(!output.exists()); + sim.run_until(1).unwrap(); + assert_eq!(std::fs::read(&output).unwrap(), b"value=12\ntail"); + assert_eq!(std::fs::read(&hex).unwrap(), b"12\n34\n56\n"); + assert_eq!(std::fs::read(&bin).unwrap(), b"xz010101\n01010110\n"); + } +} + +#[test] +fn edge_host_requests_require_the_timed_api() { + let source = r#"module Top(input bit clk, output bit assigned); + always_ff @(posedge clk) begin + $fwrite(1, "edge"); + assigned = 1; + end + endmodule"#; + let build = || Simulator::from_sv_sources(vec![(source, Path::new("edge_request.sv"))], "Top"); + let results = [ + build().build_interpreter().map(|_| ()), + build().build_cranelift().map(|_| ()), + build().build_wasm().map(|_| ()), + ]; + for result in results { + assert!( + result + .unwrap_err() + .to_string() + .contains("require Simulation") + ); + } + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + assert!( + build() + .build_native() + .unwrap_err() + .to_string() + .contains("require Simulation") + ); +} + +#[test] +fn invalid_file_descriptors_report_runtime_errors() { + let source = r#"module Top; initial $fwrite(32'h8000ffff, "bad"); endmodule"#; + let mut sim = + celox::Simulation::from_sv_sources(vec![(source, Path::new("invalid_fd.sv"))], "Top") + .build_interpreter() + .unwrap(); + assert!( + sim.step() + .unwrap_err() + .to_string() + .contains("invalid or closed") + ); +} diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 35ef965f311..86bbbee169b 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -437,12 +437,12 @@ sv_backends! { 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 dist_uniform_reference_sequence(sim) { + @case "random_plusargs::dist_uniform_reference_sequence"; + } fn plusargs_absent_preserves_destination(sim) { @case "random_plusargs::plusargs_absent_preserves_destination"; } @@ -1797,9 +1797,9 @@ fn reports_where_a_known_system_function_is_not_supported() { endmodule", ), ( - "system function `$fopen`", + "system function `$fgetc`", r#"module Top(input logic a, output logic y); - always_comb begin $fopen("x.txt"); y = a; end + always_comb begin $fgetc(0); y = a; end endmodule"#, ), ( diff --git a/crates/celox/tests/sv_host_requests.rs b/crates/celox/tests/sv_host_requests.rs new file mode 100644 index 00000000000..ed74e5e2ef5 --- /dev/null +++ b/crates/celox/tests/sv_host_requests.rs @@ -0,0 +1,94 @@ +#![cfg(feature = "systemverilog")] + +use std::path::Path; + +/// Every instance starts its own site numbering at zero. Interleaved +/// operation families must retain their operands after a host round trip. +macro_rules! mixed_requests { + ($name:ident, $backend:ident) => { + #[test] + fn $name() { + let directory = tempfile::tempdir().unwrap(); + let first = directory.path().join("first.txt"); + let second = directory.path().join("second.txt"); + let source = String::from( + r#" + module Child #(parameter int ID = 0) + (output logic [7:0] value, output logic ok); + timeunit 1ps; timeprecision 1ps; + logic [2047:0] filename; + logic [127:0] query, file_query; + int fd, seed, random_value; + initial begin + seed = 19; + query = ID == 0 ? "A=%d" : "B=%d"; + file_query = ID == 0 ? "A_PATH=%s" : "B_PATH=%s"; + ok = $value$plusargs(query, value); + ok &= $value$plusargs(file_query, filename); + random_value = $dist_uniform(seed, -3, 3); + ok &= random_value >= -3 && random_value <= 3; + fd = $fopen(filename, "w"); + $fdisplay(fd, "%m:%0d", value); + $fclose(fd); + #1 value = value + 1; + end + endmodule + module Top(output logic [7:0] a_value, b_value, + output logic a_ok, b_ok); + timeunit 1ps; timeprecision 1ps; + Child a(a_value, a_ok); + Child #(.ID(1)) b(b_value, b_ok); + endmodule + "#, + ); + let mut simulation = celox::Simulation::from_sv_sources( + vec![(&source, Path::new("mixed_host_requests.sv"))], + "Top", + ) + .four_state(true) + .plusargs([ + "+A=11".to_string(), + "+B=29".to_string(), + format!("+A_PATH={}", first.display()), + format!("+B_PATH={}", second.display()), + ]) + .$backend() + .unwrap(); + simulation.run_until(2).unwrap(); + assert_eq!(simulation.get(simulation.signal("a_ok")), 1u8.into()); + assert_eq!(simulation.get(simulation.signal("b_ok")), 1u8.into()); + assert_eq!(simulation.get(simulation.signal("a_value")), 12u8.into()); + assert_eq!(simulation.get(simulation.signal("b_value")), 30u8.into()); + assert_eq!(std::fs::read_to_string(first).unwrap(), "Top.a:11\n"); + assert_eq!(std::fs::read_to_string(second).unwrap(), "Top.b:29\n"); + } + }; +} + +mixed_requests!(interpreter, build_interpreter); +mixed_requests!(cranelift, build_cranelift); +mixed_requests!(wasm, build_wasm); +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +mixed_requests!(native, build_native); + +#[test] +fn external_host_state_rejects_checkpoints_and_state_files() { + let statement = r#"$fwrite(1, "output");"#; + let source = + format!("module Top(output bit q); initial begin {statement} q = 1; end endmodule"); + let mut simulation = + celox::Simulation::from_sv_sources(vec![(&source, Path::new("external_state.sv"))], "Top") + .build_interpreter() + .unwrap(); + assert!(matches!( + simulation.checkpoint(), + Err(celox::CheckpointError::ExternalSystemTasks) + )); + assert!( + simulation + .save_state() + .unwrap_err() + .to_string() + .contains("SystemVerilog file I/O") + ); +} diff --git a/crates/celox/tests/sv_ordinary_host_requests.rs b/crates/celox/tests/sv_ordinary_host_requests.rs new file mode 100644 index 00000000000..cae1da6492b --- /dev/null +++ b/crates/celox/tests/sv_ordinary_host_requests.rs @@ -0,0 +1,96 @@ +#![cfg(feature = "systemverilog")] +use std::path::Path; + +macro_rules! ordinary_host_requests { + ($module:ident, $backend:ident) => { + mod $module { + use super::*; + + #[test] + fn ordinary_edge_host_calls_require_timed_simulation() { + for body in [ + "q = q + 1; #0; enabled = $test$plusargs(\"ON\"); q = q + 1;", + "q = q + 1; enabled = $test$plusargs(\"ON\"); q = q + 1;", + "q = q + 1; $fwrite(1, \"edge\"); q = q + 1;", + "q = q + 1; enabled = $fopen(\"unused.txt\"); q = q + 1;", + ] { + let source = format!( + "module Top(input bit clk, output int q, enabled); always @(posedge clk) begin {body} end endmodule" + ); + let error = celox::Simulator::from_sv_sources( + vec![(&source, Path::new("ordinary_host.sv"))], "Top", + ).$backend().err().expect("untimed edge host process was accepted"); + assert!(error.to_string().contains("require Simulation"), "{error}"); + } + } + + #[test] + fn ordinary_edge_host_and_surrounding_statements_run_on_each_edge() { + let source = r#"module Top(input bit clk, output int q, enabled, reference); + always_ff @(posedge clk) reference <= reference + 1; + always @(posedge clk) begin + q = q + 1; + #0; + enabled = $test$plusargs("ON"); + $fwrite(1, "edge"); + q = q + 1; + end + endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("ordinary_host.sv"))], "Top", + ).plusargs(["+ON"]).$backend().unwrap(); + sim.schedule("clk", 1, 1).unwrap(); + sim.schedule("clk", 2, 0).unwrap(); + sim.schedule("clk", 3, 1).unwrap(); + sim.run_until(3).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 4u8.into()); + assert_eq!(sim.get(sim.signal("reference")), 2u8.into()); + assert_eq!(sim.get(sim.signal("enabled")), 1u8.into()); + assert_eq!(sim.drain_runtime_events(), vec![ + celox::RuntimeEvent::Write { message: b"edge".to_vec() }, + celox::RuntimeEvent::Write { message: b"edge".to_vec() }, + ]); + } + + #[test] + fn repeating_host_requirement_does_not_bootstrap_an_immediate_body() { + let source = r#"module Top(output int count, enabled); + timeunit 1ps; timeprecision 1ps; + always begin + count = count + 1; + #1; + enabled = $test$plusargs("ON"); + end + endmodule"#; + let error = celox::Simulator::from_sv_sources( + vec![(source, Path::new("delayed_host.sv"))], "Top", + ).$backend().err().expect("untimed repeating host process was accepted"); + assert!(error.to_string().contains("require Simulation"), "{error}"); + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("delayed_host.sv"))], "Top", + ).plusargs(["+ON"]).$backend().unwrap(); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("count")), 1u8.into()); + assert_eq!(sim.get(sim.signal("enabled")), 0u8.into()); + sim.run_until(1).unwrap(); + assert_eq!(sim.get(sim.signal("count")), 2u8.into()); + assert_eq!(sim.get(sim.signal("enabled")), 1u8.into()); + } + + #[test] + fn one_shot_initial_host_keeps_existing_untimed_builder_boundary() { + let source = r#"module Top(output int enabled); + initial enabled = $test$plusargs("ON"); + endmodule"#; + celox::Simulator::from_sv_sources( + vec![(source, Path::new("initial_host.sv"))], "Top", + ).$backend().unwrap(); + } + } + }; +} +ordinary_host_requests!(interpreter, build_interpreter); +ordinary_host_requests!(cranelift, build); +#[cfg(target_arch = "x86_64")] +ordinary_host_requests!(native, build_native); +ordinary_host_requests!(wasm, build_wasm); diff --git a/crates/celox/tests/sv_scheduled_host_requests.rs b/crates/celox/tests/sv_scheduled_host_requests.rs new file mode 100644 index 00000000000..7df1a9b7ff6 --- /dev/null +++ b/crates/celox/tests/sv_scheduled_host_requests.rs @@ -0,0 +1,305 @@ +#![cfg(feature = "systemverilog")] +use std::path::Path; + +macro_rules! scheduled_requests { + ($module:ident, $backend:ident) => { + mod $module { + use super::*; + #[test] + fn failed_mcd_open_cannot_be_silently_closed() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("missing").join("output.txt"); + let source = format!( + r#"module Top; + int fd; + initial begin fd = $fopen("{}"); $fclose(fd); end + endmodule"#, + path.display() + ); + let mut sim = celox::Simulation::from_sv_sources( + vec![(&source, Path::new("close_zero_mcd.sv"))], + "Top", + ) + .$backend() + .unwrap(); + let error = sim + .run_until(0) + .expect_err("closing zero MCD must be invalid"); + assert!(error.to_string().contains("invalid or closed"), "{error}"); + } + + #[test] + fn disjoint_scheduled_and_regular_writers_remain_valid() { + let source = r#"module Top(input bit clk, output logic [1:0] q); + always_ff @(posedge clk) q[0] <= 1; + always_ff @(posedge clk) q[1] <= $test$plusargs("ON"); + endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("disjoint_scheduled_drivers.sv"))], + "Top", + ) + .plusargs(["+ON"]) + .$backend() + .unwrap(); + sim.schedule("clk", 1, 1).unwrap(); + sim.run_until(1).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 3u8.into()); + } + + #[test] + fn scheduled_writers_participate_in_all_driver_checks() { + for source in [ + r#"module Top(input bit clk, output bit q); + always_ff @(posedge clk) begin q <= 1; $fwrite(1, "host"); end + always_ff @(posedge clk) q <= 0; + endmodule"#, + r#"module Top(input bit clk, output bit q); + always_ff @(posedge clk) begin q <= 1; $fwrite(1, "first"); end + always_ff @(posedge clk) begin q <= 0; $fwrite(1, "second"); end + endmodule"#, + r#"module Top(input bit clk, output bit q); + always_ff @(posedge clk) begin q <= 1; $fwrite(1, "host"); end + always_comb q = 0; + endmodule"#, + r#"module Child(output bit q); always_comb q = 0; endmodule + module Top(input bit clk, output bit q); + Child child(q); + always_ff @(posedge clk) begin q <= 1; $fwrite(1, "host"); end + endmodule"#, + r#"package p; bit state; endpackage + module Writer(input bit clk); + import p::*; + always_ff @(posedge clk) begin state <= 1; $fwrite(1, "host"); end + endmodule + module Top(input bit clk, output bit q); + import p::*; + Writer a(clk), b(clk); + assign q = state; + endmodule"#, + ] { + let error = celox::Simulation::from_sv_sources( + vec![(source, Path::new("scheduled_drivers.sv"))], + "Top", + ) + .$backend() + .err() + .expect("conflicting scheduled writer was accepted"); + let message = error.to_string(); + assert!( + message.contains("multiple variable drivers") + || message.contains("multiple net drivers") + || message.contains("multiple drivers of package variable"), + "{message}" + ); + } + } + + #[test] + fn failed_mcd_open_cannot_silently_discard_output() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("missing").join("output.txt"); + for operation in ["$fwrite", "$fdisplay"] { + let source = format!( + r#"module Top; + int fd; + initial begin fd = $fopen("{}"); {operation}(fd, "lost"); end + endmodule"#, + path.display() + ); + let mut sim = celox::Simulation::from_sv_sources( + vec![(&source, Path::new("zero_mcd.sv"))], + "Top", + ) + .$backend() + .unwrap(); + let error = sim.run_until(0).expect_err("zero MCD must be invalid"); + assert!(error.to_string().contains("invalid or closed"), "{error}"); + assert!(!path.exists()); + } + } + + #[test] + fn a_scheduled_clock_keeps_priority_over_a_retained_reset() { + let source = r#" + module Top(input bit clk, input bit shared, output bit regular, host); + always_ff @(posedge clk or negedge shared) + if (!shared) regular <= 0; else regular <= 1; + always_ff @(posedge shared) host <= $test$plusargs("ON"); + endmodule + "#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("shared_edge_roles.sv"))], + "Top", + ) + .plusargs(["+ON"]) + .$backend() + .unwrap(); + let signals = sim.named_signals(); + assert_eq!( + signals + .iter() + .find(|s| s.name == "shared") + .unwrap() + .info + .type_kind, + celox_design::PortTypeKind::Clock + ); + sim.schedule("shared", 1, 1).unwrap(); + sim.schedule("clk", 2, 1).unwrap(); + sim.schedule("shared", 3, 0).unwrap(); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("host")), 1u8.into()); + assert_eq!(sim.get(sim.signal("regular")), 1u8.into()); + sim.run_until(3).unwrap(); + assert_eq!(sim.get(sim.signal("regular")), 0u8.into()); + } + + #[test] + fn scheduled_clock_and_reset_widths_are_validated() { + for source in [ + r#"module Top(input bit [1:0] clk, output bit q); + always_ff @(posedge clk) q <= $test$plusargs("ON"); + endmodule"#, + r#"module Top(input bit clk, input bit [1:0] rst_n, output bit q); + always_ff @(posedge clk or negedge rst_n) + if (!rst_n) q <= 0; else q <= $test$plusargs("ON"); + endmodule"#, + ] { + let error = celox::Simulation::from_sv_sources( + vec![(source, Path::new("wide_host_event.sv"))], + "Top", + ) + .$backend() + .err() + .expect("multi-bit event must be rejected"); + assert!( + error + .to_string() + .contains("multi-bit always_ff event signal"), + "{error}" + ); + } + } + + #[test] + fn stdout_is_preserved_when_another_mcd_channel_fails() { + let source = r#"module Top; + initial $fwrite(3, "stdout survives"); + endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("mcd_stdout_failure.sv"))], + "Top", + ) + .$backend() + .unwrap(); + assert!(sim.run_until(0).is_err()); + assert_eq!( + sim.drain_runtime_events(), + vec![celox::RuntimeEvent::Write { + message: b"stdout survives".to_vec() + }] + ); + } + + #[test] + fn omitted_defaults_schedule_requests_for_each_call_shape() { + let source = r#" + module Top(input bit clk, output int q); + function automatic int enabled(input int value = $test$plusargs("ON")); + return value; + endfunction + always_ff @(posedge clk) begin + q = enabled(0); + q = enabled(); + end + endmodule + "#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("default_host.sv"))], + "Top", + ) + .plusargs(["+ON"]) + .$backend() + .unwrap(); + sim.schedule("clk", 1, 1).unwrap(); + sim.run_until(1).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + + #[test] + fn folded_host_request_keeps_the_scheduled_process_requirement() { + let source = r#" + module Top(input bit clk, input bit d, output bit q); + always_ff @(posedge clk) begin + if (1'bx) $fwrite(1, "dead"); + q <= d; + end + endmodule + "#; + let result = celox::Simulator::from_sv_sources( + vec![(source, Path::new("dead_host.sv"))], + "Top", + ) + .$backend(); + assert!( + result + .err() + .unwrap() + .to_string() + .contains("require Simulation") + ); + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("dead_host.sv"))], + "Top", + ) + .$backend() + .unwrap(); + sim.checkpoint().unwrap(); // The folded call leaves no file-resource site. + let d = sim.signal("d"); + sim.modify(|io| io.set(d, 1u8)).unwrap(); + sim.schedule("clk", 1, 1).unwrap(); + sim.run_until(1).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + } + + #[test] + fn scheduled_edges_preserve_clock_and_reset_types() { + let source = r#" + module Top(input bit clk, input bit rst_n, output bit q); + always_ff @(posedge clk or negedge rst_n) begin + if (!rst_n) q <= 0; + else q <= $test$plusargs("ON"); + end + endmodule + "#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("reset_host.sv"))], + "Top", + ) + .plusargs(["+ON"]) + .$backend() + .unwrap(); + let signals = sim.named_signals(); + let clock = signals.iter().find(|s| s.name == "clk").unwrap(); + let reset = signals.iter().find(|s| s.name == "rst_n").unwrap(); + assert_eq!(clock.info.type_kind, celox_design::PortTypeKind::Clock); + assert_eq!( + reset.info.type_kind, + celox_design::PortTypeKind::ResetAsyncLow + ); + sim.schedule("rst_n", 0, 1).unwrap(); + sim.schedule("clk", 1, 1).unwrap(); + sim.schedule("rst_n", 2, 0).unwrap(); + sim.run_until(1).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 1u8.into()); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + } + } + }; +} +scheduled_requests!(interpreter, build_interpreter); +scheduled_requests!(cranelift, build_cranelift); +scheduled_requests!(wasm, build_wasm); +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +scheduled_requests!(native, build_native); diff --git a/crates/celox/tests/sv_scheduled_startup.rs b/crates/celox/tests/sv_scheduled_startup.rs new file mode 100644 index 00000000000..ed2d9ba3f94 --- /dev/null +++ b/crates/celox/tests/sv_scheduled_startup.rs @@ -0,0 +1,127 @@ +#![cfg(feature = "systemverilog")] +use std::path::Path; + +macro_rules! scheduled_startup { + ($module:ident, $backend:ident) => { + mod $module { + use super::*; + + #[test] + fn time_zero_clock_arms_ff_without_reordering_initials_or_nba() { + let source = r#"module Top(input bit clk, + output bit regular, host, initial_wait, before_nba, + output int first, second); + always_ff @(posedge clk) regular <= 1; + always_ff @(posedge clk) host <= $test$plusargs("ON"); + initial begin first = $test$plusargs("ON"); #0 first = first + 2; end + initial begin second = first; #0 before_nba = host; end + initial begin @(posedge clk); initial_wait = 1; end + endmodule"#; + for periodic in [false, true] { + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("startup_clock.sv"))], + "Top", + ) + .plusargs(["+ON"]) + .$backend() + .unwrap(); + if periodic { + sim.add_clock("clk", 2, 0); + } else { + sim.schedule("clk", 0, 1).unwrap(); + } + sim.run_until(0).unwrap(); + for name in ["regular", "host"] { + assert_eq!(sim.get(sim.signal(name)), 1u8.into(), "{name}"); + } + assert_eq!(sim.get(sim.signal("first")), 3u8.into()); + assert_eq!(sim.get(sim.signal("second")), 1u8.into()); + assert_eq!(sim.get(sim.signal("before_nba")), 0u8.into()); + assert_eq!(sim.get(sim.signal("initial_wait")), 0u8.into()); + if !periodic { + sim.schedule("clk", 1, 0).unwrap(); + sim.schedule("clk", 2, 1).unwrap(); + } + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("initial_wait")), 1u8.into()); + } + } + + #[test] + fn time_zero_unknown_to_reset_edge_matches_regular_ff() { + let source = r#"module Top(input bit clk, input logic rst_n, + output bit regular, host); + initial begin regular = 1; host = 1; end + always_ff @(posedge clk or negedge rst_n) + if (!rst_n) regular <= 0; else regular <= 1; + always_ff @(posedge clk or negedge rst_n) + if (!rst_n) host <= 0; else host <= $test$plusargs("ON"); + endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("startup_reset.sv"))], + "Top", + ) + .four_state(true) + .plusargs(["+ON"]) + .$backend() + .unwrap(); + sim.schedule("rst_n", 0, 0).unwrap(); + sim.run_until(0).unwrap(); + for name in ["regular", "host"] { + assert_eq!(sim.get(sim.signal(name)), 0u8.into(), "{name}"); + } + sim.schedule("rst_n", 1, 1).unwrap(); + sim.schedule("clk", 2, 1).unwrap(); + sim.run_until(2).unwrap(); + for name in ["regular", "host"] { + assert_eq!(sim.get(sim.signal(name)), 1u8.into(), "{name}"); + } + } + + #[test] + fn restored_time_zero_wait_does_not_restart_registration() { + // A folded host call retains the scheduled FF marker but no + // live host resource, so checkpoints/state files are supported. + let source = r#"module Top(input bit clk, output int count); + always_ff @(posedge clk) begin + if (1'bx) $fwrite(1, "dead"); + count <= count + 1; + end + endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("startup_restore.sv"))], + "Top", + ) + .$backend() + .unwrap(); + let before = sim.checkpoint().unwrap(); + sim.schedule("clk", 0, 1).unwrap(); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("count")), 1u8.into()); + sim.restore(&before).unwrap(); + sim.schedule("clk", 0, 1).unwrap(); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("count")), 1u8.into()); + let after = sim.checkpoint().unwrap(); + let file = sim.save_state().unwrap(); + for import_file in [false, true] { + if import_file { + sim.load_state(&file).unwrap(); + } else { + sim.restore(&after).unwrap(); + } + sim.schedule("clk", 0, 0).unwrap(); + sim.run_until(0).unwrap(); + sim.schedule("clk", 0, 1).unwrap(); + sim.run_until(0).unwrap(); + assert_eq!(sim.get(sim.signal("count")), 2u8.into()); + } + } + } + }; +} +scheduled_startup!(interpreter, build_interpreter); +scheduled_startup!(cranelift, build); +#[cfg(target_arch = "x86_64")] +scheduled_startup!(native, build_native); +scheduled_startup!(wasm, build_wasm); diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index 51d09dd85f4..eae5a3c8257 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -102,6 +102,8 @@ macro_rules! sv_backends { mod always_comb; #[path = "frontends/systemverilog/edges.rs"] mod edges; +#[path = "frontends/systemverilog/file_io.rs"] +mod file_io; #[path = "frontends/systemverilog/generate.rs"] mod generate; #[path = "frontends/systemverilog/hierarchy.rs"] diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 16879f41136..6ebeb90dbc5 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -69,7 +69,7 @@ as waits written directly in a 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 | +| Runtime I/O | `$test$plusargs`, `$value$plusargs`, `$fopen`, `$fclose`, `$fdisplay` / `$fwrite` and radix variants, `$writememh` / `$writememb` in timed processes | | State | two-state and four-state simulation | Every construct above is covered by tests that compare the result with a @@ -105,7 +105,7 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: ([#456](https://github.com/celox-sim/celox/issues/456)). - System tasks and functions: Celox knows every name IEEE 1800-2023 defines, including the optional ones of its Annex D. One it does not support where it is called, such as - `$realtime` in an expression or `$fopen`, is + `$realtime` in an expression or `$fgetc`, is reported with its name wherever it is written, including in an unused parameter and in a function body. A `$` name that is not a system task or function, a call with the wrong number of arguments, an omitted argument @@ -321,6 +321,30 @@ is an error. Without directives, a word-count mismatch is a compilation warning (`Simulator::warnings()`): excess words are ignored, and missing words leave memory unchanged. +### Runtime file output + +`$fopen`, `$fclose`, `$fdisplay` / `$fwrite` and their `b` / `o` / `h` +forms execute in a timed `Simulation` (IEEE 1800-2023 21.3). A one-argument +`$fopen` returns a multichannel descriptor; OR descriptors to write to multiple +files, including standard output through bit zero. Supplying an open mode returns +a file descriptor, with the standard streams at `32'h8000_0000` through +`32'h8000_0002`. Closed channels are reused. Open failures return zero. +Invalid descriptors and write failures produce a runtime error. File names and +modes accept string literals or integral packed strings containing UTF-8 paths. +Dynamic `string` values and non-UTF-8 paths are unsupported. Relative paths use +the host process's working directory. + +`$writememh` / `$writememb` snapshot static unpacked arrays when called, +overwriting the destination (21.5). Optional runtime start and finish addresses +select either traversal direction; out-of-range addresses are runtime errors. +The output retains X/Z bits, contains no address directives, and is readable by +`$readmemh` / `$readmemb`. Those existing tasks still read at compile time. +Dynamic and associative memory arrays are unsupported. + +Edge procedures that call these operations, directly or through subroutines, +run as scheduled kernels. Build them with `Simulation`; a `Simulator` builder +rejects them. Calls from combinational processes are unsupported. + ### Constant parameters of aggregate type Constant parameters of aggregate type (unpacked arrays, packed structs @@ -328,18 +352,24 @@ 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 +### Runtime I/O and plusargs -Use `Simulation::from_sv_sources` for plusargs queries in `initial` blocks -and their subroutines. Queries from combinational and edge-triggered processes -are currently unsupported. +Use `Simulation::from_sv_sources` for host I/O in `initial` blocks and +edge-triggered `always` / `always_ff` processes, including their subroutines. +These calls are unsupported in combinational procedures. A bare `Simulator` +rejects edge procedures that need this timed execution. -Supply ordered arguments with `.plusargs(["+COUNT=12", "+TRACE"])`. +Supply ordered command-line 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. +See [runtime file output](#runtime-file-output) for file descriptors and memory snapshots. + +Checkpoints and state files reject designs with file I/O, whose host state they +cannot capture. + ## Time and precision {#time-and-precision} `$timeunit` and `$timeprecision` return a signed 32-bit exponent in seconds diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index c4758baa9e3..de6bab59b87 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -64,7 +64,7 @@ package/`$unit` の static 引数を持つ時間待ち task と、static task | 乱数 | `$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` とそこから呼ぶサブルーチンで使用可能 | +| 実行時 I/O | `$test$plusargs`、`$value$plusargs`、`$fopen`、`$fclose`、`$fdisplay` / `$fwrite` と基数指定形、`$writememh` / `$writememb`。時間を持つプロセスで実行 | | 状態 | 2 値・4 値シミュレーション | 上記の各構文は、ソフトウェアモデルと結果を比較するテストで確認しています。Veryl が出力する @@ -96,7 +96,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 - 式:ストリーミング連結([#447](https://github.com/celox-sim/celox/issues/447))、パラメータ式での リダクション演算子([#456](https://github.com/celox-sim/celox/issues/456))。 - システムタスクとシステム関数:Celox は IEEE 1800-2023 が定義するすべての名前を、 - 附属書 D の任意のものも含めて知っています。呼び出した位置で対応していないもの(式の中の `$realtime`、`$fopen` など)は、 + 附属書 D の任意のものも含めて知っています。呼び出した位置で対応していないもの(式の中の `$realtime`、`$fgetc` など)は、 使われていないパラメータや関数本体の中を含め、書かれた 場所にかかわらず名前を示して報告します。システムタスクでもシステム関数でもない `$` 名、 引数の数が誤っている呼び出し、既定値のない引数の省略、値として使ったタスクはエラーです。 @@ -213,6 +213,26 @@ static なローカル変数は未対応です。`automatic` と宣言してく アドレス指定がなくワード数が範囲と合わない場合はコンパイル警告(`Simulator::warnings()`)に なり、余ったワードは無視され、足りない分のメモリは変わりません。 +### 実行時のファイル出力 + +`$fopen`、`$fclose`、`$fdisplay` / `$fwrite` とその `b` / `o` / `h` 形は、 +時間を持つ `Simulation` で実行します(IEEE 1800-2023 21.3)。引数が1個の +`$fopen` は multichannel descriptor を返し、OR で複数の出力先を選べます。 +ビット0は標準出力です。モードを指定すると file descriptor を返します。 +閉じたチャネルは再利用され、オープン失敗は0を返します。無効な descriptor や +書き込み失敗は実行時エラーです。ファイル名とモードは文字列リテラルまたは +整数の packed 文字列を指定できます。パスは UTF-8 に限定し、相対パスはホスト +プロセスの作業ディレクトリを基準とします。動的な `string` 値は未対応です。 + +`$writememh` / `$writememb` は呼び出し時点の静的 unpacked 配列を、既存ファイルを +上書きして出力します(21.5)。実行時の開始・終了アドレスで順方向・逆方向を +指定でき、範囲外は実行時エラーです。X/Z を保持し、アドレス指示子は出力しません。 +動的配列と連想配列は未対応です。既存の `$readmemh` / `$readmemb` は引き続き +コンパイル時に読み込みます。 + +これらを直接またはサブルーチン経由で呼ぶエッジプロセスには `Simulation` が必要で、 +`Simulator` のビルダーはエラーを返します。組み合わせプロセスからの呼び出しは未対応です。 + ### 集約型の定数パラメータ 集約型の定数パラメータ(unpacked 配列や、パターンで与える packed 構造体)は、 @@ -234,16 +254,22 @@ Celox は program ブロックを持たず、それ以外からの呼び出し その呼び出し位置でコンパイル警告(`Simulator::warnings()`)を出します。定数関数内の呼び出しも同様です。 関数宣言内の呼び出しは、その関数を使わなくても警告します。定数評価が実行したかどうかには依存しません。 -### コマンドライン引数 +### 実行時 I/O と plusargs -`initial` とそのサブルーチンからの plusargs 検索には `Simulation::from_sv_sources` -を使います。組合せプロセスとエッジで起動するプロセスからの検索は未対応です。 +`initial` やエッジで起動する `always` / `always_ff` と、そのサブルーチンからの +ホスト I/O には `Simulation::from_sv_sources` を使います。組合せプロセスからは +未対応です。時間付き実行が必要なエッジプロセスを `Simulator` で構築するとエラーになります。 引数は `.plusargs(["+COUNT=12", "+TRACE"])` で順序を保って渡します。 `$test$plusargs` は前方一致で検索し、`$value$plusargs` は整数変換と packed 整数変数への `%s` を扱います。最初に一致した引数を使い、未一致の場合は書き込み先の値を保持します。 real 変換と動的 string は未対応です。 +ファイル descriptor とメモリ書き出しは[実行時のファイル出力](#実行時のファイル出力)を参照してください。 + +ファイル I/O を含むデザインでは、ホスト側の状態を保存できないため、 +checkpoint と状態ファイルの保存・復元はエラーになります。 + `$dist_uniform(seed, start, end)` は Annex N の一様分布を使い、整数の seed 変数を更新します。 両端を含み、境界が同じ値か逆順なら seed を進めず `start` を返します。