calyx_opt/passes/
simplify_with_control.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
265
use crate::analysis;
use crate::traversal::{Action, Named, VisResult, Visitor};
use calyx_ir::{self as ir, GetAttributes, LibrarySignatures, RRC, structure};
use calyx_utils::{CalyxResult, Error};
use std::collections::HashMap;
use std::rc::Rc;

#[derive(Default)]
/// Transforms combinational groups into normal groups by registering the values
/// read from the ports of cells used within the combinational group.
///
/// It also transforms (if,while)-with into semantically equivalent control programs that
/// first enable a group that calculates and registers the ports defined by the combinational group
/// execute the respective cond group and then execute the control operator.
///
/// # Example
/// ```
/// group comb_cond<"static"=0> {
///     lt.right = 32'd10;
///     lt.left = 32'd1;
///     eq.right = r.out;
///     eq.left = x.out;
///     comb_cond[done] = 1'd1;
/// }
/// control {
///     if lt.out with comb_cond {
///         ...
///     }
///     while eq.out with comb_cond {
///         ...
///     }
/// }
/// ```
/// into:
/// ```
/// group comb_cond<"static"=1> {
///     lt.right = 32'd10;
///     lt.left = 32'd1;
///     eq.right = r.out;
///     eq.left = x.out;
///     lt_reg.in = lt.out
///     lt_reg.write_en = 1'd1;
///     eq_reg.in = eq.out;
///     eq_reg.write_en = 1'd1;
///     comb_cond[done] = lt_reg.done & eq_reg.done ? 1'd1;
/// }
/// control {
///     seq {
///       comb_cond;
///       if lt_reg.out {
///           ...
///       }
///     }
///     seq {
///       comb_cond;
///       while eq_reg.out {
///           ...
///           comb_cond;
///       }
///     }
/// }
/// ```
pub struct SimplifyWithControl {
    // Mapping from (group_name, (cell_name, port_name)) -> (port, static_group).
    port_rewrite: HashMap<PortInGroup, (RRC<ir::Port>, RRC<ir::StaticGroup>)>,
}

/// Represents (group_name, (cell_name, port_name))
type PortInGroup = (ir::Id, ir::Canonical);

impl Named for SimplifyWithControl {
    fn name() -> &'static str {
        "simplify-with-control"
    }

    fn description() -> &'static str {
        "Transforms if-with and while-with to if and while"
    }
}

impl Visitor for SimplifyWithControl {
    fn start(
        &mut self,
        comp: &mut ir::Component,
        sigs: &LibrarySignatures,
        _comps: &[ir::Component],
    ) -> VisResult {
        let mut used_ports =
            analysis::ControlPorts::<false>::from(&*comp.control.borrow());

        // Early return if there are no combinational groups
        if comp.comb_groups.is_empty() {
            return Ok(Action::Stop);
        }

        // Detach the combinational groups from the component
        let comb_groups = std::mem::take(&mut comp.comb_groups);
        let mut builder = ir::Builder::new(comp, sigs);

        // Groups generated by transforming combinational groups
        let groups = comb_groups
            .iter()
            .map(|cg_ref| {
                let name = cg_ref.borrow().name();
                // Register the ports read by the combinational group's usages.
                let used_ports = used_ports.remove(&name).ok_or_else(|| {
                    Error::malformed_structure(format!(
                        "values from combinational group `{}` never used",
                        name
                    ))
                })?;

                // Group generated to replace this comb group.
                let group_ref = builder.add_static_group(name, 1);
                let mut group = group_ref.borrow_mut();
                // Attach assignmens from comb group
                group.assignments = cg_ref
                    .borrow_mut()
                    .assignments
                    .clone()
                    .into_iter()
                    .map(|x| x.into())
                    .collect();

                // Registers to save value for the group
                let mut save_regs = Vec::with_capacity(used_ports.len());
                for port in used_ports {
                    // Register to save port value
                    structure!(builder;
                        let comb_reg = prim std_reg(port.borrow().width);
                        let signal_on = constant(1, 1);
                    );
                    let write = builder.build_assignment(
                        comb_reg.borrow().get("in"),
                        Rc::clone(&port),
                        ir::Guard::True,
                    );
                    let en = builder.build_assignment(
                        comb_reg.borrow().get("write_en"),
                        signal_on.borrow().get("out"),
                        ir::Guard::True,
                    );
                    group.assignments.push(write);
                    group.assignments.push(en);

                    // Define mapping from this port to the register's output
                    // value.
                    self.port_rewrite.insert(
                        (name, port.borrow().canonical().clone()),
                        (
                            Rc::clone(&comb_reg.borrow().get("out")),
                            Rc::clone(&group_ref),
                        ),
                    );

                    save_regs.push(comb_reg);
                }

                // No need for a done condition
                drop(group);

                Ok(group_ref)
            })
            .collect::<CalyxResult<Vec<_>>>()?;

        for group in groups {
            comp.get_static_groups_mut().add(group)
        }

        // Restore the combinational groups
        comp.comb_groups = comb_groups;

        Ok(Action::Continue)
    }

    fn finish_while(
        &mut self,
        s: &mut ir::While,
        _comp: &mut ir::Component,
        _sigs: &LibrarySignatures,
        _comps: &[ir::Component],
    ) -> VisResult {
        if s.cond.is_none() {
            return Ok(Action::Continue);
        }

        // Construct a new `while` statement
        let key = (
            s.cond.as_ref().unwrap().borrow().name(),
            s.port.borrow().canonical(),
        );
        let (port_ref, cond_ref) = self.port_rewrite.get(&key).unwrap();
        let cond_in_body = ir::Control::static_enable(Rc::clone(cond_ref));
        let body = std::mem::replace(s.body.as_mut(), ir::Control::empty());
        let new_body = ir::Control::seq(vec![body, cond_in_body]);
        let mut while_ =
            ir::Control::while_(Rc::clone(port_ref), None, Box::new(new_body));
        let attrs = while_.get_mut_attributes();
        *attrs = std::mem::take(&mut s.attributes);
        let cond_before_body = ir::Control::static_enable(Rc::clone(cond_ref));
        Ok(Action::change(ir::Control::seq(vec![
            cond_before_body,
            while_,
        ])))
    }

    /// Transforms a `if-with` into a `seq-if` which first runs the cond group
    /// and then the branch.
    fn finish_if(
        &mut self,
        s: &mut ir::If,
        _comp: &mut ir::Component,
        _sigs: &LibrarySignatures,
        _comps: &[ir::Component],
    ) -> VisResult {
        if s.cond.is_none() {
            return Ok(Action::Continue);
        }
        // Construct a new `if` statement
        let key = (
            s.cond.as_ref().unwrap().borrow().name(),
            s.port.borrow().canonical(),
        );
        let (port_ref, cond_ref) =
            self.port_rewrite.get(&key).unwrap_or_else(|| {
                panic!(
                    "{}: Port `{}` in group `{}` doesn't have a rewrite",
                    Self::name(),
                    key.1,
                    key.0
                )
            });
        let tbranch =
            std::mem::replace(s.tbranch.as_mut(), ir::Control::empty());
        let fbranch =
            std::mem::replace(s.fbranch.as_mut(), ir::Control::empty());
        let mut if_ = ir::Control::if_(
            Rc::clone(port_ref),
            None,
            Box::new(tbranch),
            Box::new(fbranch),
        );
        let attrs = if_.get_mut_attributes();
        *attrs = std::mem::take(&mut s.attributes);
        let cond = ir::Control::static_enable(Rc::clone(cond_ref));
        Ok(Action::change(ir::Control::seq(vec![cond, if_])))
    }

    fn finish(
        &mut self,
        comp: &mut ir::Component,
        _sigs: &LibrarySignatures,
        _comps: &[ir::Component],
    ) -> VisResult {
        if comp.is_static() {
            let msg = format!(
                "Static Component {} has combinational groups which is not supported",
                comp.name
            );
            return Err(Error::pass_assumption(Self::name(), msg)
                .with_pos(&comp.attributes));
        }
        Ok(Action::Continue)
    }
}