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
8 changes: 5 additions & 3 deletions crates/celox-backend-cranelift/src/wide_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -435,12 +435,14 @@ pub(crate) fn emit_wide_unsigned_cmp(
for i in 0..num_chunks {
let l = get_chunk_as_i64(builder, l_chunks, i);
let r = get_chunk_as_i64(builder, r_chunks, i);
let eq = builder.ins().icmp(IntCC::Equal, l, r);
// Each comparison gives 0 or 1, which a branch may test
// directly: no bitwise complement of it.
cond = if matches!(op, BinaryOp::Eq) {
let eq = builder.ins().icmp(IntCC::Equal, l, r);
builder.ins().band(cond, eq)
} else {
let neq = builder.ins().bnot(eq);
builder.ins().bor(cond, neq)
let ne = builder.ins().icmp(IntCC::NotEqual, l, r);
builder.ins().bor(cond, ne)
};
}
cond
Expand Down
146 changes: 146 additions & 0 deletions crates/celox-backend-cranelift/tests/wide_equality.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
//! A branch on the equality of operands wider than 64 bits takes the side
//! the comparison gives (#2102).
use celox_backend_cranelift::*;
use celox_design::StateObjectId;
use celox_state_layout::{LayoutInput, LayoutSource, MemoryLayoutMode, StateObjectLayout};
use num_bigint::BigUint;

struct Objects(Vec<StateObjectLayout<AbsoluteAddr>>);
impl LayoutSource<AbsoluteAddr> for Objects {
fn layout_input(&self, _: MemoryLayoutMode) -> LayoutInput<AbsoluteAddr> {
LayoutInput {
state_objects: self.0.clone(),
working_addresses: vec![],
sparse_addresses: vec![],
unpacked_arrays: HashMap::default(),
requirements: Default::default(),
ff_referenced_addresses: HashSet::default(),
num_events: 0,
runtime_event_sites: vec![],
lane_writers: Default::default(),
access_rank: Default::default(),
}
}
}

/// Branch on `a op b` for 128-bit `a` and `b`, storing 1 when it holds and 2
/// otherwise.
fn branch_on(op: BinaryOp, a: &BigUint, b: &BigUint) -> u8 {
let address = |id| AbsoluteAddr {
instance_id: InstanceId(0),
var_id: StateObjectId(id),
};
let region = |id| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address(id));
let layout = MemoryLayout::build(
&Objects(
[(0, 128), (1, 128), (2, 8)]
.into_iter()
.map(|(id, width)| StateObjectLayout {
address: address(id),
width,
is_4state: false,
})
.collect(),
),
false,
MemoryLayoutMode::Packed,
);
let store = |value: u8, register: usize| BasicBlock {
id: BlockId(value as usize),
params: vec![],
instructions: vec![
SIRInstruction::Imm(RegisterId(register), SIRValue::new(value)),
SIRInstruction::Store(
region(2),
SIROffset::Static(0),
8,
RegisterId(register),
vec![],
vec![],
),
],
terminator: SIRTerminator::Return,
};
let unit = ExecutionUnit {
entry_block_id: BlockId(0),
blocks: [
(
BlockId(0),
BasicBlock {
id: BlockId(0),
params: vec![],
instructions: vec![
SIRInstruction::Load(RegisterId(0), region(0), SIROffset::Static(0), 128),
SIRInstruction::Load(RegisterId(1), region(1), SIROffset::Static(0), 128),
SIRInstruction::Binary(RegisterId(2), RegisterId(0), op, RegisterId(1)),
],
terminator: SIRTerminator::Branch {
cond: RegisterId(2),
true_block: (BlockId(1), vec![]),
false_block: (BlockId(2), vec![]),
},
},
),
(BlockId(1), store(1, 3)),
(BlockId(2), store(2, 4)),
]
.into_iter()
.collect(),
register_map: [(0, 128), (1, 128), (2, 1), (3, 8), (4, 8)]
.into_iter()
.map(|(id, width)| {
(
RegisterId(id),
RegisterType::Bit {
width,
signed: false,
},
)
})
.collect(),
};
let mut jit = JitEngine::new(
layout.clone(),
&CompileOptions {
four_state: false,
emit_triggers: false,
cranelift: Default::default(),
},
)
.unwrap();
let entry = jit.compile_units(&[unit], None, None, None).unwrap();
// The JIT owns this function for the entire test; its ABI is (memory) -> u64.
let run: unsafe extern "C" fn(*mut u8) -> u64 = unsafe { std::mem::transmute(entry) };
let mut memory = vec![0u8; layout.merged_total_size];
for (id, value) in [(0, a), (1, b)] {
let offset = layout.offsets[&address(id)];
let bytes = value.to_bytes_le();
memory[offset..offset + bytes.len()].copy_from_slice(&bytes);
}
assert_eq!(unsafe { run(memory.as_mut_ptr()) }, 0);
memory[layout.offsets[&address(2)]]
}

#[test]
fn branches_on_wide_equality_take_the_compared_side() {
let high: BigUint = BigUint::from(1u8) << 100usize;
for (a, b) in [
(high.clone(), high.clone()),
(high.clone(), &high + 1u8),
(high.clone(), BigUint::from(0u8)),
(BigUint::from(5u8), BigUint::from(5u8)),
] {
let equal = a == b;
let side = |holds: bool| if holds { 1 } else { 2 };
assert_eq!(
branch_on(BinaryOp::Eq, &a, &b),
side(equal),
"{a:x} == {b:x}"
);
assert_eq!(
branch_on(BinaryOp::Ne, &a, &b),
side(!equal),
"{a:x} != {b:x}"
);
}
}
34 changes: 28 additions & 6 deletions crates/celox-frontend-core/src/symbolic/assembly.rs
Original file line number Diff line number Diff line change
Expand Up @@ -892,7 +892,25 @@ pub fn schedule_symbolic_rtl_reporting_loops(
.values()
.map(|module| modules[module].processes.len())
.sum();
let scheduler_slots = declare_scheduler_slots(&mut modules, root_id, process_count);
// At most one event per trigger signal of each instance's domains;
// instances connected to one clock share its event. A design with more
// events than its slots hold runs without the compiled scheduler.
let expected_events = instance_modules
.values()
.map(|module| {
let module = &modules[module];
module
.eval_apply_ff_blocks
.keys()
.chain(module.eval_only_ff_blocks.keys())
.chain(module.apply_ff_blocks.keys())
.flat_map(|triggers| std::iter::once(&triggers.clock).chain(&triggers.resets))
.collect::<HashSet<_>>()
.len()
})
.sum::<usize>();
let scheduler_slots =
declare_scheduler_slots(&mut modules, root_id, process_count, expected_events);
// Each package with variables is one instance outside the hierarchy,
// named by a path segment no instance name can take.
let mut package_instances = HashMap::default();
Expand Down Expand Up @@ -2754,12 +2772,15 @@ fn declare_settle_flags(

/// Declare the hidden objects a compiled scheduler exchanges with the
/// runtime (`RuntimeSchema::scheduler`) as variables of the top module, for
/// a design with `process_count` process kernels. A design without kernels
/// has them too: host clocks may run in a compiled scheduler.
/// a design with `process_count` process kernels and about
/// `expected_events` events, whose edge and level masks hold one bit per
/// event in whole 64-bit words. A design without kernels has them too: host
/// clocks may run in a compiled scheduler.
fn declare_scheduler_slots(
modules: &mut HashMap<ModuleId, SimModule>,
root: ModuleId,
process_count: usize,
expected_events: usize,
) -> Option<celox_design::SchedulerSlots<SourceVarId>> {
let variables = &mut modules.get_mut(&root)?.variables;
let mut next = variables.keys().map(|id| id.0 + 1).max().unwrap_or(0);
Expand Down Expand Up @@ -2791,19 +2812,20 @@ fn declare_scheduler_slots(
use celox_design::{
SCHEDULER_CLOCKS as CLOCKS, SCHEDULER_FLAG_WIDTH as FLAG, SCHEDULER_TIME_WIDTH as TIME,
};
let events = expected_events.next_multiple_of(TIME).max(TIME);
Some(celox_design::SchedulerSlots {
limit: declare("limit".into(), TIME),
now: declare("now".into(), TIME),
exit: declare("exit".into(), FLAG),
exit_arg: declare("exit_arg".into(), TIME),
exit_arg: declare("exit_arg".into(), events),
Comment thread
tignear marked this conversation as resolved.
Resolved
finish: declare("finish".into(), FLAG),
cont: declare("cont".into(), FLAG),
dirty: declare("dirty".into(), FLAG),
defer_limit_settle: declare("defer_limit_settle".into(), FLAG),
count: declare("count".into(), TIME),
current: declare("current".into(), TIME),
levels: declare("levels".into(), TIME),
unknown_levels: declare("unknown_levels".into(), TIME),
levels: declare("levels".into(), events),
unknown_levels: declare("unknown_levels".into(), events),
ready: declare("ready".into(), TIME),
wake: (0..process_count)
.map(|index| declare(format!("wake[{index}]"), TIME))
Expand Down
88 changes: 72 additions & 16 deletions crates/celox-runtime/src/schedule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,52 @@ pub struct ResolvedSchedule<B: SimBackend> {

/// A design's compiled scheduler resolved against a backend: its process
/// unit and the slots it exchanges a run with.
/// A set of the compiled scheduler's events, by their bit in `levels`: one
/// 64-bit word per 64 events.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct EventMask(Vec<u64>);

impl EventMask {
/// The set of the events at `bits`.
pub(crate) fn of(bits: impl IntoIterator<Item = usize>) -> Self {
let mut mask = Self::default();
for bit in bits {
let word = bit / 64;
if mask.0.len() <= word {
mask.0.resize(word + 1, 0);
}
mask.0[word] |= 1 << (bit % 64);
}
mask
}

pub(crate) fn union(&self, other: &Self) -> Self {
let (long, short) = if self.0.len() >= other.0.len() {
(self, other)
} else {
(other, self)
};
let mut union = long.clone();
for (word, other) in union.0.iter_mut().zip(&short.0) {
*word |= other;
}
union
}

/// The events of `self` not in `other`.
pub(crate) fn difference(&self, other: &Self) -> Self {
let mut difference = self.clone();
for (word, other) in difference.0.iter_mut().zip(&other.0) {
*word &= !other;
}
difference
}

pub(crate) fn intersects(&self, other: &Self) -> bool {
self.0.iter().zip(&other.0).any(|(a, b)| a & b != 0)
}
}

pub(crate) struct SchedulerRefs {
pub(crate) unit: usize,
pub(crate) limit: SignalRef,
Expand Down Expand Up @@ -93,19 +139,29 @@ pub(crate) struct SchedulerRefs {
/// in the order of its clock slots.
pub(crate) clocks: Vec<(usize, SignalRef)>,
/// Per process kernel, the bits of `levels` of the events it writes.
pub(crate) kernel_events: Vec<u64>,
pub(crate) kernel_events: Vec<EventMask>,
/// Per clock slot, the bit of `levels` of its event.
pub(crate) clock_events: Vec<u64>,
pub(crate) clock_events: Vec<EventMask>,
/// The bits of `levels` of clocks derived from the others, which any
/// slot may change.
pub(crate) derived_events: u64,
pub(crate) derived_events: EventMask,
pub(crate) clock_next: SignalRef,
pub(crate) clock_period: SignalRef,
pub(crate) clock_value: SignalRef,
pub(crate) clock_armed: SignalRef,
}

impl SchedulerRefs {
/// The low word of `exit_arg`, where an exit that names a clock stores
/// its index. The slot is wider when it holds the edges of more than 64
/// events.
pub(crate) fn exit_index(&self) -> SignalRef {
SignalRef {
width: self.exit_arg.width.min(celox_design::SCHEDULER_TIME_WIDTH),
..self.exit_arg
}
}

/// Element `bit` of the per-clock slot `slots`.
pub(crate) fn clock_element(slots: SignalRef, bit: usize) -> SignalRef {
let width = celox_design::SCHEDULER_TIME_WIDTH;
Expand Down Expand Up @@ -479,20 +535,22 @@ impl<B: SimBackend> ResolvedSchedule<B> {
.collect::<Option<_>>()?,
kernel_events: (0..scheduler.fallback.len())
.map(|index| {
scheduler
.kernel_events
.get(index)
.into_iter()
.flatten()
.fold(0, |mask, &bit| mask | 1 << bit)
EventMask::of(
scheduler
.kernel_events
.get(index)
.into_iter()
.flatten()
.copied(),
)
})
.collect(),
clock_events: scheduler
.clocks
.iter()
.map(|clock| {
let bit = scheduler.events.iter().position(|event| event == clock)?;
Some(1 << bit)
Some(EventMask::of([bit]))
})
.collect::<Option<_>>()?,
clocks: scheduler
Expand All @@ -507,18 +565,16 @@ impl<B: SimBackend> ResolvedSchedule<B> {
clock_period: resolve(&slots.clock_period),
clock_value: resolve(&slots.clock_value),
clock_armed: resolve(&slots.clock_armed),
derived_events: 0,
derived_events: EventMask::default(),
};
// What no kernel and no clock writes itself derives from them.
let all = 1u64
.checked_shl(refs.events.len() as u32)
.map_or(u64::MAX, |bit| bit - 1);
let all = EventMask::of(0..refs.events.len());
let driven = refs
.kernel_events
.iter()
.chain(&refs.clock_events)
.fold(0, |mask, &bits| mask | bits);
refs.derived_events = all & !driven;
.fold(EventMask::default(), |mask, bits| mask.union(bits));
refs.derived_events = all.difference(&driven);
Some(refs)
}),
kernel_fallback: model
Expand Down
Loading
Loading