Skip to content
Closed
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
65 changes: 62 additions & 3 deletions crates/celox-frontend-sv/src/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1117,6 +1117,60 @@ fn shared_edge_memories(
memories
}

/// Variables, other than unpacked arrays, that several plain edge-triggered
/// `always` processes write only by blocking assignments, such as a loop
/// index they share. A variable may have several procedural writers, and the
/// last write determines its value (IEEE 1800-2023 6.5); only always_comb,
/// always_latch and always_ff restrict it to one process (9.2.2.2, 9.2.2.4).
/// The processes read and write the variable's stable state directly (see
/// `Ff::with_shared_variables`).
fn shared_edge_variables(
module: &sv::ir::Module,
constants: &HashMap<String, i128>,
parameter_types: &HashMap<String, (usize, bool)>,
) -> HashSet<String> {
let first_ff = module.comb_processes().len();
let end_ff = first_ff + module.ff_processes().len();
let mut nonblocking = HashSet::default();
for process in module.ff_processes() {
for stmt in process.body() {
stmt.walk(&mut |stmt| match stmt {
sv::ir::Stmt::Assign {
lhs,
nonblocking: true,
..
} => {
nonblocking.insert(lhs.name());
}
sv::ir::Stmt::AssignConcat {
parts,
nonblocking: true,
..
} => nonblocking.extend(parts.iter().map(sv::ir::LValue::name)),
_ => {}
});
}
}
module
.signals()
.iter()
.filter(|signal| {
!signal.is_net()
&& signal.r#type().unpacked_ranges().is_empty()
&& !nonblocking.contains(signal.name())
})
.filter(|signal| {
let drivers = local_driver_ranges(module, signal.name(), constants, parameter_types);
drivers.iter().any(|(id, _)| drivers[0].0 != *id)
&& drivers.iter().all(|(id, _)| {
(first_ff..end_ff).contains(id)
&& !module.ff_processes()[id - first_ff].is_always_ff()
})
})
.map(|signal| signal.name().to_string())
.collect()
}

/// The unpacked arrays that only edge-triggered processes of `module` drive.
/// A process that writes one of them only by nonblocking assignments, at
/// least one of them at a run-time element, publishes just the elements it
Expand Down Expand Up @@ -1399,7 +1453,7 @@ fn validate_variable_driver_ranges(
module: &sv::ir::Module,
constants: &HashMap<String, i128>,
parameter_types: &HashMap<String, (usize, bool)>,
shared_memories: &HashSet<String>,
shared: &HashSet<String>,
) -> Result<(), sv::AnalyzerError> {
for port in module
.ports()
Expand Down Expand Up @@ -1448,7 +1502,7 @@ fn validate_variable_driver_ranges(
&& net_driver_ranges_overlap(left.1, right.1)
})
});
if overlapping_continuous || (has_overlap && !shared_memories.contains(signal_name)) {
if overlapping_continuous || (has_overlap && !shared.contains(signal_name)) {
return Err(sv::AnalyzerError::Unsupported(format!(
"multiple variable drivers for `{signal_name}`"
)));
Expand Down Expand Up @@ -3303,7 +3357,9 @@ fn lower_module_with_overrides(
foreign_writes,
warnings,
);
validate_variable_driver_ranges(module, &constants, &parameter_types, &shared_memories)?;
let shared_variables = shared_edge_variables(module, &constants, &parameter_types);
let shared_all = shared_memories.union(&shared_variables).cloned().collect();
validate_variable_driver_ranges(module, &constants, &parameter_types, &shared_all)?;
validate_foreign_drivers(
module,
&constants,
Expand Down Expand Up @@ -3651,6 +3707,7 @@ fn lower_module_with_overrides(
&ff_event_roles,
&shared_memories,
foreign_writes,
&shared_variables,
&mut repeated_ff_writes,
)?;
(
Expand Down Expand Up @@ -9141,6 +9198,7 @@ fn lower_ff_processes(
ff_event_roles: &[FfEventRole],
shared_memories: &HashSet<String>,
foreign_writes: &HashMap<String, hierarchy::ForeignWrites>,
shared_variables: &HashSet<String>,
repeated_writes: &mut Vec<FfWriteStream>,
) -> Result<SvFfBlocks, sv::AnalyzerError> {
let mut parallel_ff_parts = HashMap::<_, Vec<_>>::default();
Expand Down Expand Up @@ -9269,6 +9327,7 @@ fn lower_ff_processes(
staged,
} = ff::Ff::new(pm, random_seeds[&(0, index)])
.with_sparse_memories(shared_memories)
.with_shared_variables(shared_variables)
.with_sparse_candidates(&edge_memories)
.with_window_writes(&window_writes)
.lower_process(process.body())?;
Expand Down
37 changes: 31 additions & 6 deletions crates/celox-frontend-sv/src/lowering/ff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,9 @@ pub(super) struct Ff<'p, 'a> {
/// Variables a process kernel may write between the evaluation of this
/// process and the NBA region (see `kernel_window_writes`).
window_writes: HashSet<SourceVarId>,
/// Variables several edge processes write by blocking assignments (see
/// `with_shared_variables`).
shared: HashSet<SourceVarId>,
b: SIRBuilder<Addr>,
/// Variables read from the working region.
working: HashSet<SourceVarId>,
Expand Down Expand Up @@ -129,6 +132,7 @@ impl<'p, 'a> Ff<'p, 'a> {
element_writes: HashSet::default(),
other_writes: HashSet::default(),
window_writes: HashSet::default(),
shared: HashSet::default(),
b: SIRBuilder::new(),
working: HashSet::default(),
nonblocking: HashSet::default(),
Expand Down Expand Up @@ -255,10 +259,23 @@ impl<'p, 'a> Ff<'p, 'a> {
self
}

/// Variables other edge processes also write by blocking assignments.
/// The process reads and writes their stable state directly, as a
/// blocking assignment updates the variable at once (IEEE 1800-2023
/// 10.4.1): its reads see its own preceding writes, and the last write of
/// any process stays, even when a later process does not write it. A
/// working value seeded by each process would instead be committed by
/// every one of them.
pub fn with_shared_variables(mut self, names: &HashSet<String>) -> Self {
self.shared = names.iter().filter_map(|name| self.m.id(name)).collect();
self
}

/// Where a write of `id`, and a read of a value the process wrote, go:
/// the working region, or stable state in a process kernel.
/// the working region, or stable state in a process kernel and for a
/// shared variable.
fn target(&self, id: SourceVarId) -> Addr {
if self.kernel.is_some() || self.direct {
if self.kernel.is_some() || self.direct || self.shared.contains(&id) {
stable(id)
} else {
working(id)
Expand Down Expand Up @@ -475,9 +492,11 @@ impl<'p, 'a> Ff<'p, 'a> {
let working_set = &self.working;
let variables = &*self.m.variables;
let direct = self.kernel.is_some() || self.direct;
let shared = &self.shared;
let map = |id: &SourceVarId| -> Addr {
if direct {
stable(*aliases.get(id).unwrap_or(id))
let var = aliases.get(id).unwrap_or(id);
if direct || shared.contains(var) {
stable(*var)
} else if let Some(var) = aliases.get(id) {
working(*var)
} else if working_set.contains(id)
Expand Down Expand Up @@ -4268,6 +4287,11 @@ impl<'p, 'a> Ff<'p, 'a> {
})
.collect();
self.sparse_memories.extend(sparse);
if self.nonblocking.iter().any(|id| self.shared.contains(id)) {
return Err(unsupported(
"nonblocking writes to a variable several edge processes write",
));
}
if self
.working
.iter()
Expand Down Expand Up @@ -4333,11 +4357,12 @@ impl<'p, 'a> Ff<'p, 'a> {
stage_nonblocking(body, &staged, self.m)
};
// A variable staged for an exact publication has no next state of
// its own: only its merge publishes it.
// its own: only its merge publishes it. A shared variable is written
// in stable state.
let published: Vec<_> = targets
.iter()
.copied()
.filter(|target| !exact.contains(&target.id))
.filter(|target| !exact.contains(&target.id) && !self.shared.contains(&target.id))
.collect();
let ordinary_targets: Vec<_> = published
.iter()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -200,15 +200,15 @@ fn optimize_bit_extracts(
| SIRInstruction::Load(dst, _, _, _) => *dst,
_ => continue,
};
if use_count.get(&def_reg).copied().unwrap_or(0) == 0 {
// Also decrement use counts for operands of this dead instruction
if use_count.get(&def_reg).copied().unwrap_or(0) == 0 && dead_set.insert(dead_idx) {
// Multiple replacements may share this definition. Removing
// it consumes its operands once, not once per replacement.
if let SIRInstruction::Binary(_, lhs, _, rhs) = &instructions[dead_idx] {
*use_count.entry(*lhs).or_default() =
use_count.get(lhs).copied().unwrap_or(0).saturating_sub(1);
*use_count.entry(*rhs).or_default() =
use_count.get(rhs).copied().unwrap_or(0).saturating_sub(1);
}
dead_set.insert(dead_idx);
}
}
}
Expand Down Expand Up @@ -399,6 +399,69 @@ mod tests {
}
}

#[test]
fn preserves_ssa_when_replacements_share_a_shift() {
let addr = test_addr();
let other = RegionedAbsoluteAddr {
instance_id: InstanceId(1),
..addr
};
let mut unit = ExecutionUnit {
entry_block_id: BlockId(0),
blocks: [(
BlockId(0),
BasicBlock {
id: BlockId(0),
params: vec![],
instructions: vec![
SIRInstruction::Load(RegisterId(0), addr, SIROffset::Static(0), 8),
SIRInstruction::Load(RegisterId(8), other, SIROffset::Static(0), 8),
SIRInstruction::Imm(RegisterId(1), SIRValue::new(2u64)),
SIRInstruction::Binary(
RegisterId(2),
RegisterId(0),
BinaryOp::Shr,
RegisterId(1),
),
SIRInstruction::Imm(RegisterId(3), SIRValue::new(3u64)),
SIRInstruction::Binary(
RegisterId(4),
RegisterId(2),
BinaryOp::And,
RegisterId(3),
),
SIRInstruction::Imm(RegisterId(5), SIRValue::new(15u64)),
SIRInstruction::Binary(
RegisterId(6),
RegisterId(2),
BinaryOp::And,
RegisterId(5),
),
SIRInstruction::Binary(
RegisterId(7),
RegisterId(8),
BinaryOp::Shr,
RegisterId(1),
),
SIRInstruction::RuntimeEvent {
site_id: 0,
args: vec![RegisterId(4), RegisterId(6), RegisterId(7)],
},
],
terminator: SIRTerminator::Return,
},
)]
.into_iter()
.collect(),
register_map: (0..9)
.map(|id| (RegisterId(id), RegisterType::Logic { width: 8 }))
.collect(),
};
unit.verify_result().unwrap();
BitExtractPeepholePass.run(&mut unit, &PassOptions::default());
unit.verify_result().unwrap();
}

#[test]
fn keeps_shift_result_used_by_runtime_event() {
let addr = test_addr();
Expand Down
Loading
Loading