Skip to main content

logicaffeine_compile/codegen_sva/
controller_gen.rs

1//! Designer → certified controller: turn a synthesized [`PhasePlan`] into a Verilog phase-FSM and
2//! let the existing RTL pipeline (`parse_transition_system` → `prove_invariant`) certify it.
3//!
4//! The controller cycles a `phase` counter; on entering each phase it greens *exactly* that
5//! phase's movements and reds the rest. Because the plan is a conflict-free colouring, no
6//! conflicting pair is ever green together — and because every transition fully rewrites all
7//! movement registers to a (safe) phase configuration, the safety property is **1-inductive**, so
8//! `prove_invariant(1)` proves it with no extra invariant strengthening. This closes the loop:
9//! design (SAT) → generate (codegen) → prove (k-induction), entirely on our own stack.
10
11use super::signal_design::{Intersection, PhasePlan};
12use std::fmt::Write as _;
13
14/// Generate a synthesizable Verilog controller (one 1-bit `mvN` register per movement, a `phase`
15/// counter) whose conflict-freedom is provable by `prove_invariant`.
16pub fn generate_controller(it: &Intersection, plan: &PhasePlan) -> String {
17    let n = it.movements.len();
18    let k = plan.num_phases.max(1);
19    let groups = plan.groups();
20    let bits = phase_bits(k);
21
22    let mut v = String::new();
23    let _ = writeln!(v, "module controller(input clk);");
24    let _ = writeln!(v, "  reg [{}:0] phase;", bits - 1);
25    for i in 0..n {
26        let _ = writeln!(v, "  reg mv{i};");
27    }
28    let _ = writeln!(
29        v,
30        "  initial begin phase = {bits}'d0; {} end",
31        config_assigns(&groups, 0, n, true)
32    );
33    let _ = writeln!(v, "  always @(posedge clk)");
34    if k == 1 {
35        // No conflicts: a single phase greens everything, every cycle.
36        let _ = writeln!(
37            v,
38            "    begin phase <= {bits}'d0; {} end",
39            config_assigns(&groups, 0, n, false)
40        );
41    } else {
42        for p in 0..(k - 1) {
43            let kw = if p == 0 { "if" } else { "else if" };
44            let _ = writeln!(
45                v,
46                "    {kw} (phase == {bits}'d{p}) begin phase <= {bits}'d{}; {} end",
47                p + 1,
48                config_assigns(&groups, p + 1, n, false)
49            );
50        }
51        // Last phase (and any unreachable out-of-range counter value) wraps to phase 0.
52        let _ = writeln!(
53            v,
54            "    else begin phase <= {bits}'d0; {} end",
55            config_assigns(&groups, 0, n, false)
56        );
57    }
58    let _ = writeln!(v, "  assert property ({});", conflict_free_property(it));
59    let _ = writeln!(v, "endmodule");
60    v
61}
62
63/// Assign every movement register for phase `p`: `1` if served in that phase, else `0`.
64/// `blocking` selects `=` (an `initial` block) vs `<=` (an `always` block).
65fn config_assigns(groups: &[Vec<usize>], p: usize, n: usize, blocking: bool) -> String {
66    let op = if blocking { "=" } else { "<=" };
67    let served: std::collections::HashSet<usize> = groups
68        .get(p)
69        .map(|g| g.iter().copied().collect())
70        .unwrap_or_default();
71    (0..n)
72        .map(|i| format!("mv{i} {op} 1'd{};", usize::from(served.contains(&i))))
73        .collect::<Vec<_>>()
74        .join(" ")
75}
76
77/// The safety property: no conflicting pair is green together. A conflict-free intersection has
78/// nothing to violate, so a tautology stands in.
79fn conflict_free_property(it: &Intersection) -> String {
80    if it.conflicts.is_empty() {
81        "mv0 | ~mv0".to_string()
82    } else {
83        it.conflicts
84            .iter()
85            .map(|&(a, b)| format!("~(mv{a} & mv{b})"))
86            .collect::<Vec<_>>()
87            .join(" & ")
88    }
89}
90
91/// Bits needed for a phase counter over `k` phases (values `0..k`).
92fn phase_bits(k: usize) -> usize {
93    let mut bits = 1;
94    while (1usize << bits) < k {
95        bits += 1;
96    }
97    bits
98}
99
100#[cfg(test)]
101#[path = "../../../logicaffeine_tests/unit/logicaffeine_compile/codegen_sva/controller_gen/tests.rs"]
102mod tests;