use crate::traversal::{Action, Named, VisResult, Visitor};
use calyx_ir::{self as ir};
use std::collections::{HashMap, HashSet};
fn get_comb_dependence_map<T>(
assigns: &Vec<ir::Assignment<T>>,
) -> HashMap<ir::Id, HashSet<ir::Id>> {
let mut comb_dependence_map: HashMap<ir::Id, HashSet<ir::Id>> =
HashMap::new();
for assign in assigns {
let src = assign.src.borrow();
let dst = assign.dst.borrow();
let dst_name = dst.get_parent_name();
if dst.parent_is_comb() {
if src.parent_is_comb() {
comb_dependence_map
.entry(dst_name)
.or_default()
.insert(src.get_parent_name());
}
for p in assign.guard.all_ports() {
if p.borrow().parent_is_comb() {
comb_dependence_map
.entry(dst_name)
.or_default()
.insert(p.borrow().get_parent_name());
}
}
}
}
comb_dependence_map
}
fn get_non_comb_writes<T>(assigns: &Vec<ir::Assignment<T>>) -> Vec<ir::Id> {
let mut non_comb_writes: Vec<ir::Id> = Vec::new();
for assign in assigns {
if !assign.dst.borrow().parent_is_comb() {
let src = assign.src.borrow();
let src_name = src.get_parent_name();
if src.parent_is_comb() {
non_comb_writes.push(src_name);
}
for p in assign.guard.all_ports() {
let p_name = p.borrow().get_parent_name();
if p.borrow().parent_is_comb() {
non_comb_writes.push(p_name);
}
}
}
}
non_comb_writes
}
#[derive(Default)]
pub struct DeadAssignmentRemoval;
impl Named for DeadAssignmentRemoval {
fn name() -> &'static str {
"dead-assign-removal"
}
fn description() -> &'static str {
"removes assignments that are never used inside a group"
}
}
impl Visitor for DeadAssignmentRemoval {
fn enable(
&mut self,
s: &mut ir::Enable,
_comp: &mut ir::Component,
_sigs: &ir::LibrarySignatures,
_comps: &[ir::Component],
) -> VisResult {
let mut comb_dependence_map: HashMap<ir::Id, HashSet<ir::Id>> =
get_comb_dependence_map(&s.group.borrow().assignments);
let mut non_comb_writes: Vec<ir::Id> =
get_non_comb_writes(&s.group.borrow().assignments);
let mut used_combs: HashSet<ir::Id> = HashSet::new();
while !(non_comb_writes.is_empty()) {
let used = non_comb_writes.pop().unwrap();
if let Some(write_to_used) = comb_dependence_map.remove(&used) {
for write in write_to_used {
non_comb_writes.push(write);
}
}
used_combs.insert(used);
}
s.group.borrow_mut().assignments.retain(|assign| {
let dst = assign.dst.borrow();
if dst.parent_is_comb() {
return used_combs.contains(&dst.get_parent_name());
}
!assign.guard.is_false()
});
Ok(Action::Continue)
}
}