Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions crates/celox-design/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -514,6 +514,49 @@ pub enum DeadStorePolicy {
PreserveAllPorts,
}

/// One simulation tick, expressed as a power of ten seconds.
/// Valid SystemVerilog/VCD scales range from 1 fs (-15) to 100 s (2).
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(try_from = "i32", into = "i32")]
pub struct TimePrecision(i32);

impl TimePrecision {
pub fn exponent(self) -> i32 {
self.0
}

/// The magnitude and physical unit used by a VCD `$timescale` header.
pub fn vcd_timescale(self) -> (u8, &'static str) {
let magnitude = 10u8.pow(self.0.rem_euclid(3) as u32);
let unit = ["s", "ms", "us", "ns", "ps", "fs"][(-self.0.div_euclid(3)) as usize];
(magnitude, unit)
}
}

impl Default for TimePrecision {
/// Scale-free frontends use the same 1ps tick as the SV implementation default.
fn default() -> Self {
Self(-12)
}
}

impl TryFrom<i32> for TimePrecision {
type Error = &'static str;
fn try_from(exponent: i32) -> Result<Self, Self::Error> {
if (-15..=2).contains(&exponent) {
Ok(Self(exponent))
} else {
Err("time precision must be between 1fs and 100s")
}
}
}

impl From<TimePrecision> for i32 {
fn from(precision: TimePrecision) -> Self {
precision.0
}
}

/// Source-independent runtime diagnostics and observable event descriptions.
#[derive(Clone, Debug)]
pub struct RuntimeSchema<A> {
Expand Down Expand Up @@ -732,6 +775,13 @@ impl<A: Copy + Eq + std::hash::Hash> EventTopology<A> {
}
}

/// Time unit and rounding precision of one source scope, in powers of ten seconds.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct TimeScale {
pub unit: TimePrecision,
pub precision: TimePrecision,
}

/// Backend-neutral semantic design data after hierarchy flattening.
///
/// This is intentionally not a frontend lookup table: every state object is
Expand All @@ -743,6 +793,11 @@ impl<A: Copy + Eq + std::hash::Hash> EventTopology<A> {
deserialize = "A: Deserialize<'de> + Eq + std::hash::Hash + Ord"
))]
pub struct ElaboratedDesign<A> {
/// Physical duration of one global simulation tick.
#[serde(default)]
pub time_precision: TimePrecision,
/// Local time units and precisions retained for reflected instance queries.
pub instance_time_scales: HashMap<InstanceId, TimeScale>,
pub state_objects: HashMap<A, VariableMetadata>,
pub events: EventTopology<A>,
pub initial_state: Vec<InitialStateValue<A>>,
Expand All @@ -751,6 +806,8 @@ pub struct ElaboratedDesign<A> {
impl<A> Default for ElaboratedDesign<A> {
fn default() -> Self {
Self {
time_precision: TimePrecision::default(),
instance_time_scales: HashMap::default(),
state_objects: HashMap::default(),
events: EventTopology::default(),
initial_state: Vec::new(),
Expand Down
2 changes: 2 additions & 0 deletions crates/celox-frontend-core/src/sdk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1897,6 +1897,8 @@ pub fn lower_frontend_artifact(

let module_id = ModuleId(0);
let sim_module = SimModule {
time_precision: None,
time_scale: celox_design::TimeScale::default(),
name: artifact.module_name().to_string(),
variables,
ff_access_summaries: HashMap::default(),
Expand Down
4 changes: 4 additions & 0 deletions crates/celox-frontend-core/src/symbolic/artifact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ pub struct SymbolicProcess {

#[derive(Clone)]
pub struct SimModule {
/// A frontend's global tick precision; absent for scale-free frontends.
pub time_precision: Option<celox_design::TimePrecision>,
/// Local unit and precision; scale-free frontends use the 1ps default.
pub time_scale: celox_design::TimeScale,
pub name: String,
pub variables: HashMap<SourceVarId, SymbolicVariable>,
pub ff_access_summaries:
Expand Down
13 changes: 13 additions & 0 deletions crates/celox-frontend-core/src/symbolic/assembly.rs
Original file line number Diff line number Diff line change
Expand Up @@ -572,6 +572,11 @@ pub fn schedule_symbolic_rtl(
root_id,
packages,
} = symbolic;
let time_precision = modules
.values()
.filter_map(|module| module.time_precision)
.min()
.unwrap_or_default();
let flatten_timing = trace_opts.phase_timing;
macro_rules! timed_sub {
($label:expr, $body:expr) => {{
Expand Down Expand Up @@ -603,6 +608,10 @@ pub fn schedule_symbolic_rtl(
instance_modules.insert(id, *module_id);
package_instances.insert(*module_id, id);
}
let instance_time_scales = instance_modules
.iter()
.map(|(&instance, module)| (instance, modules[module].time_scale))
.collect::<HashMap<_, _>>();
let bindings = &PackageBindings::new(&instance_modules, &modules, &package_instances)?;
let global_boundaries = timed_sub!(
"propagate_boundaries",
Expand Down Expand Up @@ -1479,6 +1488,8 @@ pub fn schedule_symbolic_rtl(
.collect();
let watches: Vec<EventWatch<StateAddr>> = {
let event_kinds = ElaboratedDesign {
time_precision,
instance_time_scales: HashMap::default(),
state_objects: state_objects.clone(),
events: events.clone(),
initial_state: Vec::new(),
Expand Down Expand Up @@ -1546,6 +1557,8 @@ pub fn schedule_symbolic_rtl(
let scheduled = ScheduledRtl {
sir,
design: ElaboratedDesign {
time_precision,
instance_time_scales,
state_objects,
events,
initial_state,
Expand Down
36 changes: 33 additions & 3 deletions crates/celox-frontend-sv/src/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -723,7 +723,12 @@ fn lower_package_states(
.into_iter()
.enumerate()
.map(|(index, module)| {
let lowered = lower_module(module, four_state, true, ff_parts)?;
let mut lowered = lower_module(module, four_state, true, ff_parts)?;
lowered.sim_module.time_precision = Some(
celox_design::TimePrecision::try_from(packages.global_time_precision())
.map_err(|reason| sv::AnalyzerError::Unsupported(reason.to_string()))?,
);
lowered.sim_module.time_scale = scope_time_scale(packages, module.name())?;
// Declaration initializers run before every `initial` block
// (IEEE 1800-2023 10.5); one that is not folded into an initial
// value would run among them.
Expand Down Expand Up @@ -1791,12 +1796,35 @@ fn specialize_module(
.iter()
.find(|candidate| candidate.name() == module.name)
.ok_or_else(|| sv::AnalyzerError::Unsupported(format!("module `{}`", module.name)))?;
lower_module(
let mut lowered = lower_module(
specialized,
four_state,
module.implicit_nets_allowed,
ff_parts,
)
)?;
lowered.sim_module.time_precision = Some(
celox_design::TimePrecision::try_from(module.packages.global_time_precision())
.map_err(|reason| sv::AnalyzerError::Unsupported(reason.to_string()))?,
);
lowered.sim_module.time_scale = scope_time_scale(&module.packages, &module.name)?;
Ok(lowered)
}

fn scope_time_scale(
packages: &sv::Packages,
name: &str,
) -> Result<celox_design::TimeScale, sv::AnalyzerError> {
let Some((unit, precision)) = packages.scope_time_scale(name) else {
return Ok(celox_design::TimeScale::default());
};
let convert = |exponent: i32| {
celox_design::TimePrecision::try_from(exponent)
.map_err(|reason| sv::AnalyzerError::Unsupported(reason.to_string()))
};
Ok(celox_design::TimeScale {
unit: convert(unit)?,
precision: convert(precision)?,
})
}

fn lower_module(
Expand Down Expand Up @@ -2060,6 +2088,8 @@ fn lower_module_with_overrides(
source: module.clone(),
implicit_nets_allowed,
sim_module: SimModule {
time_precision: None,
time_scale: celox_design::TimeScale::default(),
name,
variables: shared_variables,
ff_access_summaries: HashMap::default(),
Expand Down
2 changes: 2 additions & 0 deletions crates/celox-frontend-veryl/src/artifact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,8 @@ pub(crate) fn project_module_with_ids(

Ok((
crate::symbolic::artifact::SimModule {
time_precision: None,
time_scale: celox_design::TimeScale::default(),
name: veryl_parser::resource_table::get_str_value(module.name).unwrap_or_default(),
variables,
ff_access_summaries: module
Expand Down
42 changes: 39 additions & 3 deletions crates/celox-napi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -684,6 +684,7 @@ struct CachedBuild {
state_schema: Arc<celox::StateSchema>,
/// Pre-computed VCD signal descriptors so VCD works on cache hits.
vcd_descs: Vec<celox::VcdSignalDesc>,
time_precision: celox_design::TimePrecision,
/// Derived clock domains per event, valid for every backend sharing
/// `shared_code`.
derived_ticks: celox::DerivedTickPlans<DefaultEvent>,
Expand Down Expand Up @@ -1126,6 +1127,7 @@ impl NativeSimulatorHandle {
let state_fingerprint = sim.state_fingerprint();
let state_schema = sim.state_schema();
let vcd_descs = sim.build_vcd_descs(four_state);
let time_precision = sim.program().design.time_precision;
let runtime_errors = runtime_errors_by_name(sim.program());
let derived_ticks = sim.derived_tick_plans();
let event_edges = sim.event_edges();
Expand Down Expand Up @@ -1155,6 +1157,7 @@ impl NativeSimulatorHandle {
state_fingerprint,
state_schema: Arc::clone(&state_schema),
vcd_descs: vcd_descs.clone(),
time_precision,
derived_ticks: Arc::clone(&derived_ticks),
event_edges: Arc::clone(&event_edges),
});
Expand All @@ -1165,7 +1168,7 @@ impl NativeSimulatorHandle {
// Create VcdWriter if requested
let vcd_writer = if let Some(path) = vcd_path {
Some(
celox::VcdWriter::new(path, &vcd_descs)
celox::VcdWriter::new_with_time_precision(path, &vcd_descs, time_precision)
.map_err(|e| Error::from_reason(format!("Failed to create VCD: {}", e)))?,
)
} else {
Expand Down Expand Up @@ -1261,8 +1264,12 @@ impl NativeSimulatorHandle {
)));
let vcd_writer = if let Some(path) = vcd_path {
Some(
celox::VcdWriter::new(path, &cached.vcd_descs)
.map_err(|e| Error::from_reason(format!("Failed to create VCD: {}", e)))?,
celox::VcdWriter::new_with_time_precision(
path,
&cached.vcd_descs,
cached.time_precision,
)
.map_err(|e| Error::from_reason(format!("Failed to create VCD: {}", e)))?,
)
} else {
None
Expand Down Expand Up @@ -4332,6 +4339,35 @@ mod tests {
);
}

#[test]
fn cached_waveforms_retain_explicit_time_precision() {
let dir = tempfile::tempdir().unwrap();
let source = "module CachedPrecision(y: output logic) {}";
let sources = make_sources(&[(source, "cached_precision.veryl")]);
let key = build_cache_key(&sources, "CachedPrecision", &default_opts(), None);
let sim = celox::Simulator::builder(source, "CachedPrecision")
.vcd(dir.path().join("initial.vcd"))
.build()
.unwrap();
let handle = NativeSimulatorHandle::build_and_cache(sim, None, Some(key.clone())).unwrap();
drop(handle);
let mut cached = JIT_CACHE
.lock()
.unwrap_or_else(|e| e.into_inner())
.remove(&key)
.unwrap();
// A frontend with a non-default scale supplies this cached metadata.
Arc::get_mut(&mut cached).unwrap().time_precision =
celox_design::TimePrecision::try_from(-15).unwrap();
let path = dir.path().join("cached.vcd");
let mut handle = NativeSimulatorHandle::from_cached(&cached, path.to_str()).unwrap();
handle.dump(123.0).unwrap();
handle.vcd_writer.as_mut().unwrap().flush().unwrap();
let text = std::fs::read_to_string(path).unwrap();
assert!(text.contains("$timescale 1fs $end"), "{text}");
assert!(text.contains("#123\n"));
}

#[test]
fn vcd_paths_share_compiled_code_but_tracing_modes_do_not() {
let src = make_sources(&[("module Top {}", "a.veryl")]);
Expand Down
1 change: 1 addition & 0 deletions crates/celox-runtime/src/reflection.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ pub struct ReflectionScope {
pub name: String,
pub full_name: String,
pub module_name: String,
pub time_scale: celox_design::TimeScale,
pub parent: Option<ReflectionScopeId>,
pub children: Vec<ReflectionScopeId>,
pub signals: Vec<ReflectionSignalId>,
Expand Down
Loading
Loading