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
11 changes: 7 additions & 4 deletions crates/celox-frontend-sv/src/lowering/ff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3622,9 +3622,11 @@ impl<'p, 'a> Ff<'p, 'a> {
let mut arena = SLTNodeArena::new();
let node = self.expr_slt(rhs, Some((total, signed)), &mut arena)?;
let node = coerce_node_width(&mut arena, node, Some(total), signed).map_err(slt_error)?;
// Capture the value before any part is written.
let (temp, temp_name) = self.m.temp("concat", total, false, true);
// Capture the value before any part is written, in a temporary of
// the value's state kind.
let value = self.lower_slt(&arena, node)?;
let four_state = matches!(self.b.register(&value), RegisterType::Logic { .. });
let (temp, temp_name) = self.m.temp("concat", total, false, four_state);
self.store(temp, SIROffset::Static(0), total, value);
let mut lsb = total;
for (part, width) in parts.iter().zip(widths) {
Expand Down Expand Up @@ -7838,14 +7840,15 @@ fn impure_call(pm: &ProcModule<'_>, expr: &sv::ir::Expr) -> Option<String> {
// Container contents are immutable: reading an element is a
// value of the container handle and index, unlike a class
// property that can change without its handle changing.
// A record of a structure element is immutable as well.
sv::ir::Callee::Object(op)
if matches!(
*op,
sv::ir::ObjectOp::Container {
op: sv::ir::ContainerOp::Get,
..
}
) =>
} | sv::ir::ObjectOp::Unbox(_)
) || matches!(*op, sv::ir::ObjectOp::Load(field) if field.nullable) =>
{
continue;
}
Expand Down
148 changes: 129 additions & 19 deletions crates/celox-frontend-sv/src/lowering/ff/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,11 @@ impl Ff<'_, '_> {
.collect::<Result<Vec<_>, _>>()?;
if args.iter().any(|arg| self.m.calls(arg)) {
for (index, arg) in args.iter_mut().enumerate() {
// A record is built from a flat structure value, not a handle.
if let ObjectOp::Box(record) = op {
*arg = self.heap_operand(arg, Some((record.width(), false)), None)?;
continue;
}
let (width, signed) = if index == 0 {
(32, false)
} else {
Expand Down Expand Up @@ -118,36 +123,87 @@ impl Ff<'_, '_> {
}
ObjectOp::Load(field) if field.four_state && self.m.four_state => {
let object = self.handle(&args[0])?;
let [value, mask] = [0, field.bytes()].map(|plane| {
let offset = self.constant64(u64::from(field.offset + plane));
let count = self.constant64(u64::from(field.bytes()));
let stored = self.heap_call(ops::OBJECT_LOAD, &[object, offset, count]);
self.complement(stored)
});
let result = self.load_field(object, *field);
let width = field.width as usize;
let result = self.container_join(value, mask, width, true);
let (temp, name) = self.m.temp("object", width, field.signed, true);
self.store(temp, SIROffset::Static(0), width, result);
return Ok(sv::ir::Expr::Ident(name));
}
ObjectOp::Load(field) => {
let object = self.handle(&args[0])?;
let offset = self.constant64(u64::from(field.offset));
let count = self.constant64(u64::from(field.bytes()));
self.heap_call(ops::OBJECT_LOAD, &[object, offset, count])
self.load_field(object, *field)
}
ObjectOp::Unbox(record) => {
let object = self.handle(&args[0])?;
let parts = record
.fields
.iter()
.map(|field| self.load_field(object, *field))
.collect::<Vec<_>>();
let width = record.width();
let four_state = self.m.four_state && record.fields.iter().any(|f| f.four_state);
let value = if four_state {
self.b.alloc_logic(width)
} else {
self.b.alloc_bit(width, false)
};
self.b.emit(SIRInstruction::Concat(value, parts));
let (temp, name) = self.m.temp("record", width, false, four_state);
self.store(temp, SIROffset::Static(0), width, value);
return Ok(sv::ir::Expr::Ident(name));
}
ObjectOp::Box(record) => {
// Evaluate the value first: its calls may end the block, so
// the record's handle is only used after them.
let expr = self.hoist(&args[0])?;
let width = record.width();
let mut arena = SLTNodeArena::new();
let node = self.expr_slt(&expr, Some((width, false)), &mut arena)?;
let node =
coerce_node_width(&mut arena, node, Some(width), false).map_err(slt_error)?;
let value = self.lower_slt(&arena, node)?;
// A record is not seeded: it has no random state, and seeding
// would draw from the creating process's RNG.
let size = self.constant64(u64::from(record.size));
let object = self.heap_call(
ops::encode(ops::OBJECT_NEW, u64::from(sv::ir::Record::CLASS)),
&[size],
);
Comment thread
tignear marked this conversation as resolved.
Resolved
for field in &record.fields {
if let Some(kind) = field.handle {
let offset = self.constant64(u64::from(field.offset));
let kind = self.constant64(match kind {
HandleProperty::String => 0,
HandleProperty::Object => 1,
});
self.heap_call(ops::OBJECT_HANDLE, &[object, offset, kind]);
}
}
let mut lsb = width;
for field in &record.fields {
lsb -= field.width as usize;
let part = if matches!(self.b.register(&value), RegisterType::Logic { .. }) {
self.b.alloc_logic(field.width as usize)
} else {
self.b.alloc_bit(field.width as usize, false)
};
self.b.emit(SIRInstruction::Slice(
part,
value,
lsb,
field.width as usize,
));
self.store_field(object, *field, part);
}
// An equal value keeps the handle it already has, so that
// storing it again leaves a container unchanged.
self.heap_call(ops::OBJECT_FINISH_RECORD, &[object])
}
ObjectOp::Store(field) if field.four_state && self.m.four_state => {
let object = self.handle(&args[0])?;
let expr = self.hoist(&args[1])?;
let value = self.eval(&expr, Some((field.width as usize, field.signed)))?;
let (value, mask) = self.container_split(value);
for (plane, bits) in [(0, value), (field.bytes(), mask)] {
let place = self.constant64(
u64::from(field.offset + plane) | u64::from(field.bytes()) << 32,
);
let stored = self.complement(bits);
self.heap_call(ops::OBJECT_STORE, &[object, place, stored]);
}
self.store_field(object, *field, value);
self.constant64(0)
}
ObjectOp::Store(field) => {
Expand Down Expand Up @@ -223,7 +279,10 @@ impl Ff<'_, '_> {
let (temp, name) = self.m.temp("object", width, signed, false);
let kind = match op {
ObjectOp::Container { .. } => unreachable!("handled by container_call"),
ObjectOp::New { .. } | ObjectOp::Copy => Some(celox_design::ValueKind::ObjRef),
ObjectOp::New { .. } | ObjectOp::Copy | ObjectOp::Box(_) => {
Some(celox_design::ValueKind::ObjRef)
}
ObjectOp::Unbox(_) => unreachable!("lowered to its own temporary"),
ObjectOp::Load(field) => field.handle.map(|handle| match handle {
HandleProperty::String => celox_design::ValueKind::StrRef,
HandleProperty::Object => celox_design::ValueKind::ObjRef,
Expand Down Expand Up @@ -251,6 +310,57 @@ impl Ff<'_, '_> {
Ok(sv::ir::Expr::Ident(name))
}

/// The value of `field` of the object in 64-bit `object`: a register of
/// the field's width, 4-state for a 4-state field in 4-state simulation.
fn load_field(&mut self, object: RegisterId, field: sv::ir::ObjectField) -> RegisterId {
let opcode = if field.nullable {
ops::OBJECT_LOAD_NULLABLE
} else {
ops::OBJECT_LOAD
};
let width = field.width as usize;
if field.four_state && self.m.four_state {
let [value, mask] = [0, field.bytes()].map(|plane| {
let offset = self.constant64(u64::from(field.offset + plane));
let count = self.constant64(u64::from(field.bytes()));
let stored = self.heap_call(opcode, &[object, offset, count]);
self.complement(stored)
});
return self.container_join(value, mask, width, true);
}
let offset = self.constant64(u64::from(field.offset));
let count = self.constant64(u64::from(field.bytes()));
let loaded = self.heap_call(opcode, &[object, offset, count]);
let value = self.b.alloc_bit(width, field.signed);
self.b.emit(SIRInstruction::Slice(value, loaded, 0, width));
value
}

/// Store register `value` of `field`'s width into `field` of the object in
/// 64-bit `object`.
fn store_field(&mut self, object: RegisterId, field: sv::ir::ObjectField, value: RegisterId) {
let planes = if field.four_state && self.m.four_state {
let (value, mask) = self.container_split(value);
vec![
(0, self.complement(value)),
(field.bytes(), self.complement(mask)),
Comment thread
tignear marked this conversation as resolved.
Resolved
]
} else {
let known = self.b.alloc_bit(field.width as usize, false);
self.b
.emit(SIRInstruction::Unary(known, UnaryOp::ToTwoState, value));
let wide = self.b.alloc_bit(64, false);
self.b
.emit(SIRInstruction::Unary(wide, UnaryOp::Ident, known));
vec![(0, wide)]
};
for (plane, bits) in planes {
let place =
self.constant64(u64::from(field.offset + plane) | u64::from(field.bytes()) << 32);
self.heap_call(ops::OBJECT_STORE, &[object, place, bits]);
}
}

/// A 4-state property holds the complement of its value and mask planes,
/// so the zeroed bytes of a new object read as X (IEEE 1800-2023 6.8).
fn complement(&mut self, plane: RegisterId) -> RegisterId {
Expand Down
6 changes: 6 additions & 0 deletions crates/celox-heap/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ pub struct Heap {
next_object: Handle,
containers: HashMap<Handle, Arc<containers::Container>>,
container_lookup: HashMap<Arc<containers::Container>, Handle>,
/// Structure records by their contents, see [`ops::OBJECT_FINISH_RECORD`].
#[serde(default)]
record_lookup: HashMap<objects::RecordContents, Handle>,
/// The first heap operation error since the runtime last checked.
fault: Option<Fault>,
/// Entries below this handle are never collected.
Expand Down Expand Up @@ -112,6 +115,7 @@ impl Heap {
next_object: NULL + 1,
containers: HashMap::default(),
container_lookup: HashMap::default(),
record_lookup: HashMap::default(),
fault: None,
pinned: 1,
created: 0,
Expand Down Expand Up @@ -241,6 +245,8 @@ impl Heap {
self.containers.retain(|handle, _| objects.contains(handle));
self.container_lookup
.retain(|_, handle| objects.contains(handle));
self.record_lookup
.retain(|_, handle| objects.contains(handle));
// No buffer outlives the kernel that built it.
self.buffers.clear();
self.free_buffers.clear();
Expand Down
51 changes: 51 additions & 0 deletions crates/celox-heap/src/objects.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,36 @@ impl std::fmt::Display for Fault {
}
}

/// The contents of a structure record: its bytes and handle fields.
pub(crate) type RecordContents = (Box<[u8]>, Vec<(u32, HandleKind)>);

impl Heap {
/// The handle of the record with the contents of the finished `record`,
/// so that equal values of an unpacked structure have one handle, as
/// equal strings and containers do: `null` for the default value, whose
/// bytes are all zero (a `null` record reads as its members' defaults).
/// A record is never written after it is finished.
pub fn finish_record(&mut self, record: Handle) -> Handle {
let Some(object) = self.objects.get(&record) else {
return record;
};
if object.bytes.iter().all(|&byte| byte == 0) {
self.objects.remove(&record);
return NULL;
}
let contents = (object.bytes.clone(), object.handles.clone());
match self.record_lookup.get(&contents) {
Comment thread
tignear marked this conversation as resolved.
Resolved
Some(&canonical) if canonical != record && self.objects.contains_key(&canonical) => {
self.objects.remove(&record);
canonical
}
_ => {
self.record_lookup.insert(contents, record);
record
}
}
}

/// A new object of `class` with `size` zeroed bytes.
pub fn new_object(&mut self, class: u32, size: usize) -> Handle {
let handle = self.next_object;
Expand Down Expand Up @@ -335,6 +364,28 @@ mod tests {
assert_eq!(heap.take_fault(), None);
}

#[test]
fn equal_records_share_one_handle_until_collected() {
let mut heap = Heap::new();
let record = |heap: &mut Heap, value: u64| {
let record = heap.new_object(u32::MAX, 8);
heap.declare_handle(record, 0, HandleKind::String);
heap.store(record, 4, 4, value);
heap.finish_record(record)
};
let first = record(&mut heap, 1);
let second = record(&mut heap, 1);
let other = record(&mut heap, 2);
assert_eq!(first, second);
assert_ne!(first, other);
assert_eq!(heap.objects.len(), 2);
assert_eq!(record(&mut heap, 0), NULL);
assert_eq!(heap.objects.len(), 2);
heap.collect([Root::object(other)]);
assert_eq!(heap.record_lookup.len(), 1);
assert_ne!(record(&mut heap, 1), first);
}

#[test]
fn null_dereferences_are_faults_that_read_zero() {
let mut heap = Heap::new();
Expand Down
9 changes: 9 additions & 0 deletions crates/celox-heap/src/ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,12 @@ pub const OBJECT_RANDOMIZE_INPUTS: u64 = 65;
/// Constraint index is encoded in the parameter; set-all uses u32::MAX.
pub const OBJECT_CONSTRAINT_MODE_GET: u64 = 66;
pub const OBJECT_CONSTRAINT_MODE_SET: u64 = 67;
/// `load(record, offset, count)` of a structure record: `null` reads as
/// zero bytes without a fault.
pub const OBJECT_LOAD_NULLABLE: u64 = 68;
/// `finish(record)` of a structure record whose fields are all stored: the
/// handle of the one record with its contents, which may replace `record`.
pub const OBJECT_FINISH_RECORD: u64 = 69;

/// The opcode word of `op` with parameter `parameter`.
pub const fn encode(op: u64, parameter: u64) -> u64 {
Expand Down Expand Up @@ -196,6 +202,9 @@ impl Heap {
0
}
OBJECT_LOAD => self.load(a as Handle, b as usize, c as usize),
OBJECT_LOAD_NULLABLE if a as Handle == crate::objects::NULL => 0,
OBJECT_LOAD_NULLABLE => self.load(a as Handle, b as usize, c as usize),
OBJECT_FINISH_RECORD => self.finish_record(a as Handle).into(),
OBJECT_STORE => {
self.store(a as Handle, b as u32 as usize, (b >> 32) as usize, c);
0
Expand Down
3 changes: 3 additions & 0 deletions crates/celox-sv-analyzer/src/ast.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2291,6 +2291,9 @@ struct ContainerType {
key: Option<Type>,
layout: system_functions::ContainerLayout,
element: Type,
/// The record that holds an element of unpacked structure type which is
/// not kept as a flat value.
record: Option<system_functions::Record>,
}

impl Type {
Expand Down
20 changes: 17 additions & 3 deletions crates/celox-sv-analyzer/src/ast/case.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,23 @@ pub(super) fn expr_is_two_state(
Expr::Call {
callee: Callee::Object(op),
..
} => {
!matches!(**op, ObjectOp::Container { op, layout } if !layout.two_state && (op.reduction().is_some() || matches!(op, ContainerOp::Get | ContainerOp::PopFront | ContainerOp::PopBack | ContainerOp::Equal)))
}
} => match **op {
// A 4-state property or member of a record may hold X or Z.
ObjectOp::Load(field) => !field.four_state,
ObjectOp::Unbox(ref record) => !record.fields.iter().any(|field| field.four_state),
ObjectOp::Container { op, layout } => {
layout.two_state
|| !(op.reduction().is_some()
|| matches!(
op,
ContainerOp::Get
| ContainerOp::PopFront
| ContainerOp::PopBack
| ContainerOp::Equal
))
}
_ => true,
Comment thread
tignear marked this conversation as resolved.
Resolved
},
Expr::Call {
callee: Callee::Subroutine(name),
..
Expand Down
3 changes: 2 additions & 1 deletion crates/celox-sv-analyzer/src/ast/classes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1266,7 +1266,7 @@ fn out_of_block_definition(

/// The layout of a property of type `ty` at the first aligned offset at or
/// after `offset`.
fn field(
pub(super) fn field(
state: &AnalysisState,
ty: &Type,
env: &HashMap<String, i128>,
Expand Down Expand Up @@ -1303,6 +1303,7 @@ fn field(
ty.kind(),
TypeKind::Logic | TypeKind::Reg | TypeKind::Implicit
),
nullable: false,
})
}

Expand Down
Loading
Loading