diff --git a/Cargo.lock b/Cargo.lock index d76de844ab8..9638a70c314 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -404,6 +404,7 @@ dependencies = [ "celox-frontend-sdk", "celox-frontend-sv", "celox-frontend-veryl", + "celox-heap", "celox-macros", "celox-runtime", "celox-sir", @@ -648,6 +649,13 @@ dependencies = [ "veryl-parser", ] +[[package]] +name = "celox-heap" +version = "0.11.0" +dependencies = [ + "fxhash", +] + [[package]] name = "celox-macros" version = "0.11.0" @@ -800,6 +808,7 @@ name = "celox-testbench" version = "0.11.0" dependencies = [ "celox-design", + "celox-heap", "num-bigint", "num-traits", "serde", diff --git a/Cargo.toml b/Cargo.toml index 853335b6b46..76c0db9690d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ members = [ "crates/celox-frontend-sdk", "crates/celox-frontend-sv", "crates/celox-frontend-veryl", + "crates/celox-heap", "crates/celox-sir", "crates/celox-sir-opt", "crates/celox-slt", @@ -65,6 +66,7 @@ celox-frontend-core = { version = "=0.11.0", path = "crates/celox-frontend-c celox-frontend-sdk = { version = "=0.11.0", path = "crates/celox-frontend-sdk" } # x-release-please-version celox-frontend-sv = { version = "=0.11.0", path = "crates/celox-frontend-sv" } # x-release-please-version celox-frontend-veryl = { version = "=0.11.0", path = "crates/celox-frontend-veryl" } # x-release-please-version +celox-heap = { version = "=0.11.0", path = "crates/celox-heap" } # x-release-please-version celox-macros = { version = "=0.11.0", path = "crates/celox-macros" } # x-release-please-version celox-napi = { version = "=0.11.0", path = "crates/celox-napi" } # x-release-please-version celox-runtime = { version = "=0.11.0", path = "crates/celox-runtime" } # x-release-please-version diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 9ebb81097db..2c420a0c4f2 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -54,6 +54,28 @@ pub struct VariableMetadata { /// Per-dimension sizes for array ports (for example, `[4]` for `logic<32>[4]`). /// Empty means scalar. pub array_dims: Vec, + /// What each element holds. Handle elements are 32-bit two-state slots. + #[serde(default)] + pub value_kind: ValueKind, +} + +/// Bit width of a handle element in state memory. +pub const HANDLE_WIDTH: usize = 32; + +/// What a state element holds. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ValueKind { + /// Packed bits. + #[default] + Bits, + /// A handle of a string in the simulator's heap. + StrRef, +} + +impl ValueKind { + pub fn is_handle(self) -> bool { + self != Self::Bits + } } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] @@ -1596,6 +1618,7 @@ mod tests { kind: DomainKind::Other, type_kind: PortTypeKind::Logic, array_dims: vec![4], + value_kind: Default::default(), }; assert_eq!(metadata.width, 32); @@ -1613,6 +1636,7 @@ mod tests { kind: DomainKind::ClockPosedge, type_kind: PortTypeKind::Clock, array_dims: Vec::new(), + value_kind: Default::default(), }, ); design.events.aliases.insert(11, 10); @@ -1641,6 +1665,7 @@ mod tests { kind, type_kind: PortTypeKind::Logic, array_dims: Vec::new(), + value_kind: Default::default(), }, ); } @@ -1673,6 +1698,7 @@ mod tests { kind, type_kind: PortTypeKind::Logic, array_dims: Vec::new(), + value_kind: Default::default(), }, ); } diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index 77ddc67441f..6c6f6e61d6a 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1058,6 +1058,7 @@ impl HiddenObjects<'_> { PortTypeKind::Bit }, array_dims: Vec::new(), + value_kind: Default::default(), }, unpacked_ranges: Vec::new(), packed_dims: vec![width], @@ -1821,6 +1822,7 @@ pub fn lower_frontend_artifact( kind, type_kind, array_dims: Vec::new(), + value_kind: Default::default(), }, unpacked_ranges: Vec::new(), packed_dims: vec![signal.value_type().width()], diff --git a/crates/celox-frontend-core/src/watch.rs b/crates/celox-frontend-core/src/watch.rs index da653ee9f27..008f9d44bc0 100644 --- a/crates/celox-frontend-core/src/watch.rs +++ b/crates/celox-frontend-core/src/watch.rs @@ -501,6 +501,7 @@ pub fn declare_counter_slots( kind: DomainKind::Other, type_kind: PortTypeKind::Bit, array_dims: Vec::new(), + value_kind: Default::default(), }, unpacked_ranges: Vec::new(), packed_dims: vec![EVENT_COUNTER_WIDTH], diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index b1105551afe..85c9d6574da 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -94,6 +94,7 @@ impl SvVariable { kind: self.domain_kind, type_kind: self.type_kind, array_dims: self.array_dims.clone(), + value_kind: Default::default(), }, unpacked_ranges: self.unpacked_ranges.clone(), packed_dims: self diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 7b8dd5ae2a7..216018f79ad 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -460,6 +460,11 @@ pub(crate) fn project_module_with_ids( .iter() .filter_map(|value| *value) .collect(), + value_kind: if variable.r#type.is_string() { + celox_design::ValueKind::StrRef + } else { + celox_design::ValueKind::Bits + }, }, packed_dims, unpacked_ranges: Vec::new(), diff --git a/crates/celox-frontend-veryl/src/lowering/bitaccess.rs b/crates/celox-frontend-veryl/src/lowering/bitaccess.rs index 3f6ee374de7..50e53826b44 100644 --- a/crates/celox-frontend-veryl/src/lowering/bitaccess.rs +++ b/crates/celox-frontend-veryl/src/lowering/bitaccess.rs @@ -228,7 +228,10 @@ fn collect_dims(module: &Module, var_id: VarId) -> Result, ParserErro // Enums and aggregates encode their packed width in TypeKind rather // than the width Shape. Even a one-bit struct/union needs that dimension: // Veryl represents member access as a select into the packed aggregate. - if width.is_empty() { + if var_type.is_string() { + // A string element is a handle into the simulator's heap. + dims.push(celox_design::HANDLE_WIDTH); + } else if width.is_empty() { if let Some(kind_width) = var_type.kind.width() && (kind_width > 1 || (kind_width == 1 && var_type.is_struct_union())) { diff --git a/crates/celox-frontend-veryl/src/lowering/types.rs b/crates/celox-frontend-veryl/src/lowering/types.rs index 78134de525d..562cc3527cb 100644 --- a/crates/celox-frontend-veryl/src/lowering/types.rs +++ b/crates/celox-frontend-veryl/src/lowering/types.rs @@ -4,9 +4,14 @@ use crate::ParserError; /// Resolve the total storage size of a variable. pub fn resolve_total_width(module: &Module, variable: &Variable) -> Result { - let width = variable.total_width().ok_or_else(|| { - ParserError::unresolved_width(module, variable, variable.r#type.to_string()) - })?; + // A string element is a handle into the simulator's heap. + let width = if variable.r#type.is_string() { + celox_design::HANDLE_WIDTH + } else { + variable.total_width().ok_or_else(|| { + ParserError::unresolved_width(module, variable, variable.r#type.to_string()) + })? + }; let array = variable.r#type.total_array().ok_or_else(|| { ParserError::unresolved_width(module, variable, variable.r#type.to_string()) })?; diff --git a/crates/celox-frontend-veryl/src/testbench.rs b/crates/celox-frontend-veryl/src/testbench.rs index b427e7f8268..11a0b377b6e 100644 --- a/crates/celox-frontend-veryl/src/testbench.rs +++ b/crates/celox-frontend-veryl/src/testbench.rs @@ -1556,7 +1556,7 @@ impl ExprCompiler<'_> { } ops.push(TbOpcode::LoadString { location: Self::state_location_at(address, 0), - elements: info.width, + elements: info.width / celox_design::HANDLE_WIDTH, }); } @@ -3922,6 +3922,7 @@ mod tests { kind: DomainKind::Other, type_kind: PortTypeKind::Logic, array_dims: Vec::new(), + value_kind: Default::default(), }, }; diff --git a/crates/celox-heap/Cargo.toml b/crates/celox-heap/Cargo.toml new file mode 100644 index 00000000000..477e1d8a232 --- /dev/null +++ b/crates/celox-heap/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "celox-heap" +version.workspace = true +publish = ["crates-io"] +authors.workspace = true +repository.workspace = true +license.workspace = true +description = "Runtime heap of dynamic values referenced by handles in Celox state" +edition.workspace = true +rust-version.workspace = true + +[dependencies] +fxhash = { workspace = true } + +[lints] +workspace = true diff --git a/crates/celox-heap/src/lib.rs b/crates/celox-heap/src/lib.rs new file mode 100644 index 00000000000..d52b3b146d9 --- /dev/null +++ b/crates/celox-heap/src/lib.rs @@ -0,0 +1,217 @@ +//! The runtime heap of a simulator. +//! +//! Dynamic values live here and state memory refers to them by 32-bit +//! handles, never by address, so state images stay position independent. +//! Strings are interned and immutable: equal contents have equal handles, so +//! stores, commits, change detection and `==` compare handles as integers. +//! +//! References from state memory are not counted. A collection marks the +//! entries reachable from the handles the caller passes as roots and frees +//! the rest; callers collect only where every copy of a handle is in a place +//! they can enumerate. + +use std::sync::Arc; + +use fxhash::FxHashMap as HashMap; + +/// A reference to a heap entry, as stored in state memory. +pub type Handle = u32; + +/// Byte width of a handle slot in state memory. +pub const HANDLE_BYTES: usize = 4; + +/// The handle of `""`, the value of zero-initialized state memory. +pub const EMPTY_STRING: Handle = 0; + +/// Entries created since the last collection before another one is due, +/// unless the live set is larger. +const MIN_COLLECTION_INTERVAL: usize = 1024; + +/// Dynamic strings referenced by [`Handle`]. +#[derive(Clone, Debug)] +pub struct Heap { + strings: Vec>>, + lookup: HashMap, Handle>, + free: Vec, + /// Entries below this handle are never collected. + pinned: usize, + created: usize, + live_after_collection: usize, +} + +impl Default for Heap { + fn default() -> Self { + Self::new() + } +} + +impl Heap { + pub fn new() -> Self { + let empty: Arc<[u8]> = Arc::from(&[][..]); + let mut lookup = HashMap::default(); + lookup.insert(empty.clone(), EMPTY_STRING); + Self { + strings: vec![Some(empty)], + lookup, + free: Vec::new(), + pinned: 1, + created: 0, + live_after_collection: 1, + } + } + + /// The handle of the string `bytes`, creating it if needed. NUL bytes are + /// removed first, as assigning a literal to a string does (IEEE 1800-2023 + /// 6.16). + pub fn intern(&mut self, bytes: &[u8]) -> Handle { + if bytes.contains(&0) { + let stripped: Vec = bytes.iter().copied().filter(|&byte| byte != 0).collect(); + return self.intern_stripped(&stripped); + } + self.intern_stripped(bytes) + } + + fn intern_stripped(&mut self, bytes: &[u8]) -> Handle { + if let Some(&handle) = self.lookup.get(bytes) { + return handle; + } + let value: Arc<[u8]> = Arc::from(bytes); + let handle = match self.free.pop() { + Some(handle) => { + self.strings[handle as usize] = Some(value.clone()); + handle + } + None => { + let handle = Handle::try_from(self.strings.len()) + .expect("the heap has more strings than handles can name"); + self.strings.push(Some(value.clone())); + handle + } + }; + self.lookup.insert(value, handle); + self.created += 1; + handle + } + + /// The contents of `handle`. A handle that names no string reads as `""`, + /// so a value written into a handle slot by the host cannot crash a read. + pub fn string(&self, handle: Handle) -> &[u8] { + self.strings + .get(handle as usize) + .and_then(Option::as_deref) + .unwrap_or_default() + } + + /// Whether `handle` names a live string. + pub fn contains(&self, handle: Handle) -> bool { + self.strings + .get(handle as usize) + .is_some_and(Option::is_some) + } + + /// The number of live strings, including `""`. + pub fn len(&self) -> usize { + self.strings.len() - self.free.len() + } + + pub fn is_empty(&self) -> bool { + false + } + + /// Bytes of string contents, excluding allocator overhead. + pub fn content_size(&self) -> usize { + self.strings.iter().flatten().map(|value| value.len()).sum() + } + + /// Whether enough entries were created since the last collection to make + /// another worthwhile. The interval grows with the live set, so the cost + /// of collecting stays proportional to the allocation that triggered it. + pub fn should_collect(&self) -> bool { + self.created >= MIN_COLLECTION_INTERVAL.max(self.live_after_collection) + } + + /// Free every unpinned entry that no handle in `roots` refers to. Roots + /// that name no entry are ignored. + pub fn collect(&mut self, roots: impl IntoIterator) { + let mut marked = vec![false; self.strings.len()]; + marked[..self.pinned].fill(true); + for root in roots { + if let Some(mark) = marked.get_mut(root as usize) { + *mark = true; + } + } + for (handle, live) in marked.into_iter().enumerate() { + if live { + continue; + } + if let Some(value) = self.strings[handle].take() { + self.lookup.remove(&value); + self.free.push(handle as Handle); + } + } + self.created = 0; + self.live_after_collection = self.len(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn interning_gives_equal_contents_equal_handles() { + let mut heap = Heap::new(); + let a = heap.intern(b"abc"); + assert_eq!(heap.intern(b"abc"), a); + assert_ne!(heap.intern(b"abd"), a); + assert_eq!(heap.intern(b""), EMPTY_STRING); + assert_eq!(heap.string(a), b"abc"); + } + + #[test] + fn nul_bytes_are_removed() { + let mut heap = Heap::new(); + let a = heap.intern(b"a\0b\0"); + assert_eq!(heap.string(a), b"ab"); + assert_eq!(heap.intern(b"ab"), a); + assert_eq!(heap.intern(b"\0\0"), EMPTY_STRING); + } + + #[test] + fn unknown_handles_read_as_empty() { + let heap = Heap::new(); + assert_eq!(heap.string(12345), b""); + assert!(!heap.contains(12345)); + } + + #[test] + fn collection_frees_unreachable_strings_and_reuses_handles() { + let mut heap = Heap::new(); + let kept = heap.intern(b"kept"); + let dropped = heap.intern(b"dropped"); + heap.collect([kept, 999]); + assert_eq!(heap.string(kept), b"kept"); + assert!(!heap.contains(dropped)); + assert!(heap.contains(EMPTY_STRING)); + // A freed handle is reused, and its old contents are gone from the + // intern table. + let again = heap.intern(b"new"); + assert_eq!(again, dropped); + assert_eq!(heap.string(again), b"new"); + assert_ne!(heap.intern(b"dropped"), kept); + } + + #[test] + fn collection_is_due_after_enough_allocation() { + let mut heap = Heap::new(); + for index in 0..MIN_COLLECTION_INTERVAL - 1 { + heap.intern(index.to_string().as_bytes()); + } + assert!(!heap.should_collect()); + heap.intern(b"one more"); + assert!(heap.should_collect()); + heap.collect([]); + assert!(!heap.should_collect()); + assert_eq!(heap.len(), 1); + } +} diff --git a/crates/celox-runtime/src/state_file.rs b/crates/celox-runtime/src/state_file.rs index a377679d3ba..98c61ea0cf8 100644 --- a/crates/celox-runtime/src/state_file.rs +++ b/crates/celox-runtime/src/state_file.rs @@ -34,11 +34,16 @@ //! counted count u32, then per signal: signal str | 3 × counter u32 //! write count u32, then per host write: signal str | value bytes | mask bytes //! host pending u8 | finished u8 +//! strings (only with FLAG_STRINGS): count u32, then per string: bytes //! scheduled event: time u64 | event str | signal str | value u8 //! str: byte length u32 | UTF-8 //! bytes: byte length u32 | little-endian bytes //! ``` //! +//! The value of a string object is one little-endian u32 per element: 0 for +//! `""`, otherwise one more than the index of its contents in the strings +//! section. Files without strings keep the earlier encoding. +//! //! Version 1 files, which have no process section, still load. A file whose //! processes have nothing to record is written as version 1, which older //! builds read too. @@ -52,6 +57,8 @@ const FLAG_SCHEDULE: u16 = 1 << 1; /// The schedule lists events whose signal was x or z. Set only when there are /// any, so other files keep their earlier encoding. const FLAG_UNKNOWN_EVENTS: u16 = 1 << 2; +/// String objects refer to a strings section after the schedule. +const FLAG_STRINGS: u16 = 1 << 3; /// How a state object gets its value. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -175,6 +182,8 @@ pub struct StateFile { pub four_state: bool, pub objects: Vec, pub schedule: Option, + /// Contents of the strings that string objects refer to. + pub strings: Vec>, } /// A state file that could not be read. @@ -225,6 +234,9 @@ impl StateFile { flags |= FLAG_UNKNOWN_EVENTS; } } + if !self.strings.is_empty() { + flags |= FLAG_STRINGS; + } put_u16(w, flags)?; put_len(w, self.objects.len())?; for object in &self.objects { @@ -276,6 +288,12 @@ impl StateFile { put_processes(w, processes)?; } } + if !self.strings.is_empty() { + put_len(w, self.strings.len())?; + for string in &self.strings { + put_bytes(w, string)?; + } + } Ok(()) } @@ -364,6 +382,13 @@ impl StateFile { } else { None }; + let strings = if flags & FLAG_STRINGS != 0 { + (0..get_u32(r)?) + .map(|_| get_len_bytes(r)) + .collect::>()? + } else { + Vec::new() + }; let mut rest = [0; 1]; if r.read(&mut rest)? != 0 { return Err(StateFileError::Malformed( @@ -374,6 +399,7 @@ impl StateFile { four_state, objects, schedule, + strings, }) } @@ -741,9 +767,23 @@ mod tests { finished: false, }, }), + strings: Vec::new(), } } + #[test] + fn strings_round_trip_after_the_schedule() { + let mut file = sample(); + file.strings = vec![b"abc".to_vec(), Vec::new(), b"\xff".to_vec()]; + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + assert_eq!(StateFile::read_from(bytes.as_slice()).unwrap(), file); + file.schedule = None; + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + assert_eq!(StateFile::read_from(bytes.as_slice()).unwrap(), file); + } + #[test] fn files_without_process_state_are_version_1() { let mut file = sample(); diff --git a/crates/celox-testbench/Cargo.toml b/crates/celox-testbench/Cargo.toml index 2c373de4040..866bf086d7d 100644 --- a/crates/celox-testbench/Cargo.toml +++ b/crates/celox-testbench/Cargo.toml @@ -11,6 +11,7 @@ rust-version.workspace = true [dependencies] celox-design = { workspace = true } +celox-heap = { workspace = true } num-bigint = { workspace = true } num-traits = { workspace = true } serde = { workspace = true } diff --git a/crates/celox-testbench/src/lib.rs b/crates/celox-testbench/src/lib.rs index 5d5c95342a1..24217b7e149 100644 --- a/crates/celox-testbench/src/lib.rs +++ b/crates/celox-testbench/src/lib.rs @@ -16,9 +16,6 @@ pub use format::{ }; pub use vm::{CompiledExpr, TestbenchValue}; -/// Dynamic string values, addressed by a bound variable and flattened array index. -pub type TestbenchStrings = std::collections::BTreeMap<(usize, usize), Vec>; - #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct StateLocation { pub address: A, @@ -521,10 +518,14 @@ pub enum ExprOpcode { byte_size: usize, }, ConstString(Vec), + /// Pop the bit offset of a string element within the variable at + /// `location`, which holds `elements` heap handles, and push its contents. + /// An offset past the last element reads `""`. LoadString { location: L, elements: usize, }, + /// Pop a string and store its heap handle at `location`. StoreString { location: L, }, diff --git a/crates/celox-testbench/src/vm.rs b/crates/celox-testbench/src/vm.rs index 3bba0da9720..fcd6d4e0444 100644 --- a/crates/celox-testbench/src/vm.rs +++ b/crates/celox-testbench/src/vm.rs @@ -110,15 +110,16 @@ impl CompiledExpr { memory: *mut u8, on_write: impl FnMut(usize, usize), ) -> TestbenchValue { - self.eval_with_strings(memory, &mut crate::TestbenchStrings::new(), on_write) + self.eval_with_heap(memory, None, on_write) } - /// Evaluate using the simulator-owned string storage. Values are copied on - /// load so assigning another variable cannot alias a mutable string. - pub fn eval_with_strings( + /// Evaluate with the simulator's heap, which string variables refer to. + /// Without a heap, string variables read as `""` and string stores are + /// dropped instead of writing a handle no heap knows. + pub fn eval_with_heap( &self, memory: *mut u8, - strings: &mut crate::TestbenchStrings, + mut heap: Option<&mut celox_heap::Heap>, mut on_write: impl FnMut(usize, usize), ) -> TestbenchValue { let mut stack: Vec = Vec::with_capacity(16); @@ -126,7 +127,7 @@ impl CompiledExpr { let ops = self.bytecode.ops(); while pc < ops.len() { - self.exec_at(ops, &mut pc, &mut stack, memory, strings, &mut on_write); + self.exec_at(ops, &mut pc, &mut stack, memory, &mut heap, &mut on_write); } stack.pop().unwrap_or_else(|| { debug_assert!(false, "testbench bytecode: stack empty after evaluation"); @@ -143,7 +144,7 @@ impl CompiledExpr { pc: &mut usize, stack: &mut Vec, memory: *mut u8, - strings: &mut crate::TestbenchStrings, + heap: &mut Option<&mut celox_heap::Heap>, on_write: &mut impl FnMut(usize, usize), ) { match &ops[*pc] { @@ -152,14 +153,17 @@ impl CompiledExpr { *pc += 1; } TbOpcode::LoadString { location, elements } => { - let index = stack.pop().expect("string index").to_u64() as usize; - let value = if index < *elements { - strings - .get(&(*location, index)) - .cloned() - .unwrap_or_default() - } else { - Vec::new() + let index = stack.pop().expect("string element offset").to_u64() as usize + / celox_design::HANDLE_WIDTH; + let value = match heap { + Some(heap) if index < *elements => { + let offset = location + index * celox_heap::HANDLE_BYTES; + // SAFETY: bound bytecode addresses a handle slot of + // `elements` handles in this memory image. + let handle = unsafe { read_handle(memory, offset) }; + heap.string(handle).to_vec() + } + _ => Vec::new(), }; stack.push(TestbenchValue::String(value)); *pc += 1; @@ -168,7 +172,19 @@ impl CompiledExpr { let TestbenchValue::String(value) = stack.pop().expect("string store value") else { unreachable!("string store requires a string value"); }; - strings.insert((*location, 0), value); + if let Some(heap) = heap { + let handle = heap.intern(&value); + // SAFETY: bound bytecode addresses a handle slot in this + // memory image. + unsafe { + std::ptr::copy_nonoverlapping( + handle.to_le_bytes().as_ptr(), + memory.add(*location), + celox_heap::HANDLE_BYTES, + ); + } + on_write(*location, celox_heap::HANDLE_BYTES); + } *pc += 1; } TbOpcode::ConstU64(v) => { @@ -326,14 +342,14 @@ impl CompiledExpr { if !cond.is_zero() { let then_end = *pc + then_len; while *pc < then_end { - self.exec_at(ops, pc, stack, memory, strings, on_write); + self.exec_at(ops, pc, stack, memory, heap, on_write); } *pc += else_len; // skip else block } else { *pc += then_len; // skip then block let else_end = *pc + else_len; while *pc < else_end { - self.exec_at(ops, pc, stack, memory, strings, on_write); + self.exec_at(ops, pc, stack, memory, heap, on_write); } } } @@ -998,6 +1014,20 @@ fn eval_binop_wide_cmp(l: &BigUint, op: Op, r: &BigUint) -> u64 { } } +/// Read the handle stored at `offset`. +/// +/// # Safety +/// +/// `memory + offset` must be valid for reading a handle. +unsafe fn read_handle(memory: *const u8, offset: usize) -> celox_heap::Handle { + let mut bytes = [0; celox_heap::HANDLE_BYTES]; + // SAFETY: guaranteed by the caller. + unsafe { + std::ptr::copy_nonoverlapping(memory.add(offset), bytes.as_mut_ptr(), bytes.len()); + } + celox_heap::Handle::from_le_bytes(bytes) +} + #[cfg(test)] mod float_tests { use super::*; diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index 399a7fd538a..78161e8e44f 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -943,6 +943,7 @@ mod tests { object("next", StateRole::Comb, stale, 0), ], schedule: None, + strings: Vec::new(), } } diff --git a/crates/celox/Cargo.toml b/crates/celox/Cargo.toml index bddbd054b93..2a6c3e241dc 100644 --- a/crates/celox/Cargo.toml +++ b/crates/celox/Cargo.toml @@ -52,6 +52,7 @@ celox-sir-opt = { workspace = true, default-features = false } celox-slt = { workspace = true } celox-state-layout = { workspace = true } celox-runtime = { workspace = true } +celox-heap = { workspace = true } celox-testbench = { workspace = true } fxhash = { workspace = true } thiserror = { workspace = true } diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index bc708bb142d..3535fb17956 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -2,6 +2,8 @@ mod builder; #[cfg(feature = "host-runtime")] mod checkpoint; mod error; +#[cfg(feature = "host-runtime")] +mod heap; #[cfg(feature = "systemverilog")] pub(crate) mod mixed; #[cfg(feature = "host-runtime")] @@ -118,8 +120,10 @@ mod host { /// cross-codegen builds or unsupported hosts. pub struct Simulator { pub(crate) backend: B, - /// Dynamic testbench strings, keyed by the bound variable location. - pub(crate) testbench_strings: celox_testbench::TestbenchStrings, + /// Dynamic values that handle slots in state memory refer to. + pub(crate) heap: celox_heap::Heap, + /// Byte offsets of every handle slot in state memory. + pub(super) handle_slots: std::sync::OnceLock>, file_io: celox_runtime::file_io::FileIo, pending_host_events: Arc>, pub(crate) program: RuntimeProgram, @@ -827,7 +831,8 @@ mod host { dirty: false, declaration_phase: false, warnings, - testbench_strings: Default::default(), + heap: Default::default(), + handle_slots: Default::default(), file_io: Default::default(), pending_host_events: Default::default(), components: Default::default(), @@ -2167,6 +2172,16 @@ mod host { .iter() .filter_map(|address| self.program.design.variable(address)) .filter(|variable| instance.resolves_path_to(&variable.path, variable.address)) + // A handle slot holds a heap reference, not a value to + // show; strings have no VCD representation yet. + .filter(|variable| { + !self + .program + .design + .state_objects + .get(&variable.address) + .is_some_and(|metadata| metadata.value_kind.is_handle()) + }) .collect(); sorted_vars.sort_by(|a, b| a.path.cmp(&b.path)); diff --git a/crates/celox/src/simulator/checkpoint.rs b/crates/celox/src/simulator/checkpoint.rs index b5a16a235a5..e3de65e94e6 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -92,7 +92,7 @@ fn state_range(backend: &B) -> std::ops::Range { #[derive(Clone)] pub struct Checkpoint { image: StateImage, - testbench_strings: celox_testbench::TestbenchStrings, + heap: celox_heap::Heap, comb_observer_snapshots: Vec>, comb_observer_initial_eval: bool, /// Whether the design had finished a timed simulation. @@ -102,7 +102,7 @@ pub struct Checkpoint { impl Checkpoint { /// Bytes in the saved memory image and string contents, excluding allocator overhead. pub fn state_size(&self) -> usize { - self.image.len() + self.testbench_strings.values().map(Vec::len).sum::() + self.image.len() + self.heap.content_size() } } @@ -159,7 +159,7 @@ impl Simulator { } Ok(Checkpoint { image: StateImage::capture(&self.backend, self.state_fingerprint()), - testbench_strings: self.testbench_strings.clone(), + heap: self.heap.clone(), comb_observer_snapshots: self.comb_observer_snapshots.clone(), comb_observer_initial_eval: self.comb_observer_initial_eval, frozen: self.frozen, @@ -179,8 +179,7 @@ impl Simulator { checkpoint .image .restore_into(&mut self.backend, fingerprint)?; - self.testbench_strings - .clone_from(&checkpoint.testbench_strings); + self.heap.clone_from(&checkpoint.heap); self.comb_observer_snapshots .clone_from(&checkpoint.comb_observer_snapshots); self.comb_observer_initial_eval = checkpoint.comb_observer_initial_eval; diff --git a/crates/celox/src/simulator/heap.rs b/crates/celox/src/simulator/heap.rs new file mode 100644 index 00000000000..accc54b560d --- /dev/null +++ b/crates/celox/src/simulator/heap.rs @@ -0,0 +1,73 @@ +//! Collecting the heap that handle slots in state memory refer to. + +use std::sync::Arc; + +use celox_heap::{HANDLE_BYTES, Handle}; + +use super::host::Simulator; +use crate::backend::SimBackend; + +impl Simulator { + /// Byte offsets of every handle slot in the stable and working regions. + pub(crate) fn handle_slots(&self) -> Arc<[usize]> { + self.handle_slots + .get_or_init(|| { + let layout = self.backend.layout(); + let mut slots = Vec::new(); + for (address, metadata) in &self.program.design.state_objects { + if !metadata.value_kind.is_handle() { + continue; + } + debug_assert!( + !layout.sparse_offsets.contains_key(address), + "handle slots are never sparse FF targets" + ); + let elements = metadata.width / celox_design::HANDLE_WIDTH; + let bases = layout.offsets.get(address).copied().into_iter().chain( + layout + .working_offsets + .get(address) + .map(|offset| layout.working_base_offset + offset), + ); + for base in bases { + slots.extend((0..elements).map(|index| base + index * HANDLE_BYTES)); + } + } + slots.sort_unstable(); + slots.into() + }) + .clone() + } + + /// The handles held by the handle slots of state memory. + pub(crate) fn handle_roots(&self) -> Vec { + let (memory, len) = self.backend.memory_as_ptr(); + self.handle_slots() + .iter() + .filter(|&&offset| offset + HANDLE_BYTES <= len) + .map(|&offset| { + let mut bytes = [0; HANDLE_BYTES]; + // SAFETY: the slot lies inside the `len` bytes of the image. + unsafe { + std::ptr::copy_nonoverlapping( + memory.add(offset), + bytes.as_mut_ptr(), + HANDLE_BYTES, + ); + } + Handle::from_le_bytes(bytes) + }) + .collect() + } + + /// Collect the heap if enough was allocated since the last collection. + /// State memory and `extra_roots` must hold every live handle: the + /// caller runs this only where no copy of a handle is anywhere else. + pub(crate) fn maybe_collect_heap(&mut self, extra_roots: impl IntoIterator) { + if !self.heap.should_collect() { + return; + } + let roots = self.handle_roots(); + self.heap.collect(roots.into_iter().chain(extra_roots)); + } +} diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index b7b465d948e..96f30a45e94 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -40,6 +40,8 @@ pub enum StateError { /// matching code keeps compiling. #[error("the state of the simulation's processes could not be recorded")] Processes, + /// Not returned: state files record strings by their contents. Kept so + /// that matching code keeps compiling. #[error("state files do not support dynamic testbench strings; use a checkpoint instead")] TestbenchStrings, } @@ -105,6 +107,9 @@ struct NamedObject { path: String, signal: SignalRef, role: StateRole, + /// Whether the elements are string handles, which a file records as + /// references to its strings section. + strings: bool, } /// The state objects of a built design, with the paths and roles that state @@ -121,8 +126,22 @@ pub struct StateSchema { impl StateSchema { /// Save the value of every state object of `backend` as last evaluated. + /// String objects read as `""`; use [`Self::capture_with_heap`] for a + /// backend whose strings live in a heap. pub fn capture(&self, backend: &B) -> StateFile { - let objects = self + self.capture_with_heap(backend, &celox_heap::Heap::new()) + } + + /// Save the value of every state object of `backend`, with the contents + /// of its strings from `heap`. + pub fn capture_with_heap( + &self, + backend: &B, + heap: &celox_heap::Heap, + ) -> StateFile { + let mut strings = Vec::new(); + let mut file_ids: HashMap = HashMap::default(); + let mut objects: Vec = self .objects .iter() .map(|object| { @@ -149,10 +168,36 @@ impl StateSchema { } }) .collect(); + // Number strings by first use in path order, so equal states save + // equal files. + for (object, named) in objects.iter_mut().zip(&self.objects) { + if !named.strings { + continue; + } + for element in object + .value + .as_chunks_mut::<{ celox_heap::HANDLE_BYTES }>() + .0 + { + let handle = celox_heap::Handle::from_le_bytes(*element); + let contents = heap.string(handle); + let id = if contents.is_empty() { + 0 + } else { + // Interning gives each contents one handle. + *file_ids.entry(handle).or_insert_with(|| { + strings.push(contents.to_vec()); + strings.len() as u32 + }) + }; + element.copy_from_slice(&id.to_le_bytes()); + } + } StateFile { four_state: self.four_state, objects, schedule: None, + strings, } } @@ -166,6 +211,16 @@ impl StateSchema { &self, backend: &mut B, file: &StateFile, + ) -> Result<(), StateMismatch> { + self.load_with_heap(backend, &mut celox_heap::Heap::new(), file) + } + + /// Like [`Self::load`], creating the file's strings in `heap`. + pub fn load_with_heap( + &self, + backend: &mut B, + heap: &mut celox_heap::Heap, + file: &StateFile, ) -> Result<(), StateMismatch> { let saved: BTreeMap<&str, &StateObject> = file .objects @@ -184,7 +239,7 @@ impl StateSchema { if let Some(saved) = saved.get(object.path.as_str()) && saved.width == object.signal.width { - seeds.push((object.signal, *saved)); + seeds.push((object, *saved)); } continue; } @@ -197,7 +252,7 @@ impl StateSchema { object.signal.width, )); } - Some(saved) => writes.push((object.signal, *saved)), + Some(saved) => writes.push((object, *saved)), } } let declared: std::collections::BTreeSet<&str> = self @@ -213,8 +268,22 @@ impl StateSchema { if !mismatch.is_empty() { return Err(mismatch); } - for (signal, object) in seeds.into_iter().chain(writes) { - let value = BigUint::from_bytes_le(&object.value); + for (named, object) in seeds.into_iter().chain(writes) { + let signal = named.signal; + let value = if named.strings { + let mut value = object.value.clone(); + for element in value.as_chunks_mut::<{ celox_heap::HANDLE_BYTES }>().0 { + let id = u32::from_le_bytes(*element) as usize; + let contents = id + .checked_sub(1) + .and_then(|index| file.strings.get(index)) + .map_or(&[][..], Vec::as_slice); + element.copy_from_slice(&heap.intern(contents).to_le_bytes()); + } + BigUint::from_bytes_le(&value) + } else { + BigUint::from_bytes_le(&object.value) + }; let mask = object .mask .as_deref() @@ -246,9 +315,6 @@ impl Simulator { /// 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); - } if !self.components.is_empty() { return Err(CheckpointError::ExternalComponents.into()); } @@ -256,7 +322,9 @@ impl Simulator { self.eval_comb_checked().map_err(StateError::Runtime)?; self.dirty = false; } - Ok(self.state_schema().capture(&self.backend)) + Ok(self + .state_schema() + .capture_with_heap(&self.backend, &self.heap)) } /// Load the state saved in `file`, matching objects by path. @@ -279,9 +347,6 @@ impl Simulator { file: &StateFile, time: u64, ) -> Result<(), StateError> { - if !self.testbench_strings.is_empty() { - return Err(StateError::TestbenchStrings); - } if !self.components.is_empty() { return Err(CheckpointError::ExternalComponents.into()); } @@ -289,7 +354,7 @@ impl Simulator { // combinational loop), so keep the current state to return to. let previous = self.checkpoint()?; self.state_schema() - .load(&mut self.backend, file) + .load_with_heap(&mut self.backend, &mut self.heap, file) .map_err(StateError::Mismatch)?; for address in &self.program.runtime_schema.time_slots { self.backend.set( @@ -355,6 +420,9 @@ impl Simulator { } else { StateRole::State }, + strings: self.program.design.state_objects.get(address).is_some_and( + |metadata| metadata.value_kind == celox_design::ValueKind::StrRef, + ), }); } index = end; diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index 1c305ebff5d..23fb0943e78 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -99,18 +99,14 @@ fn eval_expr( ) -> TbValue { let (memory, _) = sim.backend.memory_as_ptr(); let trace = sim.backend.layout().trace.as_ref(); - expr.eval_with_strings( - memory.cast_mut(), - &mut sim.testbench_strings, - |offset, len| { - if let Some(trace) = trace { - // SAFETY: bytecode is bound to this simulator's memory layout. - unsafe { - trace.mark_range(memory.cast_mut(), offset, len); - } + expr.eval_with_heap(memory.cast_mut(), Some(&mut sim.heap), |offset, len| { + if let Some(trace) = trace { + // SAFETY: bytecode is bound to this simulator's memory layout. + unsafe { + trace.mark_range(memory.cast_mut(), offset, len); } - }, - ) + } + }) } pub(crate) fn eval_backend_expr( @@ -253,12 +249,19 @@ fn sim_set_target( value: TbValue, ) { if let TbValue::String(bytes) = value { + // A selection names a string element by its bit offset. let index = target.selection.as_ref().map_or(0, |selection| { - eval_expr(sim, &selection.offset).to_u64() as usize + eval_expr(sim, &selection.offset).to_u64() as usize / celox_design::HANDLE_WIDTH }); - if index < target.signal.width { - sim.testbench_strings - .insert((target.signal.offset, index), bytes); + if index < target.signal.width / celox_design::HANDLE_WIDTH { + let handle = sim.heap.intern(&bytes); + let element = SignalRef { + offset: target.signal.offset + index * celox_heap::HANDLE_BYTES, + width: celox_design::HANDLE_WIDTH, + is_4state: false, + array_layout: None, + }; + sim.set(element, handle); } return; } @@ -290,6 +293,32 @@ fn sim_set_target( ); } +/// Collect the heap between concurrent process polls. The saved temporaries of +/// suspended processes are outside state memory, so their handles are roots. +fn collect_testbench_heap( + sim: &mut Simulator, + private_signals: &[SignalRef], + locals: &[Vec<(BigUint, BigUint)>], +) { + if !sim.heap.should_collect() { + return; + } + let slots = sim.handle_slots(); + let saved_roots: Vec = private_signals + .iter() + .enumerate() + .filter(|(_, signal)| slots.binary_search(&signal.offset).is_ok()) + .flat_map(|(index, signal)| { + let elements = signal.width / celox_design::HANDLE_WIDTH; + locals.iter().flat_map(move |process| { + let digits = process[index].0.to_u32_digits(); + (0..elements).map(move |element| digits.get(element).copied().unwrap_or(0)) + }) + }) + .collect(); + sim.maybe_collect_heap(saved_roots); +} + fn execution_random_seed(seed: Option) -> u64 { seed.unwrap_or_else(rand::random) } @@ -1797,6 +1826,9 @@ fn exec_testbench( Poll::Pending => debug_assert!(wait.borrow().is_some()), } } + // No process is running, so every string handle is in state memory or + // in a suspended process's saved temporaries. + collect_testbench_heap(&mut sim.borrow_mut(), testbench.private_signals(), &locals); for wait in &waits { if let Some(wait) = wait.borrow().as_ref() && wait.remaining != 0 @@ -1973,6 +2005,9 @@ fn exec_detailed( ) -> ExecResult { for stmt in stmts { let r = exec_one_detailed(sim, stmt, ctx); + // Only a single process runs here, so between statements every string + // handle is in state memory. + sim.maybe_collect_heap([]); // Stop on control-flow transfers or hard errors. Assertion failures that // are allowed to continue return `Continue` and are recorded in `ctx`. if matches!( diff --git a/crates/celox/tests/testbench_string.rs b/crates/celox/tests/testbench_string.rs index 2736f0d1198..574530a26d4 100644 --- a/crates/celox/tests/testbench_string.rs +++ b/crates/celox/tests/testbench_string.rs @@ -146,12 +146,6 @@ fn checkpoint_restores_string_values() { ); let saved = sim.checkpoint().unwrap(); assert_eq!(saved.state_size(), empty_size + b"saved string".len()); - assert!( - sim.save_state() - .unwrap_err() - .to_string() - .contains("dynamic testbench strings") - ); sim.set(mode, 1u32); assert_eq!( run_compiled_testbench(&mut sim, &program), @@ -165,6 +159,159 @@ fn checkpoint_restores_string_values() { ); } +#[test] +fn state_files_restore_string_values_by_contents() { + use celox::testbench::{compile_initial_testbench, run_compiled_testbench}; + let source = r#" + #[test(Top)] module Top { + var text: string; + var names: string[3]; + var mode: u32; + initial { + if mode == 0 { + text = "saved string"; + names[1] = "one"; + names[2] = "two"; + } else if mode == 1 { + text = "replacement"; + names[1] = "uno"; + } else { + $assert(text == "saved string", "[%s]", text); + $assert(names[0] == "", "[%s]", names[0]); + $assert(names[1] == "one", "[%s]", names[1]); + $assert(names[2] == "two", "[%s]", names[2]); + } + $finish(); + } + } + "#; + let mut sim = celox::Simulator::builder(source, "Top") + .build_interpreter() + .unwrap(); + let program = compile_initial_testbench(&sim).unwrap(); + let mode = sim.signal("mode"); + sim.set(mode, 0u32); + assert_eq!( + run_compiled_testbench(&mut sim, &program), + celox::TestResult::Pass + ); + let saved = sim.save_state().unwrap(); + assert_eq!( + saved.strings, + [b"one".to_vec(), b"two".to_vec(), b"saved string".to_vec()] + ); + let mut bytes = Vec::new(); + saved.write_to(&mut bytes).unwrap(); + let saved = celox::StateFile::read_from(bytes.as_slice()).unwrap(); + + sim.set(mode, 1u32); + assert_eq!( + run_compiled_testbench(&mut sim, &program), + celox::TestResult::Pass + ); + // A fresh simulator has none of the saved strings in its heap, so the + // file must carry their contents. + for target in [ + &mut sim, + &mut celox::Simulator::builder(source, "Top") + .build_interpreter() + .unwrap(), + ] { + target.load_state(&saved).unwrap(); + let mode = target.signal("mode"); + target.set(mode, 2u32); + assert_eq!( + run_compiled_testbench(target, &program), + celox::TestResult::Pass + ); + } +} + +#[test] +fn collected_heap_keeps_reachable_strings() { + use celox::testbench::{compile_initial_testbench, run_compiled_testbench}; + // More distinct strings than one collection interval. + let values: Vec = (0..1500).map(|index| format!("value {index}")).collect(); + let assignments: String = values + .iter() + .map(|value| format!("text = \"{value}\"; clk.next();\n")) + .collect(); + let source = format!( + r#" + #[test(Top)] module Top {{ + var kept: string; + var text: string; + inst clk: $tb::clock_gen; + initial {{ + kept = "kept"; + {assignments} + $assert(kept == "kept", "[%s]", kept); + $assert(text == "value 1499", "[%s]", text); + $finish(); + }} + }} + "# + ); + let mut sim = celox::Simulator::builder(&source, "Top") + .build_interpreter() + .unwrap(); + let program = compile_initial_testbench(&sim).unwrap(); + let empty_size = sim.checkpoint().unwrap().state_size(); + assert_eq!( + run_compiled_testbench(&mut sim, &program), + celox::TestResult::Pass + ); + // Without a collection the heap would hold every value. + let all_values: usize = values.iter().map(String::len).sum::() + b"kept".len(); + assert!(sim.checkpoint().unwrap().state_size() - empty_size < all_values / 2); +} + +#[test] +fn concurrent_processes_keep_strings_across_collections() { + use celox::testbench::{compile_initial_testbench, run_compiled_testbench}; + let values: Vec = (0..1500).map(|index| format!("value {index}")).collect(); + let assignments: String = values + .iter() + .map(|value| format!("text = identity(\"{value}\"); clk.next();\n")) + .collect(); + let source = format!( + r#" + #[test(Top)] module Top {{ + var kept: string; + var text: string; + var done: bit; + inst clk: $tb::clock_gen; + function identity(value: input string) -> string {{ + return value; + }} + initial {{ + kept = identity("kept"); + clk.next(1600); + $assert(kept == "kept", "[%s]", kept); + $assert(done == 1); + $finish(); + }} + initial {{ + {assignments} + $assert(text == "value 1499", "[%s]", text); + done = 1; + }} + }} + "# + ); + let mut sim = celox::Simulator::builder(&source, "Top") + .build_interpreter() + .unwrap(); + let program = compile_initial_testbench(&sim).unwrap(); + let empty_size = sim.checkpoint().unwrap().state_size(); + assert_eq!( + run_compiled_testbench(&mut sim, &program), + celox::TestResult::Pass + ); + let all_values: usize = values.iter().map(String::len).sum::() + b"kept".len(); + assert!(sim.checkpoint().unwrap().state_size() - empty_size < all_values / 2); +} + #[test] fn unsupported_string_concatenation_is_rejected() { for expression in ["{a, b}", "{a repeat 2}"] { diff --git a/crates/lydite-celox/src/tests.rs b/crates/lydite-celox/src/tests.rs index 92f08e7a69d..0dc77c141c7 100644 --- a/crates/lydite-celox/src/tests.rs +++ b/crates/lydite-celox/src/tests.rs @@ -462,6 +462,7 @@ fn exported_array_width_is_total_not_per_element() { kind: DomainKind::Other, type_kind: PortTypeKind::Bit, array_dims: array_dims.to_vec(), + value_kind: Default::default(), }) }; assert_eq!(shape(64, &[2]).unwrap(), (32, 2)); diff --git a/crates/lydite-celox/tests/fixtures/array_read_write2.json b/crates/lydite-celox/tests/fixtures/array_read_write2.json index 0ab8cb5adb8..26d02f21004 100644 --- a/crates/lydite-celox/tests/fixtures/array_read_write2.json +++ b/crates/lydite-celox/tests/fixtures/array_read_write2.json @@ -1 +1 @@ -{"allow_always_ff_function_effects":true,"allowed_diagnostics":[],"design":{"cascaded_events":[],"event_aliases":[],"initial_state":[],"ordered_events":[{"instance_id":0,"var_id":0}],"reset_clocks":[],"state_objects":[{"address":{"instance_id":0,"var_id":0},"metadata":{"array_dims":[],"is_4state":true,"kind":"ClockPosedge","type_kind":"Clock","width":1}},{"address":{"instance_id":0,"var_id":7},"metadata":{"array_dims":[2],"is_4state":false,"kind":"Other","type_kind":"Bit","width":64}},{"address":{"instance_id":0,"var_id":4},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":32}},{"address":{"instance_id":0,"var_id":1},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1}},{"address":{"instance_id":0,"var_id":5},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1}},{"address":{"instance_id":0,"var_id":2},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1}},{"address":{"instance_id":0,"var_id":6},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":32}},{"address":{"instance_id":0,"var_id":3},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1}}]},"four_state":false,"frontend_lookup":"FrontendLookup { instances: 1, modules: 1, projected_state_objects: 8, .. }","runtime_event_sites":[],"signals":[{"address":{"instance_id":0,"var_id":0},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":true,"kind":"ClockPosedge","type_kind":"Clock","width":1},"path":["clk"],"signed":false},{"address":{"instance_id":0,"var_id":7},"instances":[],"kind":"Output","metadata":{"array_dims":[2],"is_4state":false,"kind":"Other","type_kind":"Bit","width":64},"path":["mem"],"signed":false},{"address":{"instance_id":0,"var_id":4},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":32},"path":["wd"],"signed":false},{"address":{"instance_id":0,"var_id":1},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1},"path":["rst"],"signed":false},{"address":{"instance_id":0,"var_id":5},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1},"path":["ra0"],"signed":false},{"address":{"instance_id":0,"var_id":2},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1},"path":["we"],"signed":false},{"address":{"instance_id":0,"var_id":6},"instances":[],"kind":"Output","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":32},"path":["q0"],"signed":false},{"address":{"instance_id":0,"var_id":3},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","width":1},"path":["wa"],"signed":false}],"sir":{"apply_ffs":[],"eval_apply_ffs":[{"event":{"instance_id":0,"var_id":0},"units":[{"blocks":{"0":{"id":0,"instructions":[{"Commit":[{"instance_id":0,"region":0,"var_id":6},{"instance_id":0,"region":1,"var_id":6},{"Static":0},32,[]]},{"Load":[0,{"instance_id":0,"region":0,"var_id":1},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":0,"false_block":[2,[]],"true_block":[1,[]]}}},"1":{"id":1,"instructions":[{"Imm":[1,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":0},32,1,[],[]]},{"Imm":[2,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":32},32,2,[],[]]},{"Imm":[3,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":1,"var_id":6},{"Static":0},32,3,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}},"2":{"id":2,"instructions":[{"Load":[4,{"instance_id":0,"region":0,"var_id":2},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":4,"false_block":[5,[]],"true_block":[4,[]]}}},"3":{"id":3,"instructions":[{"Commit":[{"instance_id":0,"region":1,"var_id":6},{"instance_id":0,"region":0,"var_id":6},{"Static":0},32,[]]},{"Commit":[{"instance_id":0,"region":2,"var_id":7},{"instance_id":0,"region":0,"var_id":7},{"Static":0},64,[]]}],"params":[],"terminator":"Return"},"4":{"id":4,"instructions":[{"Load":[5,{"instance_id":0,"region":0,"var_id":4},{"Static":0},32]},{"Load":[6,{"instance_id":0,"region":0,"var_id":3},{"Static":0},1]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":6}},32,5,[],[]]}],"params":[],"terminator":{"Jump":[6,[]]}},"5":{"id":5,"instructions":[],"params":[],"terminator":{"Jump":[6,[]]}},"6":{"id":6,"instructions":[{"Load":[8,{"instance_id":0,"region":0,"var_id":5},{"Static":0},1]},{"Load":[7,{"instance_id":0,"region":0,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":8}},32]},{"Store":[{"instance_id":0,"region":1,"var_id":6},{"Static":0},32,7,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}}},"entry_block_id":0,"register_map":{"0":{"Bit":{"signed":false,"width":1}},"1":{"Bit":{"signed":false,"width":32}},"2":{"Bit":{"signed":false,"width":32}},"3":{"Bit":{"signed":false,"width":32}},"4":{"Bit":{"signed":false,"width":1}},"5":{"Bit":{"signed":false,"width":32}},"6":{"Bit":{"signed":false,"width":1}},"7":{"Bit":{"signed":false,"width":32}},"8":{"Bit":{"signed":false,"width":1}}}}]}],"eval_comb":[{"blocks":{"0":{"id":0,"instructions":[],"params":[],"terminator":"Return"}},"entry_block_id":0,"register_map":{}}],"eval_comb_apply_ffs":[{"event":{"instance_id":0,"var_id":0},"units":[{"blocks":{"0":{"id":0,"instructions":[{"Load":[0,{"instance_id":0,"region":0,"var_id":1},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":0,"false_block":[2,[]],"true_block":[1,[]]}}},"1":{"id":1,"instructions":[{"Imm":[1,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":0},32,1,[],[]]},{"Imm":[2,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":32},32,2,[],[]]},{"Imm":[3,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":0,"var_id":6},{"Static":0},32,3,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}},"2":{"id":2,"instructions":[{"Load":[4,{"instance_id":0,"region":0,"var_id":2},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":4,"false_block":[5,[]],"true_block":[4,[]]}}},"3":{"id":3,"instructions":[{"Commit":[{"instance_id":0,"region":2,"var_id":7},{"instance_id":0,"region":0,"var_id":7},{"Static":0},64,[]]}],"params":[],"terminator":"Return"},"4":{"id":4,"instructions":[{"Load":[5,{"instance_id":0,"region":0,"var_id":4},{"Static":0},32]},{"Load":[6,{"instance_id":0,"region":0,"var_id":3},{"Static":0},1]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":6}},32,5,[],[]]}],"params":[],"terminator":{"Jump":[6,[]]}},"5":{"id":5,"instructions":[],"params":[],"terminator":{"Jump":[6,[]]}},"6":{"id":6,"instructions":[{"Load":[8,{"instance_id":0,"region":0,"var_id":5},{"Static":0},1]},{"Load":[7,{"instance_id":0,"region":0,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":8}},32]},{"Store":[{"instance_id":0,"region":0,"var_id":6},{"Static":0},32,7,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}}},"entry_block_id":0,"register_map":{"0":{"Bit":{"signed":false,"width":1}},"1":{"Bit":{"signed":false,"width":32}},"2":{"Bit":{"signed":false,"width":32}},"3":{"Bit":{"signed":false,"width":32}},"4":{"Bit":{"signed":false,"width":1}},"5":{"Bit":{"signed":false,"width":32}},"6":{"Bit":{"signed":false,"width":1}},"7":{"Bit":{"signed":false,"width":32}},"8":{"Bit":{"signed":false,"width":1}}}}]}],"eval_only_ffs":[]},"status":"compiled_only_not_verified"} +{"allow_always_ff_function_effects":true,"allowed_diagnostics":[],"design":{"cascaded_events":[],"event_aliases":[],"initial_state":[],"ordered_events":[{"instance_id":0,"var_id":0}],"reset_clocks":[],"state_objects":[{"address":{"instance_id":0,"var_id":0},"metadata":{"array_dims":[],"is_4state":true,"kind":"ClockPosedge","type_kind":"Clock","value_kind":"Bits","width":1}},{"address":{"instance_id":0,"var_id":7},"metadata":{"array_dims":[2],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":64}},{"address":{"instance_id":0,"var_id":4},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":32}},{"address":{"instance_id":0,"var_id":1},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1}},{"address":{"instance_id":0,"var_id":5},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1}},{"address":{"instance_id":0,"var_id":2},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1}},{"address":{"instance_id":0,"var_id":6},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":32}},{"address":{"instance_id":0,"var_id":3},"metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1}}]},"four_state":false,"frontend_lookup":"FrontendLookup { instances: 1, modules: 1, projected_state_objects: 8, .. }","runtime_event_sites":[],"signals":[{"address":{"instance_id":0,"var_id":0},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":true,"kind":"ClockPosedge","type_kind":"Clock","value_kind":"Bits","width":1},"path":["clk"],"signed":false},{"address":{"instance_id":0,"var_id":7},"instances":[],"kind":"Output","metadata":{"array_dims":[2],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":64},"path":["mem"],"signed":false},{"address":{"instance_id":0,"var_id":4},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":32},"path":["wd"],"signed":false},{"address":{"instance_id":0,"var_id":1},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1},"path":["rst"],"signed":false},{"address":{"instance_id":0,"var_id":5},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1},"path":["ra0"],"signed":false},{"address":{"instance_id":0,"var_id":2},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1},"path":["we"],"signed":false},{"address":{"instance_id":0,"var_id":6},"instances":[],"kind":"Output","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":32},"path":["q0"],"signed":false},{"address":{"instance_id":0,"var_id":3},"instances":[],"kind":"Input","metadata":{"array_dims":[],"is_4state":false,"kind":"Other","type_kind":"Bit","value_kind":"Bits","width":1},"path":["wa"],"signed":false}],"sir":{"apply_ffs":[],"eval_apply_ffs":[{"event":{"instance_id":0,"var_id":0},"units":[{"blocks":{"0":{"id":0,"instructions":[{"Commit":[{"instance_id":0,"region":0,"var_id":6},{"instance_id":0,"region":1,"var_id":6},{"Static":0},32,[]]},{"Load":[0,{"instance_id":0,"region":0,"var_id":1},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":0,"false_block":[2,[]],"true_block":[1,[]]}}},"1":{"id":1,"instructions":[{"Imm":[1,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":0},32,1,[],[]]},{"Imm":[2,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":32},32,2,[],[]]},{"Imm":[3,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":1,"var_id":6},{"Static":0},32,3,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}},"2":{"id":2,"instructions":[{"Load":[4,{"instance_id":0,"region":0,"var_id":2},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":4,"false_block":[5,[]],"true_block":[4,[]]}}},"3":{"id":3,"instructions":[{"Commit":[{"instance_id":0,"region":1,"var_id":6},{"instance_id":0,"region":0,"var_id":6},{"Static":0},32,[]]},{"Commit":[{"instance_id":0,"region":2,"var_id":7},{"instance_id":0,"region":0,"var_id":7},{"Static":0},64,[]]}],"params":[],"terminator":"Return"},"4":{"id":4,"instructions":[{"Load":[5,{"instance_id":0,"region":0,"var_id":4},{"Static":0},32]},{"Load":[6,{"instance_id":0,"region":0,"var_id":3},{"Static":0},1]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":6}},32,5,[],[]]}],"params":[],"terminator":{"Jump":[6,[]]}},"5":{"id":5,"instructions":[],"params":[],"terminator":{"Jump":[6,[]]}},"6":{"id":6,"instructions":[{"Load":[8,{"instance_id":0,"region":0,"var_id":5},{"Static":0},1]},{"Load":[7,{"instance_id":0,"region":0,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":8}},32]},{"Store":[{"instance_id":0,"region":1,"var_id":6},{"Static":0},32,7,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}}},"entry_block_id":0,"register_map":{"0":{"Bit":{"signed":false,"width":1}},"1":{"Bit":{"signed":false,"width":32}},"2":{"Bit":{"signed":false,"width":32}},"3":{"Bit":{"signed":false,"width":32}},"4":{"Bit":{"signed":false,"width":1}},"5":{"Bit":{"signed":false,"width":32}},"6":{"Bit":{"signed":false,"width":1}},"7":{"Bit":{"signed":false,"width":32}},"8":{"Bit":{"signed":false,"width":1}}}}]}],"eval_comb":[{"blocks":{"0":{"id":0,"instructions":[],"params":[],"terminator":"Return"}},"entry_block_id":0,"register_map":{}}],"eval_comb_apply_ffs":[{"event":{"instance_id":0,"var_id":0},"units":[{"blocks":{"0":{"id":0,"instructions":[{"Load":[0,{"instance_id":0,"region":0,"var_id":1},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":0,"false_block":[2,[]],"true_block":[1,[]]}}},"1":{"id":1,"instructions":[{"Imm":[1,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":0},32,1,[],[]]},{"Imm":[2,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Static":32},32,2,[],[]]},{"Imm":[3,{"mask":[0],"payload":[0]}]},{"Store":[{"instance_id":0,"region":0,"var_id":6},{"Static":0},32,3,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}},"2":{"id":2,"instructions":[{"Load":[4,{"instance_id":0,"region":0,"var_id":2},{"Static":0},1]}],"params":[],"terminator":{"Branch":{"cond":4,"false_block":[5,[]],"true_block":[4,[]]}}},"3":{"id":3,"instructions":[{"Commit":[{"instance_id":0,"region":2,"var_id":7},{"instance_id":0,"region":0,"var_id":7},{"Static":0},64,[]]}],"params":[],"terminator":"Return"},"4":{"id":4,"instructions":[{"Load":[5,{"instance_id":0,"region":0,"var_id":4},{"Static":0},32]},{"Load":[6,{"instance_id":0,"region":0,"var_id":3},{"Static":0},1]},{"Store":[{"instance_id":0,"region":2,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":6}},32,5,[],[]]}],"params":[],"terminator":{"Jump":[6,[]]}},"5":{"id":5,"instructions":[],"params":[],"terminator":{"Jump":[6,[]]}},"6":{"id":6,"instructions":[{"Load":[8,{"instance_id":0,"region":0,"var_id":5},{"Static":0},1]},{"Load":[7,{"instance_id":0,"region":0,"var_id":7},{"Element":{"bit_offset":0,"dynamic_bit_offset":null,"element_width":32,"index":8}},32]},{"Store":[{"instance_id":0,"region":0,"var_id":6},{"Static":0},32,7,[],[]]}],"params":[],"terminator":{"Jump":[3,[]]}}},"entry_block_id":0,"register_map":{"0":{"Bit":{"signed":false,"width":1}},"1":{"Bit":{"signed":false,"width":32}},"2":{"Bit":{"signed":false,"width":32}},"3":{"Bit":{"signed":false,"width":32}},"4":{"Bit":{"signed":false,"width":1}},"5":{"Bit":{"signed":false,"width":32}},"6":{"Bit":{"signed":false,"width":1}},"7":{"Bit":{"signed":false,"width":32}},"8":{"Bit":{"signed":false,"width":1}}}}]}],"eval_only_ffs":[]},"status":"compiled_only_not_verified"} diff --git a/docs/internals/compiler-crate-architecture.md b/docs/internals/compiler-crate-architecture.md index 2afc09c893b..c2ec6c42dbe 100644 --- a/docs/internals/compiler-crate-architecture.md +++ b/docs/internals/compiler-crate-architecture.md @@ -186,6 +186,7 @@ for. | `celox-backend-x86` | x86 MIR, instruction selection, target allocation policy, and machine-code emission | Frontend or runtime policy | | `celox-backend-cranelift` | Cranelift translation and JIT construction | Frontend or x86-specific MIR | | `celox-backend-wasm` | WebAssembly module generation | Host runtime behavior | +| `celox-heap` | Dynamic values referenced by handles from state memory, and their collection | Root discovery, layouts, or scheduling | | `celox-testbench` | Source-independent testbench bytecode and values | Veryl AST traversal or simulator memory ownership | | `celox-runtime` | Events, timed scheduling, VCD output, testbench execution, and backend contracts | Frontend, SIR optimization, or concrete backend internals | | `celox` | Public API, compilation orchestration, and backend selection | New reusable compiler algorithms | diff --git a/flake.lock b/flake.lock index ffe30a922aa..3b5540491ee 100644 --- a/flake.lock +++ b/flake.lock @@ -7,11 +7,11 @@ ] }, "locked": { - "lastModified": 1792488653, - "narHash": "sha256-6mDIj7DP6kHQAdT0B7N8QpC3KBrY6W8LEenKg3GGfM0=", + "lastModified": 1792542234, + "narHash": "sha256-485fkwc2ZSHqtC+FpF2CrtuynntL4fm378pF0nBRZHQ=", "owner": "tignear", "repo": "nix-packages", - "rev": "683234e1ef474a6fbb653ce7ec11aa4657d49975", + "rev": "d0eff0edac65dd338f780e84882a4dc7e473ec28", "type": "github" }, "original": { diff --git a/scripts/publish-crates.sh b/scripts/publish-crates.sh index 4e8b5afe6ef..4751671c3c4 100755 --- a/scripts/publish-crates.sh +++ b/scripts/publish-crates.sh @@ -25,6 +25,7 @@ crates=( celox-frontend-sdk celox-macros celox-ts-gen + celox-heap celox-testbench celox-sir celox-state-layout