Skip to main content

prjunnamed_yosys_json/
export.rs

1use jzon::JsonValue;
2use std::{cell::RefCell, collections::BTreeMap, io::Write};
3
4use crate::yosys::{self, CellDetails, MetadataValue, NetDetails, PortDetails};
5use prjunnamed_netlist::{
6    Cell, Const, ConstBit, ControlNet, Design, IoNet, IoValue, MemoryPortRelation, MetaItem, MetaItemId, Value,
7    ValueBit, ValueSlice,
8};
9
10struct Counter(usize);
11
12impl Counter {
13    fn advance(&mut self) -> usize {
14        let index = self.0;
15        self.0 += 1;
16        index
17    }
18}
19
20struct NetlistIndexerState {
21    map: BTreeMap<ValueBit, usize>,
22    io_map: BTreeMap<IoNet, usize>,
23    next: Counter,
24}
25
26struct NetlistIndexer(RefCell<NetlistIndexerState>);
27
28impl NetlistIndexer {
29    fn new() -> NetlistIndexer {
30        NetlistIndexer(RefCell::new(NetlistIndexerState {
31            map: BTreeMap::new(),
32            io_map: BTreeMap::new(),
33            next: Counter(2), // "to avoid confusion", as write_json claims
34        }))
35    }
36
37    fn net(&self, net: ValueBit) -> yosys::Bit {
38        match net.as_const() {
39            Some(ConstBit::Undef) => yosys::Bit::Undef,
40            Some(ConstBit::Zero) => yosys::Bit::Zero,
41            Some(ConstBit::One) => yosys::Bit::One,
42            None => {
43                let state = &mut *self.0.borrow_mut();
44                yosys::Bit::Net(*state.map.entry(net).or_insert_with(|| state.next.advance()))
45            }
46        }
47    }
48
49    fn synthetic_net(&self) -> yosys::Bit {
50        yosys::Bit::Net(self.0.borrow_mut().next.advance())
51    }
52
53    fn value(&self, value: impl AsRef<ValueSlice>) -> yosys::BitVector {
54        yosys::BitVector(value.as_ref().iter().map(|n| self.net(n)).collect::<Vec<_>>())
55    }
56
57    fn synthetic_value(&self, size: usize) -> yosys::BitVector {
58        yosys::BitVector(std::iter::repeat_with(|| self.synthetic_net()).take(size).collect::<Vec<_>>())
59    }
60
61    fn io_net(&self, net: IoNet) -> yosys::Bit {
62        let state = &mut *self.0.borrow_mut();
63        yosys::Bit::Net(*state.io_map.entry(net).or_insert_with(|| state.next.advance()))
64    }
65
66    fn io_value(&self, value: &IoValue) -> yosys::BitVector {
67        yosys::BitVector(value.iter().map(|n| self.io_net(n)).collect::<Vec<_>>())
68    }
69}
70
71fn map_metadata(design: &Design, metadata: MetaItemId) -> Vec<(String, yosys::MetadataValue)> {
72    let mut ys_attrs: Vec<(String, MetadataValue)> = Vec::new();
73    let mut ys_srcs = Vec::new();
74    let mut ys_hdlname = None;
75    for item in design.iter_metadata_item(metadata) {
76        match *design.ref_metadata_item(item) {
77            MetaItem::Source { file, start, end } => {
78                ys_srcs.push(format!(
79                    "{}:{}.{}-{}.{}",
80                    design.ref_metadata_string(file),
81                    start.line + 1,
82                    start.column + 1,
83                    end.line + 1,
84                    end.column + 1
85                ));
86            }
87            MetaItem::Attr { name, ref value } => {
88                ys_attrs.push((design.ref_metadata_string(name).to_owned(), value.into()));
89            }
90            MetaItem::Ident { name, scope } => 'ident: {
91                let mut parts = vec![design.ref_metadata_string(name).to_owned()];
92                let mut scope = scope;
93                while !scope.is_none() {
94                    let MetaItem::NamedScope { name, parent, .. } = *design.ref_metadata_item(scope) else {
95                        break 'ident;
96                    };
97                    scope = parent;
98                    parts.push(design.ref_metadata_string(name).to_owned());
99                }
100                parts.pop();
101                let name = Vec::from_iter(parts.iter().rev().map(|s| &**s));
102                ys_hdlname = Some(name.join(" "));
103            }
104            _ => (),
105        }
106    }
107    if !ys_srcs.is_empty() {
108        ys_attrs.push(("src".to_owned(), ys_srcs.join("|").into()));
109    }
110    if let Some(ys_hdlname) = ys_hdlname {
111        ys_attrs.push(("hdlname".to_owned(), ys_hdlname.into()));
112    }
113    ys_attrs
114}
115
116fn export_module(mut design: Design) -> yosys::Module {
117    let indexer = NetlistIndexer::new();
118    let mut ys_module = yosys::Module::new();
119
120    // Yosys IR cannot express DFFs with both asynchronous and synchronous reset.
121    for cell_id in design.iter_cells() {
122        if let Cell::Dff(flip_flop) = &*design.cell(cell_id)
123            && flip_flop.has_clear()
124            && flip_flop.has_reset()
125        {
126            let mut flip_flop = flip_flop.clone();
127            flip_flop.unmap_reset(&design);
128            design.cell_replace(cell_id, Cell::Dff(flip_flop));
129        }
130    }
131    design.apply();
132
133    for (name, io_value) in design.iter_ios() {
134        ys_module.ports.add(name, PortDetails::new(yosys::PortDirection::Inout, indexer.io_value(&io_value)))
135    }
136
137    for cell_id in design.iter_cells() {
138        let cell_index = cell_id.debug_index();
139        let output = design.cell_output(cell_id);
140
141        let ys_cell_name = format!("${cell_index}");
142
143        let ys_cell_unary = |module: &mut yosys::Module, ty: &str, a: &Value| {
144            CellDetails::new(ty)
145                .param("A_SIGNED", 0)
146                .param("A_WIDTH", a.len())
147                .param("Y_WIDTH", output.len())
148                .input("A", indexer.value(a))
149                .output("Y", indexer.value(&output))
150                .attrs(map_metadata(&design, design.cell_metadata(cell_id)))
151                .add_to(&format!("${cell_index}"), module)
152        };
153
154        let ys_cell_binary = |module: &mut yosys::Module, ty: &str, a: &Value, b: &Value, signed: bool| {
155            CellDetails::new(ty)
156                .param("A_SIGNED", if signed { 1 } else { 0 })
157                .param("A_WIDTH", a.len())
158                .param("B_SIGNED", if signed { 1 } else { 0 })
159                .param("B_WIDTH", b.len())
160                .param("Y_WIDTH", output.len())
161                .input("A", indexer.value(a))
162                .input("B", indexer.value(b))
163                .output("Y", indexer.value(&output))
164                .attrs(map_metadata(&design, design.cell_metadata(cell_id)))
165                .add_to(&format!("${cell_index}"), module)
166        };
167
168        let ys_shift_count = |module: &mut yosys::Module, a: &Value, stride: u32| -> yosys::BitVector {
169            if stride == 1 {
170                indexer.value(a)
171            } else if stride == 0 {
172                indexer.value(ValueBit::ZERO)
173            } else {
174                let stride_bits = stride.ilog2() + 1;
175                let stride = Const::from_uint(stride.into(), stride_bits as usize);
176                let result = indexer.synthetic_value(a.len() + stride.len());
177                CellDetails::new("$mul")
178                    .param("A_SIGNED", 0)
179                    .param("A_WIDTH", a.len())
180                    .param("B_SIGNED", 0)
181                    .param("B_WIDTH", stride.len())
182                    .param("Y_WIDTH", result.len())
183                    .input("A", indexer.value(a))
184                    .input("B", indexer.value(Value::from(stride)))
185                    .output("Y", result.clone())
186                    .attrs(map_metadata(&design, design.cell_metadata(cell_id)))
187                    .add_to(&format!("${cell_index}$stride"), module);
188                result
189            }
190        };
191
192        let ys_cell_shift = |module: &mut yosys::Module, ty: &str, a: &Value, b: &Value, stride: u32, signed: bool| {
193            let b = ys_shift_count(module, b, stride);
194            CellDetails::new(ty)
195                .param("A_SIGNED", if signed { 1 } else { 0 })
196                .param("A_WIDTH", a.len())
197                .param("B_SIGNED", 0)
198                .param("B_WIDTH", b.len())
199                .param("Y_WIDTH", output.len())
200                .input("A", indexer.value(a))
201                .input("B", b)
202                .output("Y", indexer.value(&output))
203                .attrs(map_metadata(&design, design.cell_metadata(cell_id)))
204                .add_to(&format!("${cell_index}"), module)
205        };
206
207        let ys_control_net_pos = |module: &mut yosys::Module, not_name: &str, cnet: ControlNet| -> yosys::Bit {
208            match cnet {
209                ControlNet::Pos(net) => indexer.net(net),
210                ControlNet::Neg(net) => {
211                    let result = indexer.synthetic_net();
212                    CellDetails::new("$not")
213                        .param("A_SIGNED", 0)
214                        .param("A_WIDTH", 1)
215                        .param("Y_WIDTH", output.len())
216                        .input("A", indexer.value(net))
217                        .output("Y", result)
218                        .attrs(map_metadata(&design, design.cell_metadata(cell_id)))
219                        .add_to(not_name, module);
220                    result
221                }
222            }
223        };
224
225        match &*design.cell(cell_id) {
226            Cell::Const(_) => (),
227            Cell::Buf(arg) => ys_cell_unary(&mut ys_module, "$pos", arg),
228            Cell::Not(arg) => ys_cell_unary(&mut ys_module, "$not", arg),
229            Cell::And(arg1, arg2) => ys_cell_binary(&mut ys_module, "$and", arg1, arg2, false),
230            Cell::Or(arg1, arg2) => ys_cell_binary(&mut ys_module, "$or", arg1, arg2, false),
231            Cell::Xor(arg1, arg2) => ys_cell_binary(&mut ys_module, "$xor", arg1, arg2, false),
232            Cell::Mux(sel, [val0, val1]) => CellDetails::new("$mux")
233                .param("WIDTH", output.len())
234                .input("A", indexer.value(val0))
235                .input("B", indexer.value(val1))
236                .input("S", indexer.net(*sel))
237                .output("Y", indexer.value(&output))
238                .attrs(map_metadata(&design, design.cell_metadata(cell_id)))
239                .add_to(&format!("${cell_index}"), &mut ys_module),
240            Cell::Adc(arg1, arg2, arg3) => {
241                // The $alu cell isn't supported by `write_verilog`, so we have to pattern-match here.
242                match arg3.as_const() {
243                    Some(ConstBit::Zero) => {
244                        // no carry-in
245                        CellDetails::new("$add")
246                            .param("A_SIGNED", 0)
247                            .param("A_WIDTH", arg1.len())
248                            .param("B_SIGNED", 0)
249                            .param("B_WIDTH", arg2.len())
250                            .param("Y_WIDTH", output.len())
251                            .input("A", indexer.value(arg1))
252                            .input("B", indexer.value(arg2))
253                            .output("Y", indexer.value(&output))
254                            .attrs(map_metadata(&design, design.cell_metadata(cell_id)))
255                            .add_to(&format!("${cell_index}"), &mut ys_module);
256                    }
257                    _ => {
258                        // generic
259                        let ys_a = Value::from(arg3).concat(arg1);
260                        let ys_b = Value::from(ValueBit::ONE).concat(arg2);
261                        let ys_y = indexer.synthetic_value(1).concat(&indexer.value(&output));
262                        CellDetails::new("$add")
263                            .param("A_SIGNED", 0)
264                            .param("A_WIDTH", 1 + arg1.len())
265                            .param("B_SIGNED", 0)
266                            .param("B_WIDTH", 1 + arg2.len())
267                            .param("Y_WIDTH", 1 + output.len())
268                            .input("A", indexer.value(&ys_a))
269                            .input("B", indexer.value(&ys_b))
270                            .output("Y", ys_y)
271                            .attrs(map_metadata(&design, design.cell_metadata(cell_id)))
272                            .add_to(&format!("${cell_index}"), &mut ys_module);
273                    }
274                }
275            }
276            Cell::Aig(arg1, arg2) => {
277                let arg1 = ys_control_net_pos(&mut ys_module, &format!("${cell_index}$not1"), *arg1);
278                let arg2 = ys_control_net_pos(&mut ys_module, &format!("${cell_index}$not2"), *arg2);
279                CellDetails::new("$and")
280                    .param("A_SIGNED", 0)
281                    .param("A_WIDTH", 1)
282                    .param("B_SIGNED", 0)
283                    .param("B_WIDTH", 1)
284                    .param("Y_WIDTH", 1)
285                    .input("A", arg1)
286                    .input("B", arg2)
287                    .output("Y", indexer.value(&output))
288                    .attrs(map_metadata(&design, design.cell_metadata(cell_id)))
289                    .add_to(&format!("${cell_index}"), &mut ys_module)
290            }
291
292            Cell::Eq(arg1, arg2) => ys_cell_binary(&mut ys_module, "$eq", arg1, arg2, false),
293            Cell::ULt(arg1, arg2) => ys_cell_binary(&mut ys_module, "$lt", arg1, arg2, false),
294            Cell::SLt(arg1, arg2) => ys_cell_binary(&mut ys_module, "$lt", arg1, arg2, true),
295
296            Cell::Shl(arg1, arg2, stride) => ys_cell_shift(&mut ys_module, "$shl", arg1, arg2, *stride, false),
297            Cell::UShr(arg1, arg2, stride) => ys_cell_shift(&mut ys_module, "$shr", arg1, arg2, *stride, false),
298            Cell::SShr(arg1, arg2, stride) => ys_cell_shift(&mut ys_module, "$sshr", arg1, arg2, *stride, true),
299            Cell::XShr(arg1, arg2, stride) => ys_cell_shift(&mut ys_module, "$shiftx", arg1, arg2, *stride, false),
300
301            Cell::Mul(arg1, arg2) => ys_cell_binary(&mut ys_module, "$mul", arg1, arg2, false),
302            Cell::UDiv(arg1, arg2) => ys_cell_binary(&mut ys_module, "$div", arg1, arg2, false),
303            Cell::UMod(arg1, arg2) => ys_cell_binary(&mut ys_module, "$mod", arg1, arg2, false),
304            Cell::SDivTrunc(arg1, arg2) => ys_cell_binary(&mut ys_module, "$div", arg1, arg2, true),
305            Cell::SDivFloor(arg1, arg2) => ys_cell_binary(&mut ys_module, "$divfloor", arg1, arg2, true),
306            Cell::SModTrunc(arg1, arg2) => ys_cell_binary(&mut ys_module, "$mod", arg1, arg2, true),
307            Cell::SModFloor(arg1, arg2) => ys_cell_binary(&mut ys_module, "$modfloor", arg1, arg2, true),
308
309            Cell::Match { .. } => unimplemented!("match cells must be lowered first for Yosys JSON export"),
310            Cell::Assign { .. } => unimplemented!("assign cells must be lowered first for Yosys JSON export"),
311
312            Cell::Dff(flip_flop) => {
313                if flip_flop.has_clock() {
314                    let ys_cell_type = match (
315                        flip_flop.has_clear(),
316                        flip_flop.has_load(),
317                        flip_flop.has_reset(),
318                        flip_flop.has_enable(),
319                        flip_flop.reset_over_enable,
320                    ) {
321                        (true, _, true, _, _) => unimplemented!(
322                            "registers with both sync and async reset are not supported for Yosys JSON export"
323                        ),
324                        (true, true, _, _, _) => {
325                            unimplemented!("registers with both reset and load are not supported for Yosys JSON export")
326                        }
327                        (_, true, true, _, _) => {
328                            unimplemented!("registers with both reset and load are not supported for Yosys JSON export")
329                        }
330                        (true, false, false, false, _) => "$adff",
331                        (true, false, false, true, _) => "$adffe",
332                        (false, true, false, false, _) => "$aldff",
333                        (false, true, false, true, _) => "$aldffe",
334                        (false, false, true, false, _) => "$sdff",
335                        (false, false, true, true, false) => "$sdffce",
336                        (false, false, true, true, true) => "$sdffe",
337                        (false, false, false, false, _) => "$dff",
338                        (false, false, false, true, _) => "$dffe",
339                    };
340                    let mut ys_cell = CellDetails::new(ys_cell_type);
341                    if flip_flop.has_clear() {
342                        ys_cell = ys_cell
343                            .param("ARST_POLARITY", flip_flop.clear.is_positive())
344                            .param("ARST_VALUE", flip_flop.clear_value.clone())
345                            .input("ARST", indexer.net(flip_flop.clear.net()));
346                    }
347                    if flip_flop.has_load() {
348                        ys_cell = ys_cell
349                            .param("ALOAD_POLARITY", flip_flop.load.is_positive())
350                            .input("ALOAD", indexer.net(flip_flop.load.net()))
351                            .input("AD", indexer.value(&flip_flop.load_data));
352                    }
353                    if flip_flop.has_reset() {
354                        ys_cell = ys_cell
355                            .param("SRST_POLARITY", flip_flop.reset.is_positive())
356                            .param("SRST_VALUE", flip_flop.reset_value.clone())
357                            .input("SRST", indexer.net(flip_flop.reset.net()));
358                    }
359                    if flip_flop.has_enable() {
360                        ys_cell = ys_cell
361                            .param("EN_POLARITY", flip_flop.enable.is_positive())
362                            .input("EN", indexer.net(flip_flop.enable.net()));
363                    }
364                    ys_cell
365                        .param("CLK_POLARITY", flip_flop.clock.is_positive())
366                        .input("CLK", indexer.net(flip_flop.clock.net()))
367                        .param("WIDTH", output.len())
368                        .input("D", indexer.value(&flip_flop.data))
369                        .output("Q", indexer.value(&output))
370                        .attrs(map_metadata(&design, design.cell_metadata(cell_id)))
371                        .add_to(&ys_cell_name, &mut ys_module);
372                } else {
373                    let ys_cell_type = if flip_flop.has_clear() { "$adlatch" } else { "$dlatch" };
374                    let mut ys_cell = CellDetails::new(ys_cell_type);
375                    if flip_flop.has_clear() {
376                        ys_cell = ys_cell
377                            .param("ARST_POLARITY", flip_flop.clear.is_positive())
378                            .param("ARST_VALUE", flip_flop.clear_value.clone())
379                            .input("ARST", indexer.net(flip_flop.clear.net()));
380                    }
381                    ys_cell
382                        .param("WIDTH", output.len())
383                        .input("D", indexer.value(&flip_flop.load_data))
384                        .param("EN_POLARITY", flip_flop.load.is_positive())
385                        .input("EN", indexer.net(flip_flop.load.net()))
386                        .output("Q", indexer.value(&output))
387                        .attrs(map_metadata(&design, design.cell_metadata(cell_id)))
388                        .add_to(&ys_cell_name, &mut ys_module);
389                }
390                NetDetails::new(indexer.value(&output))
391                    .attr("init", flip_flop.init_value.clone())
392                    .add_to(&format!("{ys_cell_name}$ff"), &mut ys_module);
393                continue; // skip default $out wire (init-less) creation
394            }
395
396            Cell::Memory(memory) => {
397                let abits = memory
398                    .write_ports
399                    .iter()
400                    .map(|port| port.addr.len() + port.wide_log2(memory))
401                    .max()
402                    .unwrap_or(0)
403                    .max(
404                        memory
405                            .read_ports
406                            .iter()
407                            .map(|port| port.addr.len() + port.wide_log2(memory))
408                            .max()
409                            .unwrap_or(0),
410                    );
411
412                let mut wr_ports = 0;
413                let mut wr_clk_polarity = Const::new();
414                let mut wr_wide_continuation = Const::new();
415                let mut wr_addr = Value::new();
416                let mut wr_data = Value::new();
417                let mut wr_clk = Value::new();
418                let mut wr_en = Value::new();
419                let mut write_port_indices = vec![];
420                for (port_index, port) in memory.write_ports.iter().enumerate() {
421                    let wide_log2 = port.wide_log2(memory);
422                    for index in 0..(1 << wide_log2) {
423                        let addr = Value::from(Const::from_uint(index, wide_log2)).concat(&port.addr).zext(abits);
424                        wr_clk.extend([port.clock.net()]);
425                        wr_addr.extend(&addr);
426                        wr_clk_polarity.push(port.clock.is_positive());
427                        wr_wide_continuation.push(index != 0);
428                        write_port_indices.push(port_index);
429                    }
430                    wr_data.extend(&port.data);
431                    wr_en.extend(&port.mask);
432                    wr_ports += 1 << wide_log2;
433                }
434                if wr_ports == 0 {
435                    wr_clk_polarity.push(false);
436                    wr_wide_continuation.push(false);
437                }
438
439                let mut rd_ports = 0;
440                let mut rd_clk_enable = Const::new();
441                let mut rd_clk_polarity = Const::new();
442                let mut rd_transparency_mask = Const::new();
443                let mut rd_collision_x_mask = Const::new();
444                let mut rd_wide_continuation = Const::new();
445                let mut rd_ce_over_srst = Const::new();
446                let mut rd_arst_value = Const::new();
447                let mut rd_srst_value = Const::new();
448                let mut rd_init_value = Const::new();
449                let mut rd_clk = Value::new();
450                let mut rd_en = yosys::BitVector(vec![]);
451                let mut rd_arst = yosys::BitVector(vec![]);
452                let mut rd_srst = yosys::BitVector(vec![]);
453                let mut rd_addr = Value::new();
454                for (port_index, port) in memory.read_ports.iter().enumerate() {
455                    let wide_log2 = port.wide_log2(memory);
456                    for index in 0..(1 << wide_log2) {
457                        let addr = Value::from(Const::from_uint(index, wide_log2)).concat(&port.addr).zext(abits);
458                        rd_addr.extend(&addr);
459                        if let Some(ref flip_flop) = port.flip_flop {
460                            rd_clk.extend([flip_flop.clock.net()]);
461                            rd_clk_enable.push(true);
462                            rd_clk_polarity.push(flip_flop.clock.is_positive());
463                            rd_ce_over_srst.push(!flip_flop.reset_over_enable);
464                            for &write_port_index in &write_port_indices {
465                                let (trans, col_x) = if flip_flop.clock == memory.write_ports[write_port_index].clock {
466                                    match flip_flop.relations[write_port_index] {
467                                        MemoryPortRelation::Undefined => (false, true),
468                                        MemoryPortRelation::ReadBeforeWrite => (false, false),
469                                        MemoryPortRelation::Transparent => (true, false),
470                                    }
471                                } else {
472                                    (false, false)
473                                };
474                                rd_transparency_mask.push(trans);
475                                rd_collision_x_mask.push(col_x);
476                            }
477                        } else {
478                            rd_clk.extend([ValueBit::UNDEF]);
479                            rd_clk_enable.push(false);
480                            rd_clk_polarity.push(ConstBit::Undef);
481                            rd_ce_over_srst.push(ConstBit::Undef);
482                            rd_transparency_mask.extend(Const::undef(wr_ports));
483                            rd_collision_x_mask.extend(Const::undef(wr_ports));
484                        }
485                        rd_wide_continuation.push(index != 0);
486                    }
487                    if let Some(ref flip_flop) = port.flip_flop {
488                        rd_arst_value.extend(&flip_flop.clear_value);
489                        rd_srst_value.extend(&flip_flop.reset_value);
490                        rd_init_value.extend(&flip_flop.init_value);
491                        let enable = ys_control_net_pos(
492                            &mut ys_module,
493                            &format!("${cell_index}$rd{port_index}$en$not"),
494                            flip_flop.enable,
495                        );
496                        let clear = ys_control_net_pos(
497                            &mut ys_module,
498                            &format!("${cell_index}$rd{port_index}$arst$not"),
499                            flip_flop.clear,
500                        );
501                        let reset = ys_control_net_pos(
502                            &mut ys_module,
503                            &format!("${cell_index}$rd{port_index}$srst$not"),
504                            flip_flop.reset,
505                        );
506                        rd_en = rd_en.concat(&yosys::BitVector(vec![enable; 1 << wide_log2]));
507                        rd_srst = rd_srst.concat(&yosys::BitVector(vec![reset; 1 << wide_log2]));
508                        rd_arst = rd_arst.concat(&yosys::BitVector(vec![clear; 1 << wide_log2]));
509                    } else {
510                        rd_arst_value.extend(Const::undef(port.data_len));
511                        rd_srst_value.extend(Const::undef(port.data_len));
512                        rd_init_value.extend(Const::undef(port.data_len));
513                        rd_en = rd_en.concat(&yosys::BitVector(vec![yosys::Bit::One; 1 << wide_log2]));
514                        rd_srst = rd_srst.concat(&yosys::BitVector(vec![yosys::Bit::Zero; 1 << wide_log2]));
515                        rd_arst = rd_arst.concat(&yosys::BitVector(vec![yosys::Bit::Zero; 1 << wide_log2]));
516                    }
517                    rd_ports += 1 << wide_log2;
518                }
519                if rd_ports == 0 {
520                    rd_clk_enable.push(false);
521                    rd_clk_polarity.push(false);
522                    rd_wide_continuation.push(false);
523                    rd_ce_over_srst.push(false);
524                    rd_arst_value.push(false);
525                    rd_srst_value.push(false);
526                    rd_init_value.push(false);
527                }
528                if rd_ports == 0 || wr_ports == 0 {
529                    rd_transparency_mask.push(false);
530                    rd_collision_x_mask.push(false);
531                }
532
533                CellDetails::new("$mem_v2")
534                    .param("MEMID", format!("${cell_index}$mem"))
535                    .param("OFFSET", 0)
536                    .param("SIZE", memory.depth)
537                    .param("WIDTH", memory.width)
538                    .param("ABITS", abits)
539                    .param("INIT", memory.init_value.clone())
540                    .param("WR_PORTS", wr_ports)
541                    .param("WR_CLK_ENABLE", Const::ones(wr_ports.max(1)))
542                    .param("WR_CLK_POLARITY", wr_clk_polarity)
543                    .param("WR_PRIORITY_MASK", Const::zero(wr_ports.max(1)))
544                    .param("WR_WIDE_CONTINUATION", wr_wide_continuation)
545                    .input("WR_ADDR", indexer.value(&wr_addr))
546                    .input("WR_DATA", indexer.value(&wr_data))
547                    .input("WR_CLK", indexer.value(&wr_clk))
548                    .input("WR_EN", indexer.value(&wr_en))
549                    .param("RD_PORTS", rd_ports)
550                    .param("RD_CLK_ENABLE", rd_clk_enable)
551                    .param("RD_CLK_POLARITY", rd_clk_polarity)
552                    .param("RD_TRANSPARENCY_MASK", rd_transparency_mask)
553                    .param("RD_COLLISION_X_MASK", rd_collision_x_mask)
554                    .param("RD_WIDE_CONTINUATION", rd_wide_continuation)
555                    .param("RD_CE_OVER_SRST", rd_ce_over_srst)
556                    .param("RD_ARST_VALUE", rd_arst_value)
557                    .param("RD_SRST_VALUE", rd_srst_value)
558                    .param("RD_INIT_VALUE", rd_init_value)
559                    .input("RD_CLK", indexer.value(&rd_clk))
560                    .input("RD_EN", rd_en)
561                    .input("RD_ARST", rd_arst)
562                    .input("RD_SRST", rd_srst)
563                    .input("RD_ADDR", indexer.value(&rd_addr))
564                    .output("RD_DATA", indexer.value(&output))
565                    .add_to(&format!("${cell_index}"), &mut ys_module);
566            }
567
568            Cell::IoBuf(io_buffer) => {
569                let ys_enable = ys_control_net_pos(&mut ys_module, &format!("${cell_index}$en$not"), io_buffer.enable);
570                let ys_attrs = map_metadata(&design, design.cell_metadata(cell_id));
571                CellDetails::new("$tribuf")
572                    .param("WIDTH", output.len())
573                    .input("A", indexer.value(&io_buffer.output))
574                    .input("EN", ys_enable)
575                    .output("Y", indexer.io_value(&io_buffer.io))
576                    .attrs(ys_attrs.clone())
577                    .add_to(&format!("${cell_index}"), &mut ys_module);
578                CellDetails::new("$pos")
579                    .param("A_SIGNED", 0)
580                    .param("A_WIDTH", io_buffer.io.len())
581                    .param("Y_WIDTH", output.len())
582                    .input("A", indexer.io_value(&io_buffer.io))
583                    .output("Y", indexer.value(&output))
584                    .attrs(ys_attrs)
585                    .add_to(&format!("${cell_index}$pos"), &mut ys_module);
586            }
587
588            Cell::Other(instance) => {
589                let mut ys_cell = CellDetails::new(&instance.kind);
590                for (name, value) in instance.params.iter() {
591                    ys_cell = ys_cell.param(name, value);
592                }
593                for (name, value) in instance.inputs.iter() {
594                    ys_cell = ys_cell.input(name, indexer.value(value));
595                }
596                for (name, &value_range) in instance.outputs.iter() {
597                    ys_cell = ys_cell.output(name, indexer.value(&output[value_range]));
598                }
599                for (name, io_value) in instance.ios.iter() {
600                    ys_cell = ys_cell.inout(name, indexer.io_value(io_value));
601                }
602                ys_cell
603                    .attrs(map_metadata(&design, design.cell_metadata(cell_id)))
604                    .add_to(&ys_cell_name, &mut ys_module);
605            }
606            Cell::Target(_target_cell) => {
607                unimplemented!("target cells must be converted to instances first for Yosys JSON export")
608            }
609
610            Cell::Input(port_name, _size) => {
611                ys_module.ports.add(port_name, PortDetails::new(yosys::PortDirection::Input, indexer.value(&output)))
612            }
613            Cell::Output(port_name, value) => {
614                ys_module.ports.add(port_name, PortDetails::new(yosys::PortDirection::Output, indexer.value(value)))
615            }
616            Cell::Name(name, value) | Cell::Debug(name, value) => ys_module.netnames.add(
617                &name.replace(" ", "."),
618                NetDetails::new(indexer.value(value))
619                    .attrs(map_metadata(&design, design.cell_metadata(cell_id)))
620                    .attr("hdlname", name),
621            ),
622        };
623
624        if !output.is_empty() {
625            // Duplicating the cell metadata on the cell output net is the only way to get source locations
626            // to show up in nextpnr's timing reports.
627            NetDetails::new(indexer.value(&output))
628                .attrs(map_metadata(&design, design.cell_metadata(cell_id)))
629                .add_to(&format!("{ys_cell_name}$out"), &mut ys_module);
630        }
631    }
632
633    ys_module
634}
635
636// Exporting a design to Yosys JSON can require modifying it if it has target cells that must be mapped to instances.
637pub fn export(writer: &mut impl Write, designs: BTreeMap<String, Design>) -> std::io::Result<()> {
638    let mut ys_modules = BTreeMap::new();
639    for (name, design) in designs {
640        ys_modules.insert(name, export_module(design));
641    }
642    let ys_design = yosys::Design { creator: "prjunnamed".into(), modules: ys_modules.into() };
643
644    let json = JsonValue::from(ys_design);
645    json.write_pretty(writer, /*spaces=*/ 4)
646}