calyx_opt/analysis/fsm_construction.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264
use calyx_ir::{self as ir, build_assignments, guard};
use calyx_utils::math::bits_needed_for;
use core::ops::Not;
use itertools::Itertools;
use std::collections::HashMap;
type FSMPieces = (
Vec<Vec<ir::Assignment<ir::Nothing>>>,
Vec<ir::Transition>,
Vec<ir::RRC<ir::Cell>>,
);
/// Represents an FSM transition that doesn't yet have a destination state.
#[derive(Clone)]
pub struct IncompleteTransition {
source: u64,
guard: ir::Guard<ir::Nothing>,
}
impl IncompleteTransition {
pub fn new(source: u64, guard: ir::Guard<ir::Nothing>) -> Self {
Self { source, guard }
}
}
/// An instance of `StaticSchedule` is constrainted to live at least as long as
/// the component in which the static island that it represents lives.
pub struct StaticSchedule<'b, 'a: 'b> {
/// Builder construct to add hardware to the component it's built from
pub builder: &'b mut ir::Builder<'a>,
/// Number of cycles to which the static schedule should count up
pub state: u64,
/// Maps every FSM state to assignments that should be active in that state
pub state2assigns: HashMap<u64, Vec<ir::Assignment<ir::Nothing>>>,
/// Parital map from FSM state to transitions out of that state.
/// If a state has no mapping, assume it's an unconditional transition to
/// state + 1.
pub state2trans: HashMap<u64, ir::Transition>,
}
impl<'b, 'a> From<&'b mut ir::Builder<'a>> for StaticSchedule<'b, 'a> {
fn from(builder: &'b mut ir::Builder<'a>) -> Self {
StaticSchedule {
builder,
state: 0,
state2assigns: HashMap::new(),
state2trans: HashMap::new(),
}
}
}
impl StaticSchedule<'_, '_> {
pub fn leave_one_state_condition(
&mut self,
guard: ir::Guard<ir::Nothing>,
sen: &ir::StaticEnable,
) -> ir::Guard<ir::Nothing> {
let signal_on = self.builder.add_constant(1, 1);
let group_latency = sen.group.borrow().get_latency();
// instantiate a local counter register
let width = bits_needed_for(group_latency);
let counter =
self.builder
.add_primitive("group_counter", "std_reg", &[width]);
// transform all assignments in the static group to read
// from the local counter
let mut assigns = sen
.group
.borrow_mut()
.assignments
.clone()
.drain(..)
.map(|mut sassign| {
sassign.guard.replace_static_timing(
self.builder,
&counter,
&width,
&group_latency,
);
let mut assign = ir::Assignment::from(sassign);
assign.and_guard(guard.clone());
assign
})
.collect_vec();
// guard reprsenting if counter is in final state
let final_state_const =
self.builder.add_constant(group_latency - 1, width);
let final_state_wire: ir::RRC<ir::Cell> = self.builder.add_primitive(
format!("const{}_{}_", group_latency - 1, width),
"std_wire",
&[width],
);
let final_state_guard = ir::Guard::CompOp(
ir::PortComp::Eq,
counter.borrow().get("out"),
final_state_wire.borrow().get("out"),
);
let not_final_state_guard = final_state_guard.clone().not();
// build assignments to increment / reset the counter
let adder = self.builder.add_primitive("adder", "std_add", &[width]);
let const_one = self.builder.add_constant(1, width);
let const_zero = self.builder.add_constant(0, width);
let incr_counter_assigns = build_assignments!(self.builder;
final_state_wire["in"] = ? final_state_const["out"];
adder["left"] = ? counter["out"];
adder["right"] = ? const_one["out"];
counter["write_en"] = ? signal_on["out"];
counter["in"] = final_state_guard ? const_zero["out"];
counter["in"] = not_final_state_guard ? adder["out"];
);
assigns.extend(incr_counter_assigns.to_vec());
// push these assignments into the one state allocated for this
// enable
self.state2assigns
.entry(self.state)
.and_modify(|other_assigns| {
other_assigns.extend(assigns.clone());
})
.or_insert(assigns);
final_state_guard
}
pub fn register_transitions(
&mut self,
curr_state: u64,
transitions_to_curr: &mut Vec<IncompleteTransition>,
and_guard: ir::Guard<ir::Nothing>,
) {
transitions_to_curr.drain(..).for_each(
|IncompleteTransition { source, guard }| {
let complete_transition =
match (guard, &and_guard) {
(ir::Guard::True, ir::Guard::True) => {
ir::Transition::Unconditional(curr_state)
}
(ir::Guard::True, _) => ir::Transition::Conditional(
vec![(and_guard.clone(), curr_state)],
),
(guard, ir::Guard::True) => {
ir::Transition::Conditional(vec![(
guard, curr_state,
)])
}
(guard, and_guard) => ir::Transition::Conditional(
vec![(guard.and(and_guard.clone()), curr_state)],
),
};
self.state2trans
.entry(source)
.and_modify(|existing_transition| {
match (existing_transition, complete_transition.clone())
{
(ir::Transition::Unconditional(_), _)
| (_, ir::Transition::Unconditional(_)) => (),
(
ir::Transition::Conditional(existing_conds),
ir::Transition::Conditional(new_conds),
) => {
existing_conds.extend(new_conds);
}
};
})
.or_insert(complete_transition);
},
);
}
pub fn build_fsm_pieces(&mut self, fsm: ir::RRC<ir::FSM>) -> FSMPieces {
let signal_on = self.builder.add_constant(1, 1);
(0..self.state)
.map(|state| {
// construct a wire to represent this state
let state_wire: ir::RRC<ir::Cell> = self.builder.add_primitive(
format!("{}_{state}", fsm.borrow().name()),
"std_wire",
&[1],
);
// build assignment to indicate that we're in this state
let mut state_assign: ir::Assignment<ir::Nothing> =
self.builder.build_assignment(
state_wire.borrow().get("in"),
signal_on.borrow().get("out"),
ir::Guard::True,
);
// merge `idle` and first `calc` state
if state == 0 {
state_assign.and_guard(ir::guard!(fsm["start"]));
}
let transition_from_state = match self
.state2trans
.remove(&state)
{
Some(mut transition) => {
// if in first state, transition conditioned on fsm[start]
let transition_mut_ref = &mut transition;
if state == 0 {
match transition_mut_ref {
ir::Transition::Unconditional(next_state) => {
*transition_mut_ref =
ir::Transition::Conditional(vec![
(guard!(fsm["start"]), *next_state),
(ir::Guard::True, 0),
]);
}
ir::Transition::Conditional(conditions) => {
conditions.iter_mut().for_each(
|(condition, _)| {
condition.update(|g| {
g.and(guard!(fsm["start"]))
});
},
);
}
}
}
// add a default self-loop for every conditional transition
// if it doesn't already have it
if let ir::Transition::Conditional(trans) =
&mut transition
{
if !(trans.last_mut().unwrap().0.is_true()) {
trans.push((ir::Guard::True, state))
}
}
transition
}
None => {
if state == 0 {
// set transition out of first state, which is
// conditional on reading fsm[start]
ir::Transition::Conditional(vec![
(guard!(fsm["start"]), 1 % self.state),
(ir::Guard::True, 0),
])
} else {
// loopback to start at final state, and increment
// state otherwise
ir::Transition::Unconditional(
if state + 1 == self.state {
0
} else {
state + 1
},
)
}
}
};
(vec![state_assign], transition_from_state, state_wire)
})
.multiunzip()
}
}