From eb4e6ae6a92ee97e699d7bb2df5b9df04782010f Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 20 Oct 2026 20:14:47 +0900 Subject: [PATCH 1/2] feat(sv)!: support runtime file output and memory dumps Implement $writememh/$writememb and $fopen/$fclose/$fdisplay/$fwrite variants through per-simulation file descriptors and ordered runtime events. Schedule edge-triggered host requests and reject checkpointing external file resources. Inspect defaults selected by omitted arguments, preserve clock/reset metadata, and retain the timed execution requirement even when host calls fold away. Choose primary edge roles globally across ordinary and scheduled processes, reject unsupported vector event signals, and publish selected stdout even when another MCD channel fails. Preserve scheduled-edge processes in every local driver scan and reject writes and closes using a zero MCD. Reject repeated standard-stream closes across FD/MCD aliases and retain scheduled reset-to-clock reflection. Keep stdout events bounded and unformatted until the caller drains them; preserve the shared overwrite policy and event order. Arm converted edge waiters before time-zero host signal changes. Reject untimed builds of ordinary repeating host procedures through site-level requirements while retaining one-shot initial behavior. Focused file I/O, narrow memory snapshot, mixed-family and checkpoint regressions pass. Affected crates pass checks, all-target Clippy and formatting. Portable memory dump cases pass external simulator validation within documented backend exclusions. Default-argument, clock/reset metadata and folded-request regressions pass across all four backends. Global role priority, event-width validation and failed-MCD stdout regressions also pass across all four backends, alongside existing derived-clock and file-output cases. Driver checks cover scheduled/ordinary/child/package writers and retain disjoint writes; failed MCD-open output and close calls are rejected across all four backends. Regressions cover caller-supplied formatting context, mixed stdout/ring overflow, time-zero clock/reset edges, initial/NBA ordering and checkpoint/state-file restoration. Update the two newly passing file-I/O conformance rows from CI run 39413853030 (artifact 12262168735). BREAKING CHANGE: Public system-task catalogs and CheckpointError gain variants; update exhaustive matches. ProcessSlots gains requires_timed_simulation and ProcessRefs gains starts_with_event_wait; update explicit struct literals. Native images use format 18 and must be rebuilt. Designs with runtime file resources cannot be checkpointed. Change-Id: Ic8428758273662a384f6b07c32944b26b314804e --- conformance/sv-tests/expected.tsv | 4 +- crates/celox-design/src/lib.rs | 3 + crates/celox-frontend-core/src/sdk.rs | 1 + crates/celox-frontend-sv/src/lowering.rs | 145 +++++- crates/celox-frontend-sv/src/lowering/ff.rs | 16 + .../src/lowering/ff/file_io.rs | 164 +++++++ .../src/lowering/procedural.rs | 25 +- crates/celox-runtime/src/file_io.rs | 340 ++++++++++++++ crates/celox-runtime/src/lib.rs | 1 + crates/celox-runtime/src/schedule.rs | 1 + .../celox-runtime/src/simulation/process.rs | 2 +- crates/celox-runtime/src/simulation/time.rs | 17 +- crates/celox-runtime/src/timing.rs | 4 + .../src/ast/expression_binding/direct.rs | 1 + crates/celox-sv-analyzer/src/ir.rs | 52 +++ .../celox-sv-analyzer/src/system_functions.rs | 110 ++++- .../src/sv/cases/file_io.vtest | 37 ++ crates/celox-test-suite/src/sv/cases/mod.rs | 4 + crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/simulation.rs | 21 +- crates/celox/src/simulator.rs | 121 ++++- crates/celox/src/simulator/builder.rs | 36 +- crates/celox/src/simulator/checkpoint.rs | 21 + crates/celox/src/simulator/host/file_io.rs | 427 ++++++++++++++++++ crates/celox/src/simulator/state_file.rs | 1 + .../tests/frontends/systemverilog/file_io.rs | 196 ++++++++ .../systemverilog/system_functions.rs | 10 +- crates/celox/tests/sv_host_requests.rs | 94 ++++ .../celox/tests/sv_ordinary_host_requests.rs | 96 ++++ .../celox/tests/sv_scheduled_host_requests.rs | 305 +++++++++++++ crates/celox/tests/sv_scheduled_startup.rs | 127 ++++++ crates/celox/tests/systemverilog.rs | 2 + docs/guide/systemverilog-reference.md | 44 +- docs/ja/guide/systemverilog-reference.md | 36 +- 34 files changed, 2396 insertions(+), 70 deletions(-) create mode 100644 crates/celox-frontend-sv/src/lowering/ff/file_io.rs create mode 100644 crates/celox-runtime/src/file_io.rs create mode 100644 crates/celox-test-suite/src/sv/cases/file_io.vtest create mode 100644 crates/celox/src/simulator/host/file_io.rs create mode 100644 crates/celox/tests/frontends/systemverilog/file_io.rs create mode 100644 crates/celox/tests/sv_host_requests.rs create mode 100644 crates/celox/tests/sv_ordinary_host_requests.rs create mode 100644 crates/celox/tests/sv_scheduled_host_requests.rs create mode 100644 crates/celox/tests/sv_scheduled_startup.rs 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` を返します。 From 3ad74a1a34e993da3b7e46f61cd541029ae75c59 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 20 Oct 2026 20:16:33 +0900 Subject: [PATCH 2/2] feat(sv)!: add source-driven VCD controls Support $dumpfile/$dumpvars/$dumpon/$dumpoff/$dumpall/$dumplimit/$dumpflush with source hierarchy and depth selection. Preserve waveform signals through optimization, propagate output errors and flush at simulation completion, including direct host API finishes. Enforce dump limits between complete header commands and value records, resume partially emitted headers before values, and rescan when limits relax. Flush old streams before reopening paths, report timed write failures, retain authored names, and apply source selections to component traces. Preserve on/off state changes while output is limited, resolve absolute $root selections, and keep package state outside module-recursive selections. Resolve escaped names, constant indexed hierarchy and explicit package-variable selections; reject source VCD tasks in untimed Simulator builds. Resolve imported package aliases, preserve source controls across output-file switches, retain terminal finish state on output failure, and publish pending diagnostic waveforms before returning fatal errors, including final run-until evaluation. Keep lexically resolved local dump targets distinct from same-named top modules. Accept omitted dump levels while retaining explicit selections, and decode dumpfile names through the shared packed-string binder. Focused VCD and mixed-family regressions pass, including error propagation, hierarchy selection and clocked processes. The completed tree also passes the recorded full unit/system-function, native image/checkpoint, Clippy, JavaScript and documentation checks. Regressions cover each reviewed output/selection failure, including deterministic activity-based limit resumption and injected traces, limited-output suspension, absolute hierarchy names, escaped/indexed hierarchy, explicit package selection and untimed-build rejection. Finish-output errors, fatal diagnostic output, restarted control state and imported-name shadowing have dedicated regressions. Header-command limit boundaries, omitted-depth package filtering and octal/multiline filenames have regressions. SV-only test helpers are gated so default-feature builds remain supported. Update the two newly passing dumpfile conformance rows from CI run 39413853030 (artifact 12262168735). BREAKING CHANGE: The public system-task catalog gains VCD variants; update exhaustive matches. Native images use format 19 for component-aware and lexically bound VCD selections and must be rebuilt. Designs with VCD system tasks cannot be checkpointed. Change-Id: Id407bf67945978820cbb54624814a47d2b66a8f1 --- conformance/sv-tests/expected.tsv | 4 +- crates/celox-frontend-sv/src/lowering/ff.rs | 80 ++ .../src/lowering/procedural.rs | 3 +- crates/celox-runtime/src/simulation/host.rs | 19 + crates/celox-runtime/src/simulation/mod.rs | 66 +- crates/celox-runtime/src/simulation/time.rs | 2 +- crates/celox-runtime/src/vcd.rs | 430 ++++++++- crates/celox-runtime/src/vcd/plan.rs | 17 + crates/celox-sv-analyzer/src/ast/packages.rs | 5 +- .../celox-sv-analyzer/src/ast/procedural.rs | 144 ++- crates/celox-sv-analyzer/src/ir.rs | 2 +- .../celox-sv-analyzer/src/system_functions.rs | 72 +- crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/component.rs | 86 ++ crates/celox/src/ir.rs | 6 + crates/celox/src/simulation.rs | 90 +- crates/celox/src/simulation/vcd_tasks.rs | 532 +++++++++++ crates/celox/src/simulator.rs | 30 +- crates/celox/src/simulator/builder.rs | 127 ++- crates/celox/src/simulator/checkpoint.rs | 11 +- .../systemverilog/system_functions.rs | 4 +- crates/celox/tests/sv_host_requests.rs | 52 +- crates/celox/tests/sv_vcd.rs | 902 ++++++++++++++++++ docs/guide/systemverilog-reference.md | 7 +- docs/guide/vcd.md | 27 + docs/ja/guide/systemverilog-reference.md | 5 +- docs/ja/guide/vcd.md | 26 + 27 files changed, 2636 insertions(+), 115 deletions(-) create mode 100644 crates/celox/src/simulation/vcd_tasks.rs create mode 100644 crates/celox/tests/sv_vcd.rs diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index b6bbf98b178..4e44a96be83 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -819,8 +819,8 @@ chapter-21/21.6--test.sv 2state pass chapter-21/21.6--test.sv 4state pass chapter-21/21.6--value.sv 2state pass chapter-21/21.6--value.sv 4state pass -chapter-21/21.7--dumpfile.sv 2state fail -chapter-21/21.7--dumpfile.sv 4state fail +chapter-21/21.7--dumpfile.sv 2state pass +chapter-21/21.7--dumpfile.sv 4state pass chapter-21/21.7--dumpports.sv 2state fail chapter-21/21.7--dumpports.sv 4state fail chapter-22/22.10--celldefine-basic-1.sv 2state skip diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 94bdcb8efe0..64b54726a4a 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -1130,6 +1130,82 @@ impl<'p, 'a> Ff<'p, 'a> { self.random.clone().expect("a process RNG") } + fn vcd_task( + &mut self, + operation: sv::ir::VcdTask, + args: &[sv::ir::SystemTaskArg], + ) -> Result<(), sv::AnalyzerError> { + use celox_design::{HostRequestKind, HostRequestSite, HostRequestValue}; + use sv::ir::VcdTask; + if self.kernel.is_none() { + return Err(unsupported("VCD tasks require a timed process")); + } + let mut values = Vec::new(); + let mut strings = Vec::new(); + for (index, arg) in args.iter().enumerate() { + if operation == VcdTask::Vars + && index == 0 + && matches!(arg, sv::ir::SystemTaskArg::Empty) + { + continue; + } + if operation == VcdTask::Vars && index > 0 { + let sv::ir::SystemTaskArg::Str(name) = arg else { + return Err(unsupported("$dumpvars module or variable selection")); + }; + strings.push(name.clone()); + continue; + } + 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) if operation == VcdTask::File => { + let bytes = unescape(text).into_bytes(); + let width = (bytes.len() * 8).max(8); + let value = bytes.iter().fold(BigUint::zero(), |value, byte| { + (value << 8u32) | BigUint::from(*byte) + }); + let reg = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Imm(reg, SIRValue::new(value))); + (reg, false, true) + } + _ => { + return Err(unsupported( + "VCD argument must be an integral value or filename string", + )); + } + }; + let width = self.b.register(®).width(); + let is_4state = matches!(self.b.register(®), RegisterType::Logic { .. }); + let (id, _) = self.m.temp("vcd_argument", width, signed, is_4state); + self.store(id, SIROffset::Static(0), width, reg); + values.push(HostRequestValue { + id, + width, + signed, + is_string, + }); + } + let local_site = self + .host_request_sites + .iter() + .filter(|site| site.kind == HostRequestKind::Vcd) + .count() as u32; + self.host_request_sites.push(HostRequestSite { + process: self.process, + kind: HostRequestKind::Vcd, + requires_timed_simulation: false, + operation: operation as u32, + args: values, + results: Vec::new(), + strings, + }); + self.with_kernel(|kernel| kernel.host_request(HostRequestKind::Vcd, local_site)) + .map_err(|error| unsupported(error.to_string()))?; + Ok(()) + } + /// The seed of this process's `$random` calls without a seed argument. /// It starts at 0, as the seed variable of `$random(seed)` typically /// does, so a design whose one process calls `$random` gets the same @@ -2408,6 +2484,10 @@ impl<'p, 'a> Ff<'p, 'a> { args: &[sv::ir::SystemTaskArg], site: Option<&sv::ir::SourceSpan>, ) -> Result { + if let sv::ir::SystemTask::Vcd(operation) = task { + self.vcd_task(operation, args)?; + return Ok(true); + } if matches!( task, sv::ir::SystemTask::Fclose diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index bf02ad0e9f6..64778f14ca0 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -931,7 +931,8 @@ pub(super) fn system_task_kind(task: sv::ir::SystemTask) -> Option return None, + | SystemTask::Exit + | SystemTask::Vcd(_) => return None, }) } diff --git a/crates/celox-runtime/src/simulation/host.rs b/crates/celox-runtime/src/simulation/host.rs index d583777dca6..37a7f4aa3a7 100644 --- a/crates/celox-runtime/src/simulation/host.rs +++ b/crates/celox-runtime/src/simulation/host.rs @@ -56,6 +56,18 @@ pub trait HostBoundary: UnitExecutor { /// change its state. fn freeze(&mut self) {} + /// Publish buffered diagnostic output without ending or freezing execution. + fn flush_output(&mut self) -> Result<(), SimulatorErrorCode> { + Ok(()) + } + + /// Freeze after a design-requested finish, reporting output failures. + fn try_freeze(&mut self) -> Result<(), SimulatorErrorCode> { + let output = self.flush_output(); + self.freeze(); + output + } + /// Snapshot external-component inputs immediately before an event domain /// evaluates its sequential logic. fn stage_external_event( @@ -78,6 +90,13 @@ pub trait HostBoundary: UnitExecutor { /// Called after the state for a simulation timestamp has stabilized. fn finish_timed_step(&mut self, _timestamp: u64) {} + + /// Fallible timestamp boundary. The default preserves the original + /// infallible hook for existing executor implementations. + fn try_finish_timed_step(&mut self, timestamp: u64) -> Result<(), Halt> { + self.finish_timed_step(timestamp); + Ok(()) + } } /// Backend execution hooks needed by the timed simulation engine: its diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 3c14ffee561..3fadd223888 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -189,17 +189,64 @@ impl SimulationState { match self.step_time(executor, limit) { Ok(time) => Ok(time), Err(Halt::Finish) => { - // The waveform records the state at the finish. - executor.finish_timed_step(self.scheduler.time); - self.finish(executor); + self.finalize_terminal(executor)?; Ok(Some(self.scheduler.time)) } // The time slot goes on when the simulation continues. Err(Halt::Stop) => Ok(Some(self.scheduler.time)), + Err(Halt::Error(error)) => { + // Preserve the primary runtime failure even if diagnostic + // waveform output also fails. This does not resume processes. + let _ = self.finish_timed_boundary(executor, self.scheduler.time); + let _ = executor.flush_output(); + Err(error) + } + } + } + + /// Complete a boundary reached from an entry point that returns runtime + /// errors rather than scheduler control halts. + fn finish_timed_boundary( + &mut self, + executor: &mut E, + time: u64, + ) -> Result<(), SimulatorErrorCode> + where + E: SimulationExecutor, + { + match executor.try_finish_timed_step(time) { + Ok(()) => Ok(()), Err(Halt::Error(error)) => Err(error), + Err(Halt::Finish) => { + self.finish_checked(executor)?; + Ok(()) + } + Err(Halt::Stop) => { + self.stopped = true; + Ok(()) + } } } + fn finish_checked(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode> + where + E: SimulationExecutor, + { + self.finished = true; + executor.try_freeze() + } + + /// Once $finish is consumed, output errors must not make execution resumable. + pub fn finalize_terminal(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode> + where + E: SimulationExecutor, + { + self.finished = true; + let output = self.finish_timed_boundary(executor, self.scheduler.time); + let frozen = executor.try_freeze(); + output.and(frozen) + } + /// End the simulation where it is. pub fn finish(&mut self, executor: &mut E) where @@ -241,16 +288,21 @@ impl SimulationState { self.slot_passes = 0; match self.step_round(executor, time, Vec::new(), Vec::new(), true) { Ok(()) => { - executor.finish_timed_step(time); + self.finish_timed_boundary(executor, time)?; Ok(Some(time)) } Err(Halt::Finish) => { - executor.finish_timed_step(time); - self.finish(executor); + self.finalize_terminal(executor)?; Ok(Some(self.scheduler.time)) } Err(Halt::Stop) => Ok(Some(self.scheduler.time)), - Err(Halt::Error(error)) => Err(error), + Err(Halt::Error(error)) => { + // Preserve the primary runtime failure even if diagnostic + // waveform output also fails. This does not resume processes. + let _ = self.finish_timed_boundary(executor, self.scheduler.time); + let _ = executor.flush_output(); + Err(error) + } } } diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index 3b4a5bec296..1d8657ff8f1 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -183,7 +183,7 @@ impl SimulationState { self.charge_pass()?; self.step_round(executor, current_time, Vec::new(), ready, false)?; } - executor.finish_timed_step(current_time); + executor.try_finish_timed_step(current_time)?; Ok(()) } diff --git a/crates/celox-runtime/src/vcd.rs b/crates/celox-runtime/src/vcd.rs index e79e493bc1b..1747c6eb6b0 100644 --- a/crates/celox-runtime/src/vcd.rs +++ b/crates/celox-runtime/src/vcd.rs @@ -119,8 +119,11 @@ pub struct VcdWriter { timestamp: u64, time_precision: celox_design::TimePrecision, header_written: bool, + /// Complete header commands awaiting emission after a byte-limit pause. + header_records: Option>>, initial_values_written: bool, external_count: usize, + suspended: bool, } struct VcdOutput { @@ -133,6 +136,9 @@ struct VcdOutput { /// Bytes already accepted by BufWriter, including short writes before an error. written: usize, encoded_changes: u64, + accepted_bytes: u64, + byte_limit: Option, + limit_comment_written: bool, stats: VcdStatistics, } @@ -158,9 +164,11 @@ impl VcdWriter { /// signals, in a new file at `path`. The first dump there records every /// value, and its timestamps start over. pub fn restart>(&mut self, path: P) -> std::io::Result<()> { + self.flush()?; let mut next = Self::new_with_time_precision(path, &self.descs, self.time_precision)?; next.add_external_signals(&self.external_descs)?; - self.flush()?; + next.suspended = self.suspended; + next.output.byte_limit = self.output.byte_limit; *self = next; Ok(()) } @@ -199,6 +207,9 @@ impl VcdWriter { encoded: Vec::new(), written: 0, encoded_changes: 0, + accepted_bytes: 0, + byte_limit: None, + limit_comment_written: false, stats: VcdStatistics::default(), }, headers, @@ -212,8 +223,10 @@ impl VcdWriter { timestamp: 0, time_precision, header_written: false, + header_records: None, initial_values_written: false, external_count: 0, + suspended: false, } } @@ -243,6 +256,110 @@ impl VcdWriter { self.rescan_pending = true; } + /// Set the maximum output size requested by `$dumplimit`. Zero removes + /// the limit. Complete records may take the file beyond the limit. + pub fn set_byte_limit(&mut self, limit: u64) { + if self.output.limit_reached() { + // Skipped output may have consumed the backend's activity flags, + // and a partial initial snapshot has not initialized every value. + self.rescan_pending = true; + self.initial_values_written = false; + } + self.output.byte_limit = (limit != 0).then_some(limit); + self.output.limit_comment_written = false; + } + + fn limit_reached(&mut self) -> bool { + let reached = self.output.limit_reached(); + if reached { + self.output.note_limit(); + } + reached + } + + /// Emit a SystemVerilog VCD checkpoint. `off` writes unknowns and + /// suspends changes; `on` writes current values and resumes; `all` + /// writes current values without changing suspension (21.7.1.3–4). + pub fn checkpoint( + &mut self, + command: &str, + timestamp: u64, + memory: &[u8], + external: &[(BigUint, BigUint)], + ) -> std::io::Result<()> { + if !matches!(command, "dumpoff" | "dumpon" | "dumpall") { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "invalid VCD checkpoint", + )); + } + self.validate_external_count(external.len())?; + // Suppressing header or value records must not suppress controls. + match command { + "dumpoff" => self.suspended = true, + "dumpon" => self.suspended = false, + _ => {} + } + if self.limit_reached() || !self.begin_timestamp(timestamp)? { + return Ok(()); + } + writeln!(self.output.encoded, "${command}")?; + if command == "dumpoff" { + for index in 0..self.headers.len() { + if self.output.limit_reached() { + break; + } + let width = self.headers[index].width; + let size = width.div_ceil(8); + self.output.encoded.reserve(width + 16); + let len = encode_value( + self.output.encoded.spare_capacity_mut(), + width, + &vec![255; size], + &vec![255; size], + ); + self.output.finish_record(len, self.plan.suffix(index))?; + } + self.suspended = true; + } else { + self.plan + .dump::(memory, external, None, &mut self.output)?; + self.initial_values_written = true; + if command == "dumpon" { + self.suspended = false; + } + } + writeln!(self.output.encoded, "$end")?; + self.output.note_limit(); + self.rescan_pending = true; + Ok(()) + } + + fn begin_timestamp(&mut self, timestamp: u64) -> std::io::Result { + if self.header_written && timestamp < self.timestamp { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!( + "VCD timestamp {timestamp} is earlier than the last dumped timestamp {}; start a new file to record a rewound simulation", + self.timestamp + ), + )); + } + self.output.write_encoded()?; + if !self.header_written && !self.write_header()? { + return Ok(false); + } + if self.limit_reached() { + return Ok(false); + } + if timestamp > self.timestamp || timestamp == 0 { + writeln!(self.output.encoded, "#{timestamp}")?; + self.timestamp = timestamp; + self.output.write_encoded()?; + } + Ok(true) + } + /// Dump as the backend's sole incremental waveform observer. Multiple /// writers must consume activity once and share it through /// `dump_with_activity`, since each consumption clears the pending flags. @@ -309,7 +426,7 @@ impl VcdWriter { return Ok(()); } } - if self.header_written { + if self.header_written || self.header_records.is_some() { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, "cannot add external VCD signals after the first dump", @@ -330,20 +447,18 @@ impl VcdWriter { } #[cold] - fn write_header(&mut self) -> std::io::Result<()> { - writeln!(self.output.encoded, "$date")?; - writeln!( - self.output.encoded, - " {}", - chrono::Local::now().format("%Y-%m-%d %H:%M:%S") - )?; - writeln!(self.output.encoded, "$end")?; - writeln!(self.output.encoded, "$version")?; - writeln!(self.output.encoded, " celox")?; - writeln!(self.output.encoded, "$end")?; + fn prepare_header(&mut self) -> std::collections::VecDeque> { + let mut records = std::collections::VecDeque::new(); + records.push_back( + format!( + "$date\n {}\n$end\n", + chrono::Local::now().format("%Y-%m-%d %H:%M:%S") + ) + .into_bytes(), + ); + records.push_back(b"$version\n celox\n$end\n".to_vec()); let (magnitude, unit) = self.time_precision.vcd_timescale(); - writeln!(self.output.encoded, "$timescale {magnitude}{unit} $end")?; - + records.push_back(format!("$timescale {magnitude}{unit} $end\n").into_bytes()); let mut scope_order = Vec::::new(); let mut scope_groups = Vec::>::new(); let mut scope_idx = fxhash::FxHashMap::::default(); @@ -359,23 +474,42 @@ impl VcdWriter { } let mut next_id = 0; for (scope, group) in scope_order.iter().zip(scope_groups) { - writeln!(self.output.encoded, "$scope module {} $end", scope)?; + records.push_back(format!("$scope module {scope} $end\n").into_bytes()); for signal_index in group { let signal = &mut self.headers[signal_index]; let id = Self::generate_vcd_id(next_id); *self.plan.suffix(signal_index) = VcdRecordSuffix::new(signal.width, &id); next_id += 1; - writeln!( - self.output.encoded, - "$var wire {} {} {} $end", - signal.width, id, signal.name - )?; + records.push_back( + format!("$var wire {} {} {} $end\n", signal.width, id, signal.name) + .into_bytes(), + ); } - writeln!(self.output.encoded, "$upscope $end")?; + records.push_back(b"$upscope $end\n".to_vec()); } - writeln!(self.output.encoded, "$enddefinitions $end")?; - writeln!(self.output.encoded, "$dumpvars")?; - writeln!(self.output.encoded, "$end")?; + records.push_back(b"$enddefinitions $end\n".to_vec()); + records.push_back(b"$dumpvars\n$end\n".to_vec()); + records + } + + #[cold] + fn write_header(&mut self) -> std::io::Result { + if self.header_records.is_none() { + self.header_records = Some(self.prepare_header()); + } + while self + .header_records + .as_ref() + .is_some_and(|records| !records.is_empty()) + { + if self.limit_reached() { + return Ok(false); + } + let record = self.header_records.as_mut().unwrap().pop_front().unwrap(); + self.output.encoded.extend_from_slice(&record); + self.output.write_encoded()?; + } + self.header_records = None; let record_capacity = self .headers .iter() @@ -402,7 +536,7 @@ impl VcdWriter { // A large header must not permanently enlarge the value buffer. self.output.encoded.shrink_to(capacity); } - Ok(()) + Ok(true) } fn generate_vcd_id(num: usize) -> String { @@ -457,27 +591,12 @@ impl VcdWriter { activity: Option<&[usize]>, ) -> std::io::Result<()> { self.validate_external_count(external.len())?; - if self.header_written && timestamp < self.timestamp { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidInput, - format!( - "VCD timestamp {timestamp} is earlier than the last dumped timestamp {}; \ - start a new file to record a rewound simulation", - self.timestamp - ), - )); + if self.suspended || self.limit_reached() { + return Ok(()); } - // Finish the previous attempt before starting a new timestamp or - // consulting caches that include its queued value records. - self.output.write_encoded()?; let first_dump = !self.initial_values_written; - if !self.header_written { - self.write_header()?; - } - if timestamp > self.timestamp || timestamp == 0 { - writeln!(self.output.encoded, "#{}", timestamp)?; - self.timestamp = timestamp; - self.output.write_encoded()?; + if !self.begin_timestamp(timestamp)? { + return Ok(()); } self.selected.clear(); // Dense activity is cheaper to walk directly in registration order. @@ -510,11 +629,26 @@ impl VcdWriter { &mut self.output, )?; } + self.output.note_limit(); Ok(()) } } impl VcdOutput { + #[inline] + fn limit_reached(&self) -> bool { + self.byte_limit + .is_some_and(|limit| self.accepted_bytes + self.encoded.len() as u64 >= limit) + } + + fn note_limit(&mut self) { + if self.limit_reached() && !self.limit_comment_written { + self.encoded + .extend_from_slice(b"$comment VCD dump limit reached $end\n"); + self.limit_comment_written = true; + } + } + // Keep suffix publication with the value encoder so SIMD constants and // output state can stay in registers between records. #[inline(always)] @@ -548,6 +682,7 @@ impl VcdOutput { self.stats.changes += self.encoded_changes; self.stats.value_bytes += self.encoded.len() as u64; } + self.accepted_bytes += self.encoded.len() as u64; self.encoded.clear(); self.written = 0; self.encoded_changes = 0; @@ -736,6 +871,211 @@ const BINARY: [[u8; 8]; 256] = { mod tests { use super::*; + #[test] + fn limited_checkpoints_preserve_on_off_state_when_recording_resumes() { + for command in ["dumpoff", "dumpon"] { + let descs = [VcdSignalDesc { + scope: "Top".into(), + name: "value".into(), + offset: 0, + width: 1, + is_4state: false, + }]; + let mut writer = VcdWriter::from_writer(Vec::new(), &descs); + writer.dump(0, &[0]).unwrap(); + if command == "dumpon" { + writer.checkpoint("dumpoff", 1, &[0], &[]).unwrap(); + } + writer.set_byte_limit(1); + writer.checkpoint(command, 2, &[1], &[]).unwrap(); + writer.set_byte_limit(0); + writer.dump(3, &[1]).unwrap(); + let output = String::from_utf8(writer.into_inner().unwrap()).unwrap(); + assert_eq!( + output.contains("#3\n1"), + command == "dumpon", + "{command}: {output}" + ); + if command == "dumpoff" { + assert!( + !output.contains("#3"), + "off under the limit must remain suspended: {output}" + ); + } + } + } + + #[test] + fn byte_limit_pauses_header_at_command_boundaries_and_resumes_once() { + let descs = (0..100) + .map(|index| VcdSignalDesc { + scope: "Top".into(), + name: format!("signal_{index}"), + offset: index, + width: 1, + is_4state: false, + }) + .collect::>(); + let mut reference = VcdWriter::from_writer(Vec::new(), &descs); + let records = reference.prepare_header(); + let max_record = records.iter().map(Vec::len).max().unwrap(); + let header_size = records.iter().map(Vec::len).sum::(); + let mut boundary = 0; + let mut limits = vec![1]; + for record in &records { + boundary += record.len(); + limits.extend([boundary.saturating_sub(1), boundary]); + } + for limit in limits { + let mut writer = VcdWriter::from_writer(Vec::new(), &descs); + writer.set_byte_limit(limit as u64); + writer.dump(0, &[0; 100]).unwrap(); + writer.flush().unwrap(); + let paused = String::from_utf8(writer.get_ref().clone()).unwrap(); + assert!( + paused.len() <= limit + max_record + 36, + "{limit}/{header_size}: {paused}" + ); + assert!( + paused.contains("VCD dump limit reached"), + "{limit}: {paused}" + ); + assert!(!paused.contains("#0"), "{limit}: {paused}"); + assert_eq!(writer.statistics().changes, 0); + writer.set_byte_limit(0); + writer.dump(5, &[1; 100]).unwrap(); + let output = String::from_utf8(writer.into_inner().unwrap()).unwrap(); + assert_eq!(output.matches("$date\n").count(), 1, "{limit}: {output}"); + assert_eq!( + output.matches("$var wire ").count(), + 100, + "{limit}: {output}" + ); + assert_eq!( + output.matches("$enddefinitions $end").count(), + 1, + "{limit}: {output}" + ); + let (_, values) = output.split_once("#5\n").unwrap(); + assert_eq!( + values.lines().filter(|line| line.starts_with('1')).count(), + 100, + "{limit}: {output}" + ); + } + } + + #[test] + fn header_limit_keeps_checkpoint_suspension_and_external_registration() { + let descs = [VcdSignalDesc { + scope: "Top".into(), + name: "state".into(), + offset: 0, + width: 1, + is_4state: false, + }]; + let mut writer = VcdWriter::from_writer(Vec::new(), &descs); + writer.set_byte_limit(1); + writer.dump(0, &[0]).unwrap(); + assert!( + writer + .add_external_signals(&[VcdExternalSignalDesc { + scope: "Top".into(), + name: "late".into(), + width: 1 + }]) + .is_err() + ); + writer.checkpoint("dumpoff", 1, &[1], &[]).unwrap(); + writer.set_byte_limit(0); + writer.dump(2, &[1]).unwrap(); + writer.checkpoint("dumpon", 3, &[1], &[]).unwrap(); + let output = String::from_utf8(writer.into_inner().unwrap()).unwrap(); + assert!(!output.contains("#2"), "{output}"); + assert!(output.contains("#3\n$dumpon\n1!\n$end"), "{output}"); + } + + #[test] + fn byte_limit_stops_initial_changes_and_checkpoint_at_one_record() { + for width in [1usize, 4, 64] { + let bytes = width.div_ceil(8); + let descs = (0..100) + .map(|i| VcdSignalDesc { + scope: "Top".into(), + name: format!("s{i}"), + offset: i * bytes, + width, + is_4state: false, + }) + .collect::>(); + for command in ["initial", "changes", "dumpall", "dumpoff", "dumpon"] { + let mut writer = VcdWriter::from_writer(Vec::new(), &descs); + let mut memory = vec![0u8; bytes * descs.len()]; + writer.write_header().unwrap(); + if command != "initial" { + writer.dump(0, &memory).unwrap(); + } + let before = writer.statistics().changes; + writer.output.write_encoded().unwrap(); + // Leave room for the timestamp/command and one record, but not + // for the complete hundred-signal snapshot or checkpoint. + let allowance = if command.starts_with("dump") { 22 } else { 6 }; + let limit = writer.output.accepted_bytes + allowance; + writer.set_byte_limit(limit); + memory.fill(255); + if command.starts_with("dump") { + writer.checkpoint(command, 1, &memory, &[]).unwrap(); + } else { + writer.dump(1, &memory).unwrap(); + } + writer.flush().unwrap(); + let records = writer.statistics().changes - before; + assert!( + records < 10, + "{command}/{width}: emitted {records} records past a small limit" + ); + let output = String::from_utf8(writer.into_inner().unwrap()).unwrap(); + assert!( + output.contains("VCD dump limit reached"), + "{command}/{width}: {output}" + ); + let max_record = width.max(1) as u64 + 5; + assert!( + output.len() as u64 <= limit + max_record + 5 + 36, + "{command}/{width}: {} exceeds bound {limit}", + output.len() + ); + } + } + } + + #[test] + fn system_task_checkpoints_and_limit() { + let descs = [VcdSignalDesc { + scope: "Top".into(), + name: "value".into(), + offset: 0, + width: 4, + is_4state: true, + }]; + let mut writer = VcdWriter::from_writer(Vec::new(), &descs); + writer.dump(0, &[0b1011, 0b0011]).unwrap(); + writer.checkpoint("dumpoff", 1, &[15, 0], &[]).unwrap(); + writer.dump(2, &[0, 0]).unwrap(); + writer.checkpoint("dumpon", 3, &[15, 0], &[]).unwrap(); + writer.checkpoint("dumpall", 4, &[15, 0], &[]).unwrap(); + writer.set_byte_limit(1); + writer.dump(5, &[0, 0]).unwrap(); + let output = String::from_utf8(writer.into_inner().unwrap()).unwrap(); + assert!(output.contains("b10xx ")); + assert!(output.contains("$dumpoff\nbxxxx ")); + assert!(!output.contains("#2")); + assert!(output.contains("$dumpon\nb1111 ")); + assert!(output.contains("$dumpall\nb1111 ")); + assert!(!output.contains("#5")); + assert!(output.contains("VCD dump limit reached")); + } + #[test] fn headers_encode_supported_time_precisions() { for (exponent, expected) in [ diff --git a/crates/celox-runtime/src/vcd/plan.rs b/crates/celox-runtime/src/vcd/plan.rs index e29499de9e0..660586741db 100644 --- a/crates/celox-runtime/src/vcd/plan.rs +++ b/crates/celox-runtime/src/vcd/plan.rs @@ -184,6 +184,9 @@ impl TracePlan { // Sparse indices can break a long typed run into many short ones. // Visit each entry once instead of first rebuilding those runs. for &index in selected { + if output.limit_reached() { + break; + } let entry = self.entries[index]; let run = Run { kind: entry.kind, @@ -199,6 +202,9 @@ impl TracePlan { // Alternating types form many tiny runs. Visit their entries // directly so each specialized loop has a known length of one. for index in 0..self.entries.len() { + if output.limit_reached() { + break; + } let entry = self.entries[index]; let run = Run { kind: entry.kind, @@ -212,6 +218,9 @@ impl TracePlan { } } else { for index in 0..self.runs.len() { + if output.limit_reached() { + break; + } // SAFETY: the complete memory range was validated above. unsafe { self.write_run::(self.runs[index], memory, external, output)?; @@ -248,6 +257,10 @@ impl TracePlan { Kind::Generic => { let signals = &self.generic[run.start..run.end]; for (index, signal) in signals.iter().enumerate() { + if output.limit_reached() { + output.stats.comparisons += index as u64; + return Ok(()); + } let size = signal.width.div_ceil(8); let external_bytes; let (value, mask, track_mask): (&[u8], &[u8], bool) = match signal.source { @@ -306,6 +319,10 @@ unsafe fn write_fixed( output: &mut VcdOutput, ) -> std::io::Result<()> { for (index, signal) in signals.iter_mut().enumerate() { + if output.limit_reached() { + output.stats.comparisons += index as u64; + return Ok(()); + } let value = if BIT { // SAFETY: the plan validated this one-byte range for this dump. u64::from(unsafe { *memory.as_ptr().add(signal.offset) } & 1) diff --git a/crates/celox-sv-analyzer/src/ast/packages.rs b/crates/celox-sv-analyzer/src/ast/packages.rs index 397455ff256..42278e04dc2 100644 --- a/crates/celox-sv-analyzer/src/ast/packages.rs +++ b/crates/celox-sv-analyzer/src/ast/packages.rs @@ -357,7 +357,10 @@ impl Packages { /// The variables package `name` declares: each is one object, shared by /// every module that uses it (IEEE 1800-2023 26.2). Constant variables are /// left out; they are copied like parameters. Package nets are rejected. -fn package_variables(name: &str, tree: &SyntaxTree) -> Result, AnalyzerError> { +pub(super) fn package_variables( + name: &str, + tree: &SyntaxTree, +) -> Result, AnalyzerError> { use celox_sv_syntax::{BodyItemKind, DataDeclaration}; let native = tree.declarations(); let mut variables = HashSet::default(); diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 6668b2960b0..1ce0ac90e77 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -843,11 +843,30 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { }; let args = arguments .iter() - .map(|arg| { + .enumerate() + .map(|(index, arg)| { let Some(id) = arg.value else { return Ok(SystemTaskArg::Empty); }; - if let celox_sv_syntax::ExprKind::Literal(text) = &declarations.expression(id).kind + if matches!(task, SystemTask::Vcd(system_functions::VcdTask::Vars)) && index > 0 { + let text = dump_selection_name( + id, + self.tree, + &self.dims, + &|value| self.rename_const(value), + &|name| { + self.scopes + .iter() + .any(|scope| scope.entries.iter().any(|entry| entry.source == name)) + }, + )?; + return Ok(SystemTaskArg::Str(text)); + } + // Filenames use the normal packed-string expression binder, + // including octal/hex escapes and multiline literal delimiters. + if !matches!(task, SystemTask::Vcd(system_functions::VcdTask::File)) + && let celox_sv_syntax::ExprKind::Literal(text) = + &declarations.expression(id).kind && let Some(text) = text .strip_prefix('"') .and_then(|text| text.strip_suffix('"')) @@ -1674,3 +1693,124 @@ pub(super) fn source_span( } result } + +fn dump_selection_name( + id: celox_sv_syntax::ExprId, + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + rename: &dyn Fn(&mut ConstExpr), + is_local: &dyn Fn(&str) -> bool, +) -> Result { + // Preserve identifier/index boundaries in host metadata. A normalized + // escaped identifier can itself contain '.', '::', or '[0]'. NUL cannot + // occur in an authored identifier, so it separates these components. + fn append( + id: celox_sv_syntax::ExprId, + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + rename: &dyn Fn(&mut ConstExpr), + kind: &mut &'static str, + fields: &mut Vec, + ) -> Result<(), AnalyzerError> { + use celox_sv_syntax::{DimensionKind, ExprKind}; + match &tree.declarations().expression(id).kind { + ExprKind::Name(name) if name.spelling == "$root" => { + *kind = "absolute"; + } + ExprKind::Name(name) => { + fields.extend([ + "name".into(), + instances::normalize_identifier(&name.spelling), + ]); + } + ExprKind::Member { + expression, + separator, + name, + } if separator == "." || separator == "::" => { + append(*expression, tree, dimensions, rename, kind, fields)?; + if separator == "::" { + *kind = "package"; + } + fields.extend([ + "name".into(), + instances::normalize_identifier(&name.spelling), + ]); + } + ExprKind::Select { + expression, + dimension, + } => { + let DimensionKind::Index(index) = &dimension.kind else { + return Err(unsupported( + "$dumpvars hierarchy selection requires a single constant index", + )); + }; + append(*expression, tree, dimensions, rename, kind, fields)?; + let mut value = constant_binding::bind(*index, tree, dimensions)? + .ok_or_else(|| unsupported("$dumpvars hierarchy index must be constant"))?; + rename(&mut value); + let index = eval_ast_const_expr(&tree.state, &value, &dimensions.const_env) + .ok_or_else(|| { + unsupported("$dumpvars hierarchy index must be a known constant integer") + })?; + fields.extend(["index".into(), index.to_string()]); + } + _ => { + return Err(unsupported( + "$dumpvars selection must be a module or variable name", + )); + } + } + Ok(()) + } + let mut kind = "relative"; + let mut fields = Vec::new(); + append(id, tree, dimensions, rename, &mut kind, &mut fields)?; + // Imports bind declarations, not a module-local spelling. Nested procedural + // declarations shadow these aliases just as they do for value expressions. + if kind == "relative" && fields.len() == 2 && !is_local(&fields[1]) { + let symbols = scope::imported(&tree.state); + if let Some(target) = symbols.aliases.get(&fields[1]) + && let Some((package, name)) = symbols + .state_signals + .iter() + .find(|signal| signal.name() == target) + .and_then(|signal| signal.package_variable()) + { + kind = "package"; + fields = vec!["name".into(), package.into(), "name".into(), name.into()]; + } else if let Ok(unit) = tree.root_unit() + && unit.kind == celox_sv_syntax::UnitKind::Package + && packages::package_variables(&unit.name.spelling, tree)?.contains(&fields[1]) + { + // A package subroutine is later instantiated at its caller, but + // its unqualified package references retain their lexical owner. + kind = "package"; + fields = vec![ + "name".into(), + instances::normalize_identifier(&unit.name.spelling), + "name".into(), + fields[1].clone(), + ]; + } + } + if fields.is_empty() { + return Err(unsupported( + "$dumpvars selection must name a module or variable", + )); + } + // A lexical declaration wins over a root module with the same spelling. + // Keep that decision in metadata: the runtime cannot recover lexical + // binding from an already flattened path or the top module's name. + if kind == "relative" + && (is_local(&fields[1]) || imports::scope_names(tree)?.contains(&fields[1])) + { + kind = "local"; + } + Ok(std::iter::once("celox.dump.path.v1".to_string()) + .chain(std::iter::once(kind.to_string())) + .chain(fields) + .collect::>() + .join("\0")) +} diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 6ebeb00ea0a..43c2066a3d7 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -7,7 +7,7 @@ pub use crate::procedural::{ CaseKind, CaseLabel, EventEdge, LoopKind, ParamDirection, SourceSpan, StmtBase, SystemTaskArg, }; pub use crate::system_functions::{ - ArrayQuery, Callee, MemoryFormat, Radix, Severity, SystemFunction, SystemTask, + ArrayQuery, Callee, MemoryFormat, Radix, Severity, SystemFunction, SystemTask, VcdTask, }; /// A procedural statement of the analyzed IR. diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 064b943d65e..5ded0654667 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -229,6 +229,8 @@ pub enum SystemTask { Write(Radix), /// `$readmemb` and `$readmemh` (21.4). Readmem(MemoryFormat), + /// Value change dump controls (21.7.1). + Vcd(VcdTask), /// File output tasks (21.3). Fclose, Fdisplay(Radix), @@ -242,6 +244,18 @@ pub enum SystemTask { AssertContinue, } +/// Four-state VCD control system tasks (IEEE 1800-2023 21.7.1). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum VcdTask { + File, + Vars, + Flush, + On, + Off, + All, + Limit, +} + /// The severity of `$error`, `$warning` and `$info`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Severity { @@ -293,7 +307,7 @@ impl SystemTask { pub fn is_host_request(self) -> bool { matches!( self, - Self::Fclose | Self::Fdisplay(_) | Self::Fwrite(_) | Self::Writemem(_) + Self::Fclose | Self::Fdisplay(_) | Self::Fwrite(_) | Self::Writemem(_) | Self::Vcd(_) ) } @@ -330,6 +344,13 @@ impl SystemTask { Self::Writemem(MemoryFormat::Hexadecimal) => "$writememh", Self::Readmem(MemoryFormat::Binary) => "$readmemb", Self::Readmem(MemoryFormat::Hexadecimal) => "$readmemh", + Self::Vcd(VcdTask::File) => "$dumpfile", + Self::Vcd(VcdTask::Vars) => "$dumpvars", + Self::Vcd(VcdTask::Flush) => "$dumpflush", + Self::Vcd(VcdTask::On) => "$dumpon", + Self::Vcd(VcdTask::Off) => "$dumpoff", + Self::Vcd(VcdTask::All) => "$dumpall", + Self::Vcd(VcdTask::Limit) => "$dumplimit", Self::Assert => "$assert", Self::AssertContinue => "$assert_continue", } @@ -839,13 +860,48 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ function(SystemFunction::TestPlusargs, 1, Some(1)), function(SystemFunction::ValuePlusargs, 2, Some(2)), // 21.7 Value change dump (VCD) files - unsupported("$dumpfile", Task), - unsupported("$dumpvars", Task), - unsupported("$dumpoff", Task), - unsupported("$dumpon", Task), - unsupported("$dumpall", Task), - unsupported("$dumplimit", Task), - unsupported("$dumpflush", Task), + task( + SystemTask::Vcd(VcdTask::File), + ProceduralAndInitial, + 0, + Some(1), + ), + task( + SystemTask::Vcd(VcdTask::Vars), + ProceduralAndInitial, + 0, + None, + ), + task( + SystemTask::Vcd(VcdTask::Off), + ProceduralAndInitial, + 0, + Some(0), + ), + task( + SystemTask::Vcd(VcdTask::On), + ProceduralAndInitial, + 0, + Some(0), + ), + task( + SystemTask::Vcd(VcdTask::All), + ProceduralAndInitial, + 0, + Some(0), + ), + task( + SystemTask::Vcd(VcdTask::Limit), + ProceduralAndInitial, + 1, + Some(1), + ), + task( + SystemTask::Vcd(VcdTask::Flush), + ProceduralAndInitial, + 0, + Some(0), + ), unsupported("$dumpports", Task), unsupported("$dumpportsoff", Task), unsupported("$dumpportson", Task), diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 9b88368edf0..608c8c4bc75 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 = 18; +const CONTAINER_VERSION: u16 = 19; 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/component.rs b/crates/celox/src/component.rs index be5f2b0a622..9091f8e1f52 100644 --- a/crates/celox/src/component.rs +++ b/crates/celox/src/component.rs @@ -920,6 +920,92 @@ pub(crate) fn host_bits(value: &HostValue) -> Option<(num_bigint::BigUint, u32)> mod tests { use super::*; + #[cfg(feature = "systemverilog")] + #[test] + fn source_vcd_filters_injected_component_trace_descriptors_and_values() { + use std::sync::Arc; + struct EmptyModel; + impl InjectedComponentHandler for EmptyModel { + fn call(&self, _: InjectedCall) -> Result { + Ok(InjectedResult::default()) + } + } + for (levels, target, expected_model, expected_other) in [ + (0, "Top.value", false, false), + (0, "Top.other.state", false, true), + (1, "Top", false, false), + (0, "Top", true, true), + (1, "Top.other", false, true), + ] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("component.vcd"); + let source = format!( + r#"module Top(output logic value); + timeunit 1ps; timeprecision 1ps; + initial begin $dumpfile("{}"); $dumpvars({levels}, {target}); value=1; + #1 $dumpall; #1 $dumpoff; #1 $dumpon; end + endmodule"#, + path.display() + ); + let mut simulation = crate::Simulation::from_sv_sources( + vec![(&source, std::path::Path::new("vcd.sv"))], + "Top", + ) + .build_interpreter() + .unwrap(); + let mut definitions = InjectedComponents::new(); + definitions + .insert("model", r#"{"kind":"method_only"}"#, Arc::new(EmptyModel)) + .unwrap(); + for (name, value) in [("model", 1u64), ("other", 42u64)] { + let mut host = HostContext::new(); + host.label = name.into(); + let instance = ExternalInstance::create_injected( + definitions.get("model").unwrap().clone(), + &mut host, + ) + .unwrap(); + host.trace_vars.push(host::HostTraceVar { + name: "state".into(), + width: 8, + words: vec![value], + }); + simulation + .simulator + .components + .components + .push(LiveComponent { + name: name.into(), + instance, + host, + inputs: Vec::new(), + outputs: Vec::new(), + events: Vec::new(), + fire_count: 0, + }); + } + simulation.run_until(4).unwrap(); + simulation.flush_vcd().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + assert_eq!( + text.contains("$scope module Top.model $end"), + expected_model, + "{target}: {text}" + ); + assert_eq!( + text.contains("$scope module Top.other $end"), + expected_other, + "{target}: {text}" + ); + if expected_other { + assert!( + text.contains("b101010 "), + "wrong external value subset for {target}: {text}" + ); + } + } + } + #[test] fn manifest_without_parameters_rejects_supplied_parameter() { let manifest = veryl_metadata::ComponentManifest::parse(r#"{"kind":"method_only"}"#) diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index 563b6ad66c4..89dd6f342ef 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -207,6 +207,12 @@ impl RuntimeDesign { self.instances.values() } + /// Package state has its own scope and is not a child of the top module. + #[cfg(feature = "host-runtime")] + pub(crate) fn is_package_instance(&self, id: InstanceId) -> bool { + self.package_instances.contains(&id) + } + pub fn instance(&self, id: InstanceId) -> Option<&RuntimeInstance> { self.instances.get(&id) } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index a1dabb941c0..498bf262948 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -11,6 +11,8 @@ use celox_runtime::{ UnitExecutor, host_watch, }; +mod vcd_tasks; + /// Saved state of a [`Simulation`], created by [`Simulation::checkpoint`]: /// the design state together with simulation time, clocks and pending events. pub struct SimulationCheckpoint { @@ -124,9 +126,7 @@ impl UnitExecutor for Simulator { self.run_plusargs_request(request, timestamp) } celox_design::HostRequestKind::FileIo => self.run_file_io_request(request, timestamp), - celox_design::HostRequestKind::Vcd => { - Err(celox_runtime::SimulatorErrorCode::InternalError.into()) - } + celox_design::HostRequestKind::Vcd => self.run_vcd_request(request, timestamp), } } } @@ -148,6 +148,23 @@ impl HostBoundary for Simulator { self.frozen = true; } + fn flush_output(&mut self) -> Result<(), RuntimeErrorCode> { + if self.sv_vcd.started.is_some() { + self.flush_vcd() + .map_err(|error| RuntimeErrorCode::Runtime { + message: format!("VCD flush at finish failed: {error}"), + signals: Vec::new(), + })?; + } + Ok(()) + } + + fn try_freeze(&mut self) -> Result<(), RuntimeErrorCode> { + let output = self.flush_output(); + self.freeze(); + output + } + fn stage_external_event( &mut self, event: B::Event, @@ -180,6 +197,28 @@ impl HostBoundary for Simulator { self.dirty = false; self.dump_unless_rewound(timestamp); } + + fn try_finish_timed_step(&mut self, timestamp: u64) -> Result<(), Halt> { + self.start_sv_vcd(timestamp).map_err(|error| { + Halt::Error(RuntimeErrorCode::Runtime { + message: format!("VCD setup failed: {error}"), + signals: Vec::new(), + }) + })?; + self.dirty = false; + self.try_dump_unless_rewound(timestamp) + .map_err(|error| Halt::Error(vcd_dump_runtime_error(error))) + } +} + +fn vcd_dump_runtime_error(error: crate::simulator::DumpError) -> RuntimeErrorCode { + match error { + crate::simulator::DumpError::Runtime(error) => error, + crate::simulator::DumpError::Io(error) => RuntimeErrorCode::Runtime { + message: format!("VCD dump failed: {error}"), + signals: Vec::new(), + }, + } } impl Simulator { @@ -278,7 +317,7 @@ impl Simulation { } let mut file = self.simulator.save_state()?; // Settling for the file may have executed a `$finish`. - self.sync_finish(); + self.sync_finish_checked().map_err(StateError::Runtime)?; let parts = self.state.export_schedule(&self.simulator.backend); let mut record = self.simulator.name_schedule(parts); record.processes.host_writes = self.simulator.name_host_writes(); @@ -333,10 +372,23 @@ impl Simulation { /// A `$finish` that flip-flop or combinational code executed outside a /// step, during a direct settle, read or dump, ends the simulation too. - fn sync_finish(&mut self) { + fn sync_finish_checked(&mut self) -> Result<(), RuntimeErrorCode> { if !self.state.is_finished() && self.simulator.take_runtime_finish() { - self.state.finish(&mut self.simulator); + self.state.finalize_terminal(&mut self.simulator)?; } + Ok(()) + } + + /// Publish diagnostic state without replacing a primary evaluation error + /// or freezing a simulation whose caller may recover. + fn flush_error_output(&mut self) { + let _ = self.simulator.try_finish_timed_step(self.state.time()); + let _ = self.simulator.flush_output(); + } + + fn sync_finish(&mut self) { + self.sync_finish_checked() + .unwrap_or_else(|error| panic!("simulation finish failed: {error}")); } /// Captures the current state of all signals and writes them to the VCD file. @@ -348,8 +400,12 @@ impl Simulation { /// See [`Simulator::try_dump`]. pub fn try_dump(&mut self, timestamp: u64) -> Result<(), crate::simulator::DumpError> { let result = self.simulator.try_dump(timestamp); - self.sync_finish(); - result + let finished = self.sync_finish_checked(); + if matches!(&result, Err(crate::simulator::DumpError::Runtime(_))) { + self.flush_error_output(); + } + result?; + finished.map_err(crate::simulator::DumpError::Runtime) } /// See [`Simulator::switch_vcd`]. @@ -396,8 +452,9 @@ impl Simulation { F: FnOnce(&mut crate::IOContext), { let result = self.simulator.modify(f); - self.sync_finish(); + let finished = self.sync_finish_checked(); result?; + finished?; let logged = self.simulator.host_watch.has_log(); self.state.note_host_writes(&self.simulator.backend, logged); Ok(()) @@ -470,7 +527,12 @@ impl Simulation { } self.state .advance_time(&mut self.simulator.backend, end_time); - self.simulator.dump_unless_rewound(end_time); + if let Err(error) = self.simulator.try_dump_unless_rewound(end_time) { + if matches!(&error, crate::simulator::DumpError::Runtime(_)) { + self.flush_error_output(); + } + return Err(vcd_dump_runtime_error(error)); + } Ok(()) } @@ -545,8 +607,12 @@ impl Simulation { /// Directly execute combinational logic evaluation. pub fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { let result = self.simulator.eval_comb(); - self.sync_finish(); - result + let finished = self.sync_finish_checked(); + if result.is_err() { + self.flush_error_output(); + } + result?; + finished } /// Returns a raw pointer to the backend memory and its total size in bytes. diff --git a/crates/celox/src/simulation/vcd_tasks.rs b/crates/celox/src/simulation/vcd_tasks.rs new file mode 100644 index 00000000000..3700f2439ef --- /dev/null +++ b/crates/celox/src/simulation/vcd_tasks.rs @@ -0,0 +1,532 @@ +//! Host-side execution of IEEE 1800-2023 21.7.1 VCD tasks. +use crate::ir::SignalRef; +use crate::{Simulator, backend::SimBackend}; +use celox_design::HostRequestSite; +use celox_runtime::Halt; +use num_traits::{ToPrimitive, Zero}; + +impl Simulator { + pub(crate) fn run_vcd_request( + &mut self, + site: &HostRequestSite, + timestamp: u64, + ) -> Result<(), Halt> { + // VcdTask discriminants are stable within one compiled artifact. + let result = self.vcd_request(site, timestamp); + result.map_err(|message| { + Halt::Error(crate::RuntimeErrorCode::Runtime { + message, + signals: Vec::new(), + }) + }) + } + + fn vcd_request( + &mut self, + site: &HostRequestSite, + timestamp: u64, + ) -> Result<(), String> { + let mut args = Vec::new(); + for arg in &site.args { + let (value, mask) = self.backend.get_four_state(arg.id); + if !mask.is_zero() { + return Err("VCD task argument contains x or z".into()); + } + if matches!(site.operation, 1 | 6) + && arg.signed + && arg.width > 0 + && value.bit((arg.width - 1) as u64) + { + return Err("VCD depth and size arguments must be nonnegative".into()); + } + args.push(value); + } + let io_error = |error: std::io::Error| format!("VCD task failed: {error}"); + match site.operation { + 0 => { + if self.sv_vcd.started.is_some() { + return Err("$dumpfile must execute before $dumpvars".into()); + } + let path = args + .first() + .map(|arg| { + let bytes = arg + .to_bytes_be() + .into_iter() + .skip_while(|byte| *byte == 0) + .collect::>(); + if bytes.contains(&0) { + return Err("$dumpfile filename contains a NUL byte".to_string()); + } + String::from_utf8(bytes) + .map_err(|_| "$dumpfile filename is not UTF-8".to_string()) + }) + .transpose()? + .unwrap_or_else(|| "dump.vcd".into()); + self.sv_vcd.path = Some(path.into()); + } + 1 => { + if self.sv_vcd.started.is_some_and(|time| time != timestamp) { + return Err( + "all $dumpvars calls must execute at the same simulation time".into(), + ); + } + let levels = args + .first() + .map(|value| { + value + .to_usize() + .ok_or("$dumpvars levels exceeds host range".to_string()) + }) + .transpose()? + .unwrap_or(0); + let owner = self + .program + .runtime_schema + .processes + .get(site.process) + .and_then(|slots| { + self.program + .design + .instances() + .find(|instance| instance.state_addresses().contains(&slots.resume)) + }) + .ok_or("$dumpvars process has no owning instance")?; + let top_name = self + .program + .design + .instances() + .find(|instance| instance.path.0.is_empty()) + .map(|instance| instance.module_name.clone()) + .unwrap_or_else(|| "top".into()); + let top = DumpComponent::name(top_name.clone()); + let owner_components = instance_dump_components(owner, &top); + let targets = if site.strings.is_empty() { + vec![DumpTarget { + package: false, + components: if args.is_empty() { + vec![top.clone()] + } else { + owner_components.clone() + }, + }] + } else { + site.strings + .iter() + .map(|name| decode_dump_target(name, &top, &owner_components)) + .collect::, _>>()? + }; + let mut descs = Vec::new(); + for instance in self.program.design.instances() { + let package = self.program.design.is_package_instance(instance.id); + let path = instance.display_path.join("."); + let scope = if package { + path.clone() + } else if path.is_empty() { + top_name.clone() + } else { + format!("{top_name}.{path}") + }; + let scope_components = if package { + vec![DumpComponent::name( + path.strip_suffix("::").unwrap_or(&path).to_string(), + )] + } else { + instance_dump_components(instance, &top) + }; + for address in instance.state_addresses() { + let Some(variable) = self.program.design.variable(address) else { + continue; + }; + if !instance.resolves_path_to(&variable.path, variable.address) { + continue; + } + let name = variable.path.join("."); + // resolves_path_to above uses the frontend's module-affiliation + // metadata; hidden compiler slots are absent from that index. + let variable_components = variable + .path + .iter() + .flat_map(|part| generated_dump_components(part)) + .collect::>(); + let selected = if package && args.is_empty() && site.strings.is_empty() { + true + } else { + dump_target_matches( + &scope_components, + &variable_components, + package, + &targets, + levels, + ) + }; + if !selected { + continue; + } + let signal = self.backend.resolve_signal(address); + if signal + .array_layout + .is_some_and(|array| array.element_stride * 8 != array.element_width) + { + return Err("$dumpvars requires packed array storage".into()); + } + descs.push(crate::VcdSignalDesc { + scope: scope.clone(), + name, + offset: signal.offset, + width: signal.width, + is_4state: self.backend.layout().four_state && signal.is_4state, + }); + } + } + let mut external = Vec::new(); + for (index, mut desc) in self.components.trace_descriptors().into_iter().enumerate() + { + if desc.scope != top_name && !desc.scope.starts_with(&format!("{top_name}.")) { + desc.scope = format!("{top_name}.{}", desc.scope); + } + if dump_target_matches( + &generated_dump_components(&desc.scope), + &generated_dump_components(&desc.name), + false, + &targets, + levels, + ) { + external.push((index, desc)); + } + } + if descs.is_empty() && external.is_empty() { + return Err("$dumpvars selection matches no dumpable variables".into()); + } + for desc in descs { + if !self + .sv_vcd + .selections + .iter() + .any(|old| old.scope == desc.scope && old.name == desc.name) + { + self.sv_vcd.selections.push(desc); + } + } + for (index, desc) in external { + if !self + .sv_vcd + .external_selections + .iter() + .any(|(old, _)| *old == index) + { + self.sv_vcd.external_selections.push((index, desc)); + } + } + self.sv_vcd.started = Some(timestamp); + self.sv_vcd.pending = true; + } + 2 => self.flush_vcd().map_err(io_error)?, + 3..=5 => { + let command = match site.operation { + 3 => "dumpon", + 4 => "dumpoff", + _ => "dumpall", + }; + self.sv_vcd.suspended = + site.operation == 4 || (site.operation == 5 && self.sv_vcd.suspended); + let external = self.vcd_external_values(); + let (ptr, size) = self.backend.memory_as_ptr(); + // SAFETY: backend execution is suspended at this host boundary. + let memory = unsafe { std::slice::from_raw_parts(ptr, size) }; + if let Some(writer) = self.vcd_writer.as_mut() { + writer + .checkpoint(command, timestamp, memory, &external) + .map_err(io_error)?; + } + } + 6 => { + self.sv_vcd.limit = args + .first() + .and_then(ToPrimitive::to_u64) + .ok_or("$dumplimit requires a nonnegative 64-bit size")?; + if let Some(writer) = self.vcd_writer.as_mut() { + writer.set_byte_limit(self.sv_vcd.limit); + } + } + _ => return Err("unknown VCD task operation".into()), + } + Ok(()) + } + + fn source_vcd_external_values(&self) -> Vec<(num_bigint::BigUint, num_bigint::BigUint)> { + let values = self.components.trace_values(); + self.sv_vcd + .external_selections + .iter() + .map(|(index, _)| values[*index].clone()) + .collect() + } + + pub(crate) fn vcd_external_values(&self) -> Vec<(num_bigint::BigUint, num_bigint::BigUint)> { + if self.sv_vcd.source_writer { + let values = self.components.trace_values(); + self.sv_vcd + .active_external_indices + .iter() + .map(|index| values[*index].clone()) + .collect() + } else { + self.components.trace_values() + } + } + + pub(crate) fn start_sv_vcd(&mut self, timestamp: u64) -> std::io::Result<()> { + if !self.sv_vcd.pending { + return Ok(()); + } + let path = self + .sv_vcd + .path + .as_deref() + .unwrap_or_else(|| std::path::Path::new("dump.vcd")); + // Retire the buffered stream before File::create can truncate the + // same path. Dropping the old handle later must not publish stale bytes. + if let Some(old) = self.vcd_writer.as_mut() { + old.flush()?; + } + self.vcd_writer = None; + let mut writer = crate::VcdWriter::new_with_time_precision( + path, + &self.sv_vcd.selections, + self.program.design.time_precision, + )?; + writer.set_byte_limit(self.sv_vcd.limit); + let external_descs = self + .sv_vcd + .external_selections + .iter() + .map(|(_, desc)| desc.clone()) + .collect::>(); + writer.add_external_signals(&external_descs)?; + if self.sv_vcd.suspended { + let (ptr, size) = self.backend.memory_as_ptr(); + let memory = unsafe { std::slice::from_raw_parts(ptr, size) }; + writer.checkpoint( + "dumpoff", + timestamp, + memory, + &self.source_vcd_external_values(), + )?; + } + self.vcd_writer = Some(writer); + self.sv_vcd.source_writer = true; + self.sv_vcd.active_external_indices = self + .sv_vcd + .external_selections + .iter() + .map(|(index, _)| *index) + .collect(); + self.sv_vcd.pending = false; + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct DumpComponent { + name: String, + indices: Vec, +} + +impl DumpComponent { + fn name(name: String) -> Self { + Self { + name, + indices: Vec::new(), + } + } +} + +struct DumpTarget { + package: bool, + components: Vec, +} + +// Generated hierarchy names may combine scopes (g[0].u). Escaped authored +// names remain one component, including any punctuation in their spelling. +fn generated_dump_components(text: &str) -> Vec { + let mut components = Vec::new(); + let mut rest = text; + while !rest.is_empty() { + if rest.starts_with('\\') { + components.push(DumpComponent::name(rest.to_string())); + break; + } + let end = rest.find(['.', '[']).unwrap_or(rest.len()); + if end == 0 { + return vec![DumpComponent::name(text.to_string())]; + } + let mut component = DumpComponent::name(rest[..end].to_string()); + rest = &rest[end..]; + while let Some(indexed) = rest.strip_prefix('[') { + let Some(end) = indexed.find(']') else { + return vec![DumpComponent::name(text.to_string())]; + }; + let Ok(index) = indexed[..end].parse::() else { + return vec![DumpComponent::name(text.to_string())]; + }; + component.indices.push(index); + rest = &indexed[end + 1..]; + } + components.push(component); + if let Some(next) = rest.strip_prefix('.') { + rest = next; + } else if !rest.is_empty() { + return vec![DumpComponent::name(text.to_string())]; + } + } + components +} + +fn instance_dump_components( + instance: &crate::ir::RuntimeInstance, + top: &DumpComponent, +) -> Vec { + let mut components = vec![top.clone()]; + for ((name, _), display) in instance.path.0.iter().zip(&instance.display_path) { + let mut part = generated_dump_components(name); + // The authored name and its indexed display name are separate in + // metadata, so an escaped literal bracket cannot become an index. + if let Some(suffix) = display + .strip_prefix(name) + .filter(|suffix| !suffix.is_empty()) + { + let indexed = generated_dump_components(&format!("instance{suffix}")); + if let (Some(last), Some(indices)) = (part.last_mut(), indexed.first()) { + last.indices.extend_from_slice(&indices.indices); + } + } + components.extend(part); + } + components +} + +fn decode_dump_target( + text: &str, + top: &DumpComponent, + owner: &[DumpComponent], +) -> Result { + let mut fields = text.split('\0'); + let (kind, mut components) = if fields.next() == Some("celox.dump.path.v1") { + let kind = fields.next().ok_or("invalid $dumpvars path metadata")?; + let mut components: Vec = Vec::new(); + while let Some(tag) = fields.next() { + let value = fields.next().ok_or("invalid $dumpvars path metadata")?; + match tag { + "name" => components.push(DumpComponent::name(value.to_string())), + "index" => components + .last_mut() + .ok_or("invalid $dumpvars index metadata")? + .indices + .push( + value + .parse() + .map_err(|_| "invalid $dumpvars index metadata")?, + ), + _ => return Err("invalid $dumpvars path metadata".into()), + } + } + (kind, components) + } else { + // Existing plain site metadata remains readable by this runtime. + if let Some(absolute) = text.strip_prefix("$root.") { + ("absolute", generated_dump_components(absolute)) + } else if let Some((package, variable)) = text.split_once("::") { + let mut components = vec![DumpComponent::name(package.to_string())]; + components.extend(generated_dump_components(variable)); + ("package", components) + } else { + ("relative", generated_dump_components(text)) + } + }; + if !matches!(kind, "relative" | "local" | "absolute" | "package") { + return Err("invalid $dumpvars path kind metadata".into()); + } + if components.is_empty() { + return Err("$dumpvars selection is empty".into()); + } + if kind == "local" || (kind == "relative" && components.first() != Some(top)) { + let mut qualified = owner.to_vec(); + qualified.extend(components); + components = qualified; + } + Ok(DumpTarget { + package: kind == "package", + components, + }) +} + +fn dump_target_matches( + scope: &[DumpComponent], + variable: &[DumpComponent], + package: bool, + targets: &[DumpTarget], + levels: usize, +) -> bool { + let full = scope.iter().chain(variable).cloned().collect::>(); + targets.iter().any(|target| { + if target.package != package { + return false; + } + if full == target.components { + return true; + } + if package { + return false; + } + if scope.starts_with(&target.components) { + return levels == 0 || scope.len() - target.components.len() < levels; + } + // A named generate scope may own variables without a child module. + let variable_scope = &full[..full.len().saturating_sub(1)]; + target.components.len() > scope.len() + && variable_scope.starts_with(&target.components) + && (levels == 0 || variable_scope.len() - target.components.len() < levels) + }) +} + +#[cfg(all(test, feature = "systemverilog"))] +mod tests { + #[test] + fn relaxed_limit_rescans_consumed_backend_writes() { + for new_limit in [0, 1_000_000] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("resume.vcd"); + let source = "module Top(output logic [3:0] value); initial value=0; endmodule"; + let mut simulation = crate::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("vcd.sv"))], + "Top", + ) + .vcd(&path) + .build() + .unwrap(); + simulation.run_until(0).unwrap(); + simulation + .simulator + .vcd_writer + .as_mut() + .unwrap() + .set_byte_limit(1); + let value = simulation.signal("value"); + simulation.modify(|io| io.set(value, 3u8)).unwrap(); + simulation.run_until(1).unwrap(); + // Limit changes made by the host do not themselves dirty a group, + // so this exercises the empty activity list on resumption. + simulation + .simulator + .vcd_writer + .as_mut() + .unwrap() + .set_byte_limit(new_limit); + simulation.run_until(2).unwrap(); + simulation.flush_vcd().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + assert!(text.contains("#2\nb11 "), "limit {new_limit}: {text}"); + } + } +} diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index a7636bdcf46..dceaed1f6bc 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -59,6 +59,19 @@ mod host { }; use num_bigint::BigUint; + #[derive(Default)] + pub(crate) struct SvVcdControl { + pub path: Option, + pub started: Option, + pub pending: bool, + pub selections: Vec, + pub external_selections: Vec<(usize, celox_runtime::VcdExternalSignalDesc)>, + pub source_writer: bool, + pub active_external_indices: Vec, + pub limit: u64, + pub suspended: bool, + } + /// Hierarchical instance tree with resolved signals. #[derive(Debug, Clone)] pub struct InstanceHierarchy { @@ -109,6 +122,7 @@ mod host { /// The program's scheduling facts. pub(crate) schedule: celox_design::schedule::ScheduleModel, pub(crate) vcd_writer: Option, + pub(crate) sv_vcd: SvVcdControl, pub(crate) dirty: bool, pub(crate) warnings: Vec, pub(crate) components: crate::component::ComponentRuntime, @@ -788,6 +802,7 @@ mod host { program, schedule, vcd_writer: None, + sv_vcd: SvVcdControl::default(), dirty: false, warnings, testbench_strings: Default::default(), @@ -1266,7 +1281,7 @@ mod host { self.eval_comb_checked().map_err(DumpError::Runtime)?; self.dirty = false; } - let component_traces = self.components.trace_values(); + let component_traces = self.vcd_external_values(); if let Some(ref mut writer) = self.vcd_writer { writer .dump_backend(timestamp, &mut self.backend, &component_traces) @@ -1288,6 +1303,19 @@ mod host { } } + pub(crate) fn try_dump_unless_rewound(&mut self, timestamp: u64) -> Result<(), DumpError> { + let rewound = self + .vcd_writer + .as_ref() + .and_then(|writer| writer.last_timestamp()) + .is_some_and(|last| timestamp < last); + if rewound { + Ok(()) + } else { + self.try_dump(timestamp) + } + } + /// Reject a return to `time` if the VCD file has already passed it. pub(crate) fn check_vcd_rewind(&self, time: u64) -> Result<(), CheckpointError> { match self diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index a545b696018..a1690891b03 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1553,6 +1553,17 @@ mod host { fn validate_untimed_host_requests( program: &crate::ir::RuntimeProgram, ) -> Result<(), SimulatorError> { + if program + .runtime_schema + .host_request_sites + .iter() + .any(|site| site.kind == celox_design::HostRequestKind::Vcd) + { + return Err(SimulatorError::from(crate::RuntimeErrorCode::Runtime { + message: "source VCD controls require Simulation; Simulator does not execute initial process kernels".into(), + signals: Vec::new(), + })); + } if program .runtime_schema .processes @@ -1565,7 +1576,7 @@ mod host { .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(), + message: "edge procedures using system file I/O, plusargs, or VCD controls require Simulation; Simulator does not execute scheduled process kernels".into(), signals: Vec::new(), })); } @@ -1590,7 +1601,13 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); - if vcd_path.is_some() { + let source_vcd = sim + .program + .runtime_schema + .host_request_sites + .iter() + .any(|site| site.kind == celox_design::HostRequestKind::Vcd); + if vcd_path.is_some() || source_vcd { if sim.layout().unpacked_arrays.values().any(|array| { !array.element_width.is_multiple_of(8) || array.element_stride != array.element_width / 8 @@ -2549,11 +2566,24 @@ mod host { tracing::debug!("[phase-timing] compile_to_sir: {:?}", start.elapsed()); } + // A source request can originate in an include or mixed-language + // child. Decide from the elaborated schema before physical layout. + let vcd_recording = self.vcd_path.is_some() + || program + .runtime_schema + .host_request_sites + .iter() + .any(|site| site.kind == celox_design::HostRequestKind::Vcd); + let layout_mode = if vcd_recording { + crate::backend::memory_layout::MemoryLayoutMode::Packed + } else { + layout_mode + }; // Build memory layout (consumes semantic layout requirements). let layout_start = phase_timing.then(crate::timing::now); let mut laid_out = program.into_laid_out_with_mode(self.options.four_state, layout_mode); - if self.vcd_path.is_some() { + if vcd_recording { laid_out.enable_vcd_tracking(); } if let Some(start) = layout_start { @@ -3187,10 +3217,21 @@ mod host { .map_err(|error| error.apply_diagnostic_policy(&self.options.diagnostic_policy)); let sim_res = program_res.and_then(|(program, mut warnings)| { self.options.diagnostic_policy.apply(&mut warnings)?; + let vcd_recording = self.vcd_path.is_some() + || program + .runtime_schema + .host_request_sites + .iter() + .any(|site| site.kind == celox_design::HostRequestKind::Vcd); + let layout_mode = if vcd_recording { + crate::backend::memory_layout::MemoryLayoutMode::Packed + } else { + layout_mode + }; 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() { + if vcd_recording { laid_out.enable_vcd_tracking(); } @@ -3468,6 +3509,69 @@ mod host { Ok(()) } + #[cfg(all( + test, + feature = "systemverilog", + any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) + ) + ))] + #[test] + fn typed_vcd_selections_survive_native_image_roundtrip() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("native.vcd"); + let source = format!( + r#" + package p; logic state=1; endpackage + module Child(output logic \state.value ); initial \state.value = 1; endmodule + module Top #(parameter int INDEX=1) (output logic [1:0] bus, output logic \literal[0] ); + Child u[0:1](bus); + logic package_use; + assign package_use=p::state; + assign \literal[0] = 0; + initial begin $dumpfile("{}"); + $dumpvars(0, Top.u[INDEX].\state.value , p::state, \literal[0] ); + end + endmodule"#, + path.display() + ); + let (program, warnings, options, _, _) = crate::Simulation::from_sv_sources( + vec![(&source, std::path::Path::new("native-vcd.sv"))], + "Top", + ) + .into_laid_out_program(crate::MemoryLayoutMode::Packed) + .unwrap(); + let image = + crate::backend::native::NativeBackend::compile_image(&program, &options).unwrap(); + let image = + crate::NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()) + .unwrap(); + let runtime = image.runtime_program(); + assert!( + runtime + .runtime_schema + .host_request_sites + .iter() + .flat_map(|site| &site.strings) + .any(|path| path.contains("\0local\0")) + ); + // SAFETY: the image was compiled from this test's trusted source. + let backend = unsafe { crate::backend::native::NativeBackend::from_image(image) }.unwrap(); + let mut simulator = + crate::Simulator::with_backend_and_program_for_simulation(backend, runtime, warnings); + simulator.apply_initial_values(); + simulator.modify(|_| {}).unwrap(); + let mut simulation = crate::Simulation::new(simulator); + simulation.run_until(1).unwrap(); + simulation.flush_vcd().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + assert_eq!(text.matches("$var wire ").count(), 3, "{text}"); + assert!(text.contains("Top.u[1]"), "{text}"); + assert!(text.contains("\\state.value"), "{text}"); + assert!(text.contains("\\literal[0]"), "{text}"); + } + /// Resolve user-specified `(instance_path, var_path)` to `AbsoluteAddr` and run DSE. fn run_dead_store_elimination( program: &mut LaidOutProgram, @@ -3476,6 +3580,21 @@ mod host { ) { use crate::HashSet; let mut externally_live = HashSet::default(); + if program + .runtime_schema + .host_request_sites + .iter() + .any(|site| site.kind == celox_design::HostRequestKind::Vcd) + { + // A runtime hierarchy selection may observe every authored object. + externally_live.extend( + program + .design + .instances() + .flat_map(|instance| instance.state_addresses().iter().copied()), + ); + } + // 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 203cca1ce9e..b5a16a235a5 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -123,10 +123,10 @@ 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 + /// Source-driven files and waveform controls 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" + "checkpoints and state files are not supported for designs with SystemVerilog file I/O or VCD control tasks" )] ExternalSystemTasks, #[error("the checkpoint was taken from a different design")] @@ -210,7 +210,12 @@ impl Simulator { .runtime_schema .host_request_sites .iter() - .any(|site| matches!(site.kind, celox_design::HostRequestKind::FileIo)) + .any(|site| { + matches!( + site.kind, + celox_design::HostRequestKind::FileIo | celox_design::HostRequestKind::Vcd + ) + }) { return Err(CheckpointError::ExternalSystemTasks); } diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 86bbbee169b..4a0960a7a7c 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -1810,8 +1810,8 @@ fn reports_where_a_known_system_function_is_not_supported() { endmodule", ), ( - "system task `$dumpvars`", - "module Top(output logic y); initial $dumpvars; assign y = 0; endmodule", + "system task `$dumpports`", + "module Top(output logic y); initial $dumpports; assign y = 0; endmodule", ), ( "system task `$stacktrace`", diff --git a/crates/celox/tests/sv_host_requests.rs b/crates/celox/tests/sv_host_requests.rs index ed74e5e2ef5..9c0263d47b7 100644 --- a/crates/celox/tests/sv_host_requests.rs +++ b/crates/celox/tests/sv_host_requests.rs @@ -11,7 +11,8 @@ macro_rules! mixed_requests { let directory = tempfile::tempdir().unwrap(); let first = directory.path().join("first.txt"); let second = directory.path().join("second.txt"); - let source = String::from( + let waveform = directory.path().join("trace.vcd"); + let source = format!( r#" module Child #(parameter int ID = 0) (output logic [7:0] value, output logic ok); @@ -38,8 +39,14 @@ macro_rules! mixed_requests { timeunit 1ps; timeprecision 1ps; Child a(a_value, a_ok); Child #(.ID(1)) b(b_value, b_ok); + initial begin + $dumpfile("{}"); + $dumpvars(0, Top); + #2 $dumpflush; + end endmodule "#, + waveform.display() ); let mut simulation = celox::Simulation::from_sv_sources( vec![(&source, Path::new("mixed_host_requests.sv"))], @@ -55,12 +62,16 @@ macro_rules! mixed_requests { .$backend() .unwrap(); simulation.run_until(2).unwrap(); + simulation.flush_vcd().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"); + let trace = std::fs::read_to_string(waveform).unwrap(); + assert!(trace.contains("$dumpvars")); + assert!(trace.contains("#1\n")); } }; } @@ -73,22 +84,25 @@ 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") - ); + for statement in ["$fwrite(1, \"output\");", "$dumpvars;"] { + 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 or VCD") + ); + } } diff --git a/crates/celox/tests/sv_vcd.rs b/crates/celox/tests/sv_vcd.rs new file mode 100644 index 00000000000..0927f6e1097 --- /dev/null +++ b/crates/celox/tests/sv_vcd.rs @@ -0,0 +1,902 @@ +#![cfg(feature = "systemverilog")] +//! Source-driven VCD controls exercise host requests and trace observation. +use celox::{SimBackend, Simulation}; +use std::path::Path; + +fn capture(mut simulation: Simulation, path: &Path) -> String { + simulation.run_until(4).unwrap(); + simulation.flush_vcd().unwrap(); + std::fs::read_to_string(path).unwrap() +} + +macro_rules! backends { + ($name:ident, $body:expr) => { + mod $name { + use super::*; + #[test] + fn interpreter() { + ($body)("interpreter", 0); + } + #[test] + fn cranelift() { + ($body)("cranelift", 1); + } + #[test] + fn wasm() { + ($body)("wasm", 2); + } + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + #[test] + fn native() { + ($body)("native", 3); + } + } + }; +} + +backends!(controls, |backend: &str, number: usize| { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(format!("{backend}.vcd")); + let source = format!( + r#" + module Top(output logic [3:0] value); + timeunit 1ps; timeprecision 1ps; + initial begin + $dumpfile("{}"); + $dumpvars(0, Top.value); + value = 4'b10xz; + #1 $dumpoff; value = 4'b1111; + #1 $dumpon; + #1 $dumpall; $dumpflush; + end + endmodule + "#, + path.display() + ); + let build = || { + Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top").four_state(true) + }; + let text = match number { + 0 => capture(build().build_interpreter().unwrap(), &path), + 1 => capture(build().build_cranelift().unwrap(), &path), + 2 => capture(build().build_wasm().unwrap(), &path), + _ => capture(build().build_native().unwrap(), &path), + }; + assert!(text.contains("$var wire 4"), "{text}"); + assert!(text.contains("b10xz "), "{text}"); + assert!(text.contains("$dumpoff\nbxxxx "), "{text}"); + assert!(text.contains("$dumpon\nb1111 "), "{text}"); + assert!(text.contains("$dumpall\nb1111 "), "{text}"); + assert!(!text.contains("vcd_argument"), "{text}"); +}); + +#[test] +fn depth_and_multiple_selections() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("hierarchy.vcd"); + let source = format!( + r#" + module Child(output logic child_value); + timeunit 1ps; timeprecision 1ps; + initial child_value = 1; + endmodule + module Top(output logic own_value, output logic child_wire); + timeunit 1ps; timeprecision 1ps; + Child child(.child_value(child_wire)); + initial begin + $dumpfile("{}"); + $dumpvars(1, Top); + $dumpvars(0, Top.child.child_value); + own_value = 1; + end + endmodule + "#, + path.display() + ); + let sim = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let text = capture(sim, &path); + assert!(text.contains("own_value"), "{text}"); + assert!(text.contains("child_value"), "{text}"); +} + +#[test] +fn later_dumpvars_reports_runtime_error() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("late.vcd"); + let source = format!( + r#"module Top(output logic value); + timeunit 1ps; timeprecision 1ps; + initial begin $dumpfile("{}"); $dumpvars; #1 $dumpvars; end + endmodule"#, + path.display() + ); + let mut sim = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let error = sim.run_until(2).unwrap_err(); + assert!(format!("{error:?}").contains("same simulation time")); +} + +#[test] +fn source_controls_keep_packed_array_storage_native() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("array.vcd"); + let source = format!( + r#"module Top(output logic done); + timeunit 1ps; timeprecision 1ps; + logic [4:0] memory [0:1]; + initial begin + $dumpfile("{}"); $dumpvars(0, Top.memory); + memory[0] = 5'h03; memory[1] = 5'h15; done = 1; + end + endmodule"#, + path.display() + ); + let sim = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build() + .unwrap(); + let text = capture(sim, &path); + assert!(text.contains("$var wire 10"), "{text}"); + assert!(text.contains("memory"), "{text}"); + assert!(!text.contains(" done "), "{text}"); +} + +#[test] +fn finish_flushes_source_waveform() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("finish.vcd"); + let source = format!( + r#"module Top(output logic value); + timeunit 1ps; timeprecision 1ps; + initial begin $dumpfile("{}"); $dumpvars; value = 1; $finish; end + endmodule"#, + path.display() + ); + let mut sim = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + sim.run_until(1).unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("value"), "{text}"); + assert!(text.contains("#0\n1"), "{text}"); +} + +#[test] +fn unwritable_source_path_returns_runtime_error() { + let dir = tempfile::tempdir().unwrap(); + // Opening a directory as an output file fails regardless of user privileges. + let source = format!( + r#"module Top(output logic value); + initial begin $dumpfile("{}"); $dumpvars; value = 1; end + endmodule"#, + dir.path().display() + ); + let mut sim = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let error = sim.run_until(1).unwrap_err(); + assert!(format!("{error:?}").contains("VCD setup failed")); +} + +#[test] +fn embedded_filename_nul_is_rejected() { + let source = r#"module Top(output logic value); + initial begin $dumpfile(32'h61006200); $dumpvars; value = 1; end + endmodule"#; + let mut sim = Simulation::from_sv_sources(vec![(source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let error = sim.run_until(1).unwrap_err(); + assert!(format!("{error:?}").contains("NUL byte")); +} + +#[test] +fn authored_internal_looking_names_are_selected() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("authored.vcd"); + let source = format!( + r#"module Top(output logic __celox_user); + initial begin $dumpfile("{}"); $dumpvars(0, Top.__celox_user); __celox_user=1; end + endmodule"#, + path.display() + ); + let simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let text = capture(simulation, &path); + assert!(text.contains(" __celox_user $end"), "{text}"); + assert!(!text.contains("vcd_argument"), "{text}"); +} + +#[test] +fn removing_reached_limit_rescans_stable_values() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("resumed.vcd"); + let source = format!( + r#"module Top(output logic [3:0] value); + timeunit 1ps; timeprecision 1ps; + initial begin + $dumpfile("{}"); $dumpvars; value=0; + #1 $dumplimit(1); value=3; + #1 value=5; + #1 $dumplimit(0); + end endmodule"#, + path.display() + ); + let simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build() + .unwrap(); + let text = capture(simulation, &path); + assert!(text.contains("VCD dump limit reached"), "{text}"); + assert!(text.contains("#3\nb101 "), "{text}"); +} + +#[test] +fn source_replacement_flushes_old_writer_before_truncation() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("same.vcd"); + let source = format!( + r#"module Top(output logic value); + timeunit 1ps; timeprecision 1ps; + initial begin + value=0; + #1 $dumpfile("{}"); $dumpvars(0, Top.value); value=1; + end endmodule"#, + path.display() + ); + let mut simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .vcd(&path) + .build_interpreter() + .unwrap(); + // Populate the old writer's buffer with more bytes than the replacement. + for _ in 0..1000 { + simulation.dump(0); + } + let text = { + simulation.run_until(2).unwrap(); + simulation.flush_vcd().unwrap(); + std::fs::read_to_string(path).unwrap() + }; + assert_eq!(text.matches("$enddefinitions").count(), 1, "{text}"); + assert!( + !text.contains("#0"), + "old buffered timestamps survived replacement: {text}" + ); +} + +#[cfg(target_os = "linux")] +#[test] +fn ordinary_timed_write_failure_is_returned() { + let source = r#"module Top(output logic [2097151:0] value); + initial begin $dumpfile("/dev/full"); $dumpvars; value='1; end + endmodule"#; + let mut simulation = Simulation::from_sv_sources(vec![(source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| simulation.run_until(1))); + let error = result + .expect("a timed waveform failure must not panic") + .unwrap_err(); + assert!( + format!("{error:?}").contains("VCD dump failed"), + "{error:?}" + ); +} + +#[test] +fn direct_finish_finalizes_source_waveform() { + for action in ["get", "get_four_state", "eval_comb", "dump"] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("direct.vcd"); + let source = format!( + r#"module Top(input logic stop_now, output logic value); + initial begin $dumpfile("{}"); $dumpvars; end + always_comb begin value=stop_now; if (stop_now) $finish; end + endmodule"#, + path.display() + ); + let mut simulation = + Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(1).unwrap(); + let stop = simulation.signal("stop_now"); + let value = simulation.signal("value"); + simulation.modify(|io| io.set(stop, 1u8)).unwrap(); + match action { + "get" => { + simulation.get(value); + } + "get_four_state" => { + simulation.get_four_state(value); + } + "eval_comb" => simulation.eval_comb().unwrap(), + _ => simulation.try_dump(1).unwrap(), + } + // Read with the simulator alive: finish must flush, independently of Drop. + let text = std::fs::read_to_string(&path).unwrap(); + let last = text.rsplit("#1\n").next().unwrap(); + assert!( + last.lines().any(|line| line.starts_with('1')), + "{action}: {text}" + ); + assert!(simulation.is_finished()); + } +} + +#[test] +fn absolute_root_dump_targets_resolve_from_child_scope() { + for target in ["$root.Top.value", "$root.Top"] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("root.vcd"); + let source = format!( + r#" + module Recorder; + initial begin $dumpfile("{}"); $dumpvars(0, {target}); end + endmodule + module Top(output logic value); + Recorder recorder(); + initial value=1; + endmodule"#, + path.display() + ); + let simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let text = capture(simulation, &path); + assert!(text.contains(" value $end"), "{target}: {text}"); + assert!( + !text.contains("$root"), + "the pseudo-root must not become a VCD scope: {text}" + ); + } +} + +#[test] +fn module_recursive_dump_excludes_package_state() { + for selection in ["$dumpvars(0, Top);", "$dumpvars(0);", "$dumpvars;"] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("package.vcd"); + let source = format!( + r#" + package p; logic [7:0] package_only = 8'd7; endpackage + module Child(output logic [7:0] child_value); + import p::*; + assign child_value=package_only; + endmodule + module Top(output logic [7:0] value, child_value); + import p::*; + Child child(child_value); + assign value=package_only; + initial begin $dumpfile("{}"); {selection} end + endmodule"#, + path.display() + ); + let simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let text = capture(simulation, &path); + assert!(text.contains(" value $end"), "{selection}: {text}"); + assert!(text.contains(" child_value $end"), "{selection}: {text}"); + let package_count = text.matches(" package_only $end").count(); + assert_eq!( + package_count, + usize::from(selection == "$dumpvars;"), + "{selection}: {text}" + ); + assert!( + !text.contains("Top.p::"), + "packages must not appear beneath the top module: {text}" + ); + } +} + +#[test] +fn escaped_dump_identifiers_keep_literal_delimiters() { + for target in [ + r"Top.\a.b ", + r"Top.\array[0] ", + r"Top.\u.x .\state.value ", + r"$root.Top.\u.x .\state.value ", + r"\$root.Top.value ", + ] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("escaped.vcd"); + let source = format!( + r#"module Child(output logic \state.value ); + initial \state.value = 1; + endmodule + module Top(output logic \a.b , \array[0] , \$root.Top.value , child_value); + Child \u.x (child_value); + initial begin \a.b = 1; \array[0] = 0; \$root.Top.value = 1; + $dumpfile("{}"); $dumpvars(0, {target}); end + endmodule"#, + path.display() + ); + let simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let text = capture(simulation, &path); + assert_eq!(text.matches("$var wire ").count(), 1, "{target}: {text}"); + } +} + +#[test] +fn constant_indexed_instance_and_generate_selections() { + for target in [ + "Top.u[INDEX + 0]", + "Top.g[INDEX + 0]", + "Top.g[INDEX].nested.value", + "$root.Top.g[INDEX]", + ] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("indexed.vcd"); + let source = format!( + r#"module Child(output logic value); initial value=1; endmodule + module Top #(parameter int INDEX=1) (output logic [1:0] bus); + Child u[0:1](bus); + for (genvar i=0; i<2; i++) begin:g + logic generated; + initial generated=1; + Child nested(); + end + initial begin $dumpfile("{}"); $dumpvars(0, {target}); end + endmodule"#, + path.display() + ); + let simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let text = capture(simulation, &path); + assert!(text.contains("[1]"), "{target}: {text}"); + assert!(!text.contains("[0]"), "{target}: {text}"); + } +} + +#[test] +fn explicit_package_dump_selects_only_requested_variable() { + for target in ["p::state", r"\p.q ::\state.value "] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("package-select.vcd"); + let source = format!( + r#"package p; logic [7:0] state=7; logic [7:0] other=9; endpackage + package \p.q ; logic \state.value = 1; endpackage + module Recorder; + initial begin $dumpfile("{}"); $dumpvars(0, {target}); end + endmodule + module Top(output logic [7:0] value, output logic escaped_value); + assign value=p::other; + assign escaped_value=\p.q ::\state.value ; + Recorder recorder(); + endmodule"#, + path.display() + ); + let simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let text = capture(simulation, &path); + assert_eq!(text.matches("$var wire ").count(), 1, "{target}: {text}"); + assert!(!text.contains(" other $end"), "{target}: {text}"); + assert!(!text.contains("$scope module Top"), "{target}: {text}"); + } +} + +#[test] +fn initial_vcd_tasks_require_timed_simulation_on_every_backend() { + for task in ["$dumpvars;", "$dumpflush;"] { + let source = format!("module Top; initial begin {task} end endmodule"); + let build = + || celox::Simulator::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top"); + let errors = [ + build().build_interpreter().unwrap_err(), + build().build_cranelift().unwrap_err(), + build().build_wasm().unwrap_err(), + build().build().unwrap_err(), + ]; + for error in errors { + assert!( + format!("{error:?}").contains("source VCD controls require Simulation"), + "{error:?}" + ); + } + } +} + +#[cfg(target_os = "linux")] +#[test] +fn finish_stays_terminal_when_final_waveform_output_fails() { + for width in [1, 2097152] { + let source = format!( + r#"module Top(output logic [{high}:0] value); + initial begin $dumpfile("/dev/full"); $dumpvars; value='1; $finish; end + initial begin #1 value='0; end + endmodule"#, + high = width - 1 + ); + let mut simulation = + Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + assert!(simulation.run_until(2).is_err()); + assert!(simulation.is_finished(), "width={width}"); + let time = simulation.time(); + assert_eq!(simulation.step().unwrap(), None); + simulation.run_until(10).unwrap(); + assert_eq!(simulation.time(), time); + } +} + +#[test] +fn pending_source_waveform_is_finalized_on_fatal_error() { + let dir = tempfile::tempdir().unwrap(); + for path in [ + dir.path().join("fatal.vcd"), + dir.path().join("absent/fatal.vcd"), + ] { + let source = format!( + r#"module Top(output logic value); + initial begin $dumpfile("{}"); $dumpvars; value=1; $fatal(1,"primary failure"); end + endmodule"#, + path.display() + ); + let mut simulation = + Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let error = simulation.run_until(1).unwrap_err(); + assert!( + format!("{error:?}").contains("primary failure"), + "{error:?}" + ); + if path.parent() == Some(dir.path()) { + let text = std::fs::read_to_string(path).unwrap(); + assert!(text.contains("$enddefinitions"), "{text}"); + assert!(text.contains("1!"), "{text}"); + } + } +} + +#[test] +fn host_waveform_switch_keeps_source_suspension_and_limit() { + for control in ["$dumpoff", "$dumplimit(1)"] { + let dir = tempfile::tempdir().unwrap(); + let first = dir.path().join("first.vcd"); + let second = dir.path().join("second.vcd"); + let source = format!( + r#"module Top(output logic value); + timeunit 1ps; timeprecision 1ps; + initial begin $dumpfile("{}"); $dumpvars; value=0; + #1 {}; #1 value=1; #1 $dumpon; $dumplimit(0); #1 value=0; + end endmodule"#, + first.display(), + control + ); + let mut simulation = + Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(1).unwrap(); + simulation.switch_vcd(&second).unwrap(); + simulation.run_until(2).unwrap(); + simulation.flush_vcd().unwrap(); + let paused = std::fs::read_to_string(&second).unwrap(); + if control == "$dumpoff" { + assert!(!paused.contains("#2"), "{control}: {paused}"); + } else { + assert!(paused.contains("VCD dump limit reached"), "{paused}"); + assert!(!paused.contains("1!"), "{paused}"); + } + simulation.run_until(4).unwrap(); + simulation.flush_vcd().unwrap(); + let resumed = std::fs::read_to_string(second).unwrap(); + assert!(resumed.contains("#3"), "{control}: {resumed}"); + assert!(resumed.contains("#4"), "{control}: {resumed}"); + } +} + +#[test] +fn imported_dump_target_follows_package_declaration_and_local_shadowing() { + for (declaration, package) in [ + ("import p::*;", true), + ("import p::state;", true), + ("import p::*; logic state;", false), + ] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("import.vcd"); + let source = format!( + r#"package p; logic state=1; logic other=0; endpackage + module Top; {} initial begin $dumpfile("{}"); $dumpvars(0,state); end endmodule"#, + declaration, + path.display() + ); + let mut simulation = + Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(1).unwrap(); + simulation.flush_vcd().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + assert_eq!(text.matches("$var ").count(), 1, "{text}"); + assert_eq!(text.contains("$scope module p::"), package, "{text}"); + assert!(!text.contains(" other "), "{text}"); + } +} + +#[cfg(target_os = "linux")] +#[test] +fn direct_finish_error_stays_terminal() { + let source = r#"module Top(input logic stop_now, output logic value); + initial begin $dumpfile("/dev/full"); $dumpvars; end + always_comb begin value=stop_now; if(stop_now) $finish; end + endmodule"#; + let mut simulation = Simulation::from_sv_sources(vec![(source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(0).unwrap(); + let stop = simulation.signal("stop_now"); + simulation.modify(|io| io.set(stop, 1u8)).unwrap(); + assert!(simulation.eval_comb().is_err()); + assert!(simulation.is_finished()); + assert_eq!(simulation.step().unwrap(), None); +} + +#[test] +fn imported_escaped_package_delimiters_remain_literal() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("escaped-import.vcd"); + let source = format!( + r#"package \p::q ; logic \state::value =1; endpackage + module Top; import \p::q ::*; + initial begin $dumpfile("{}"); $dumpvars(0,\state::value ); end endmodule"#, + path.display() + ); + let mut simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(1).unwrap(); + simulation.flush_vcd().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + assert_eq!(text.matches("$var ").count(), 1, "{text}"); + assert!(text.contains("\\state::value"), "{text}"); +} + +#[test] +fn scoped_parameter_dump_does_not_select_imported_state() { + let source = r#"package p; logic state=1; endpackage + module Top; import p::*; + initial begin localparam int state=0; $dumpvars(0,state); end endmodule"#; + let mut simulation = Simulation::from_sv_sources(vec![(source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let error = simulation.run_until(1).unwrap_err(); + assert!( + format!("{error:?}").contains("selection matches no dumpable variables"), + "{error:?}" + ); +} + +#[test] +fn direct_fatal_errors_publish_waveform_without_freezing_recovery() { + for action in ["eval_comb", "try_dump"] { + check_direct_fatal_waveform(action); + } +} + +#[test] +fn final_run_until_fatal_publishes_waveform() { + check_direct_fatal_waveform("run_until"); +} + +#[test] +fn final_bounded_run_fatal_publishes_waveform() { + check_direct_fatal_waveform("run_until_bounded"); +} + +fn check_direct_fatal_waveform(action: &str) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("direct-fatal.vcd"); + let source = format!( + r#"module Top(input logic fail_now, output logic value); + initial begin $dumpfile("{}"); $dumpvars(0,Top.value); end + always_comb begin value=fail_now; if(fail_now) $fatal(1,"direct primary"); end + endmodule"#, + path.display() + ); + let mut simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(0).unwrap(); + let fail = simulation.signal("fail_now"); + simulation.modify(|io| io.set(fail, 1u8)).unwrap(); + let error = match action { + "eval_comb" => format!("{:?}", simulation.eval_comb().unwrap_err()), + "try_dump" => format!("{:?}", simulation.try_dump(0).unwrap_err()), + "run_until" => format!("{:?}", simulation.run_until(1).unwrap_err()), + "run_until_bounded" => format!("{:?}", simulation.run_until_bounded(1, 10).unwrap_err()), + _ => unreachable!(), + }; + assert!(error.contains("direct primary"), "{action}: {error}"); + let text = std::fs::read_to_string(path).unwrap(); + assert!(text.contains("1!"), "{action}: {text}"); + simulation.modify(|io| io.set(fail, 0u8)).unwrap(); + simulation.eval_comb().unwrap(); + let value = simulation.signal("value"); + assert_eq!(simulation.get(value), 0u8.into()); + assert!(!simulation.is_finished()); +} + +#[test] +fn package_task_dump_target_keeps_lexical_package_owner() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("package-task.vcd"); + let source = format!( + r#"package p; logic state=1; + task automatic trace(); $dumpvars(0,state); endtask endpackage + module Top; logic state=0; + initial begin $dumpfile("{}"); p::trace(); end endmodule"#, + path.display() + ); + let mut simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(1).unwrap(); + simulation.flush_vcd().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + assert_eq!(text.matches("$var ").count(), 1, "{text}"); + assert!(text.contains("$scope module p::"), "{text}"); + assert!(text.contains("1!"), "{text}"); +} + +#[test] +fn lexical_dump_target_shadows_top_module_name_in_child() { + for declaration in ["logic Top=1;", "Leaf Top();"] { + for selection in ["Top", "$root.Top.root_value"] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("lexical.vcd"); + let source = format!( + r#"module Leaf; logic value=1; endmodule + module Child; {} + initial begin $dumpfile("{}"); $dumpvars(0,{}); end endmodule + module Top; logic root_value=0; Child child(); endmodule"#, + declaration, + path.display(), + selection + ); + let mut simulation = + Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(1).unwrap(); + simulation.flush_vcd().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + assert_eq!( + text.matches("$var ").count(), + 1, + "{declaration}, {selection}: {text}" + ); + if selection == "Top" { + assert!(!text.contains(" root_value "), "{text}"); + assert!(text.contains("1!"), "{text}"); + } else { + assert!(text.contains(" root_value "), "{text}"); + assert!(text.contains("0!"), "{text}"); + } + } + } +} + +#[test] +fn initial_dump_limit_bounds_header_and_resumes_current_snapshot() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("header-limit.vcd"); + let declarations = (0..100) + .map(|i| format!("logic signal_{i}=1;\n")) + .collect::(); + let source = format!( + r#"module Top; timeunit 1ps; timeprecision 1ps; {} + initial begin $dumpfile("{}"); $dumplimit(1); $dumpvars; + #1 $dumpoff; #1 $dumplimit(0); #1 $dumpon; end endmodule"#, + declarations, + path.display() + ); + let mut simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(0).unwrap(); + simulation.flush_vcd().unwrap(); + let paused = std::fs::read_to_string(&path).unwrap(); + assert!( + paused.len() < 128, + "header ignored limit: {} bytes", + paused.len() + ); + assert!(paused.contains("VCD dump limit reached"), "{paused}"); + assert!(!paused.contains("$var "), "{paused}"); + simulation.run_until(2).unwrap(); + simulation.flush_vcd().unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), paused); + simulation.run_until(3).unwrap(); + simulation.flush_vcd().unwrap(); + let resumed = std::fs::read_to_string(path).unwrap(); + assert_eq!(resumed.matches("$date\n").count(), 1, "{resumed}"); + assert_eq!(resumed.matches("$var wire ").count(), 100, "{resumed}"); + assert!(resumed.contains("#3\n$dumpon\n"), "{resumed}"); +} + +#[test] +fn omitted_dump_depth_preserves_explicit_recursive_selections() { + for (selection, count) in [("Top.value", 1), ("Top.child", 2), ("p::state", 1)] { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("omitted-depth.vcd"); + let source = format!( + r#"package p; logic state=1; logic other=0; endpackage + module Grandchild; logic grand_value=1; endmodule + module Child; logic child_value=1; Grandchild grand(); endmodule + module Top; logic value=1; logic package_use; Child child(); + assign package_use=p::other; + initial begin $dumpfile("{}"); $dumpvars(,{}); end endmodule"#, + path.display(), + selection + ); + let mut simulation = + Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(1).unwrap(); + simulation.flush_vcd().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + assert_eq!( + text.matches("$var wire ").count(), + count, + "{selection}: {text}" + ); + assert!(!text.contains(" other "), "{text}"); + if selection == "Top.child" { + assert!(text.contains(" grand_value "), "{text}"); + } + assert_eq!( + text.contains("$scope module p::"), + selection == "p::state", + "{text}" + ); + } +} + +#[test] +fn dumpfile_uses_shared_string_literal_escape_decoding() { + for kind in ["ordinary", "triple", "lf", "crlf", "triple-crlf"] { + let directory = tempfile::tempdir().unwrap(); + let base = directory.path().join("wave"); + let (delimiter, continuation) = match kind { + "triple" => ("\"\"\"", ""), + "lf" => ("\"", "\\\n"), + "crlf" => ("\"", "\\\r\n"), + "triple-crlf" => ("\"\"\"", "\\\r\n"), + _ => ("\"", ""), + }; + let literal = format!( + "{delimiter}{}{continuation}\\056vcd{delimiter}", + base.display() + ); + let source = format!( + "module Top; logic value=1; initial begin $dumpfile({literal}); $dumpvars(0,Top.value); end endmodule" + ); + let mut simulation = + Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(1).unwrap(); + simulation.flush_vcd().unwrap(); + let path = directory.path().join("wave.vcd"); + let text = std::fs::read_to_string(&path) + .unwrap_or_else(|error| panic!("{kind}: {error}, literal={literal:?}")); + assert!(text.contains("1!"), "{kind}: {text}"); + assert_eq!( + std::fs::read_dir(directory.path()).unwrap().count(), + 1, + "{kind}" + ); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 6ebeb90dbc5..10cb245e6b0 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` | -| Runtime I/O | `$test$plusargs`, `$value$plusargs`, `$fopen`, `$fclose`, `$fdisplay` / `$fwrite` and radix variants, `$writememh` / `$writememb` in timed processes | +| Runtime I/O | `$test$plusargs`, `$value$plusargs`, `$fopen`, `$fclose`, `$fdisplay` / `$fwrite` and radix variants, `$writememh` / `$writememb`, and [VCD controls](./vcd#systemverilog-source-controls) in timed processes | | State | two-state and four-state simulation | Every construct above is covered by tests that compare the result with a @@ -367,8 +367,9 @@ 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. +[Source VCD controls](./vcd#systemverilog-source-controls) start recording after +the current timestamp settles. Checkpoints and state files reject designs with +file I/O or source VCD controls, whose host state they cannot capture. ## Time and precision {#time-and-precision} diff --git a/docs/guide/vcd.md b/docs/guide/vcd.md index 7a7ec0549a9..e9d66783d0e 100644 --- a/docs/guide/vcd.md +++ b/docs/guide/vcd.md @@ -59,3 +59,30 @@ sim.dispose(); ## Further Reading - [Writing Tests](./writing-tests.md) -- Simulator and Simulation patterns. + +## SystemVerilog controls {#systemverilog-source-controls} + +A timed SystemVerilog simulation can select and control tracing from HDL: + +```systemverilog +initial begin + $dumpfile("waves.vcd"); + $dumpvars(0, Top); +end +``` + +`$dumpvars` starts recording after the current simulation timestamp settles. +All calls must execute at the same simulation time. A level of `0` includes +all descendants; `1` includes only the named module's own variables. Individual +variables and multiple module or variable selections are supported. + +`$dumpoff` records unknown values and suspends tracing. `$dumpon` records current +values and resumes it. `$dumpall` records every selected value without changing +that state. `$dumpflush` publishes buffered output, and `$dumplimit(bytes)` stops +recording at the size limit with a comment in the file. Complete records may +extend past the limit. A zero limit removes the bound. + +`$dumpfile` accepts a string literal or an integral expression containing the +filename and must run before `$dumpvars`. The default filename is `dump.vcd`. +Source controls enable the necessary trace storage automatically; a host VCD +path is optional. Host waveform methods remain available. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index de6bab59b87..9cb190ed084 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` | -| 実行時 I/O | `$test$plusargs`、`$value$plusargs`、`$fopen`、`$fclose`、`$fdisplay` / `$fwrite` と基数指定形、`$writememh` / `$writememb`。時間を持つプロセスで実行 | +| 実行時 I/O | `$test$plusargs`、`$value$plusargs`、`$fopen`、`$fclose`、`$fdisplay` / `$fwrite` と基数指定形、`$writememh` / `$writememb`、[VCD 制御](./vcd#systemverilog-source-controls)。時間を持つプロセスで実行 | | 状態 | 2 値・4 値シミュレーション | 上記の各構文は、ソフトウェアモデルと結果を比較するテストで確認しています。Veryl が出力する @@ -267,7 +267,8 @@ real 変換と動的 string は未対応です。 ファイル descriptor とメモリ書き出しは[実行時のファイル出力](#実行時のファイル出力)を参照してください。 -ファイル I/O を含むデザインでは、ホスト側の状態を保存できないため、 +[VCD 制御](./vcd#systemverilog-source-controls)の記録開始は、その時刻の状態が確定した後です。 +ファイル I/O または SV からの VCD 制御を含むデザインでは、ホスト側の状態を保存できないため、 checkpoint と状態ファイルの保存・復元はエラーになります。 `$dist_uniform(seed, start, end)` は Annex N の一様分布を使い、整数の seed 変数を更新します。 diff --git a/docs/ja/guide/vcd.md b/docs/ja/guide/vcd.md index 9a890c5038f..1a211d75ed4 100644 --- a/docs/ja/guide/vcd.md +++ b/docs/ja/guide/vcd.md @@ -56,3 +56,29 @@ sim.dispose(); ## 関連資料 - [テストの書き方](./writing-tests.md) -- Simulator・Simulation のパターン。 + +## SystemVerilog からの制御 {#systemverilog-source-controls} + +時刻付きシミュレーションでは HDL から波形を指定できます。 + +```systemverilog +initial begin + $dumpfile("waves.vcd"); + $dumpvars(0, Top); +end +``` + +`$dumpvars` は現在時刻の処理が収束してから記録を開始します。すべての呼び出しを +同じシミュレーション時刻に実行してください。深さ `0` は子階層をすべて含み、 +`1` は指定モジュール自身の変数だけを含みます。個別変数や複数の選択も指定できます。 + +`$dumpoff` は不定値を記録して停止し、`$dumpon` は現在値を記録して再開します。 +`$dumpall` は記録の停止状態を変えずに選択変数の現在値をすべて記録します。 +`$dumpflush` はバッファを出力します。`$dumplimit(bytes)` はサイズ上限に達すると +コメントを出力して記録を停止します。完全なレコードを出力するため上限を多少超える +場合があります。上限 `0` はサイズ制限を解除します。 + +`$dumpfile` は文字列リテラルまたはファイル名を格納した整数式を受け取り、 +`$dumpvars` より前に実行する必要があります。既定のファイル名は `dump.vcd` です。 +必要なトレース用ストレージは自動で有効になるため、ホスト側での VCD パス指定は +省略できます。既存のホスト側の波形 API も引き続き使用できます。