yosys2digitaljs 0.8.0 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/core.ts ADDED
@@ -0,0 +1,1210 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+
4
+ import * as HashMap from 'hashmap';
5
+ import * as bigInt from 'big-integer';
6
+ import {Vector3vl, Mem3vl} from '3vl';
7
+ const topsort: <T>(edges:T[][], options?:{continueOnCircularDependency: boolean}) => T[] = require('topsort');
8
+
9
+ function assert_fallback(val: any, msg?: string) {
10
+ if (!val)
11
+ throw new Error(msg || "Assertion failed");
12
+ }
13
+
14
+ const isNode = typeof process !== "undefined" &&
15
+ process.versions != null &&
16
+ process.versions.node != null;
17
+
18
+ const assert = isNode
19
+ ? require('assert')
20
+ : assert_fallback
21
+
22
+ export namespace Digitaljs {
23
+ export type FilePosition = {
24
+ line: number,
25
+ column: number
26
+ };
27
+
28
+ export type SourcePosition = {
29
+ name: string,
30
+ from: FilePosition,
31
+ to: FilePosition
32
+ };
33
+
34
+ export type MemReadPort = {
35
+ clock_polarity?: boolean,
36
+ enable_polarity?: boolean,
37
+ arst_polarity?: boolean,
38
+ srst_polarity?: boolean,
39
+ enable_srst?: boolean,
40
+ transparent?: boolean | boolean[],
41
+ collision?: boolean | boolean[],
42
+ init_value?: string,
43
+ arst_value?: string,
44
+ srst_value?: string
45
+ };
46
+
47
+ export type MemWritePort = {
48
+ clock_polarity?: boolean,
49
+ enable_polarity?: boolean,
50
+ no_bit_enable?: boolean
51
+ };
52
+
53
+ export type Device = {
54
+ type: string,
55
+ source_positions?: SourcePosition[],
56
+ [key: string]: any
57
+ };
58
+
59
+ export type Port = {
60
+ id: string,
61
+ port: string
62
+ };
63
+
64
+ export type Connector = {
65
+ from: Port,
66
+ to: Port,
67
+ name?: string,
68
+ source_positions?: SourcePosition[]
69
+ };
70
+
71
+ export type Module = {
72
+ devices: { [key: string]: Device },
73
+ connectors: Connector[]
74
+ };
75
+
76
+ export type TopModule = Module & {
77
+ subcircuits: { [key: string]: Module }
78
+ };
79
+ };
80
+
81
+ namespace Yosys {
82
+
83
+ export const ConstChars = ["0", "1", "x", "z"] as const;
84
+
85
+ export type BitChar = (typeof ConstChars)[number];
86
+
87
+ export type Bit = number | BitChar;
88
+
89
+ export type BitVector = Bit[];
90
+
91
+ export type Port = {
92
+ direction: 'input' | 'output' | 'inout',
93
+ bits: any
94
+ };
95
+
96
+ export type Parameters = {
97
+ WIDTH?: JsonConstant,
98
+ A_WIDTH?: JsonConstant,
99
+ B_WIDTH?: JsonConstant,
100
+ S_WIDTH?: JsonConstant,
101
+ Y_WIDTH?: JsonConstant,
102
+ A_SIGNED?: JsonConstant,
103
+ B_SIGNED?: JsonConstant,
104
+ CLK_POLARITY?: JsonConstant,
105
+ EN_POLARITY?: JsonConstant,
106
+ ARST_POLARITY?: JsonConstant,
107
+ ARST_VALUE: JsonConstant,
108
+ CTRL_IN_WIDTH?: JsonConstant,
109
+ CTRL_OUT_WIDTH?: JsonConstant,
110
+ TRANS_NUM?: JsonConstant,
111
+ STATE_NUM?: JsonConstant,
112
+ STATE_NUM_LOG2?: JsonConstant,
113
+ STATE_RST?: JsonConstant,
114
+ RD_PORTS?: JsonConstant,
115
+ WR_PORTS?: JsonConstant,
116
+ RD_CLK_POLARITY?: JsonConstant,
117
+ RD_CLK_ENABLE?: JsonConstant,
118
+ RD_CLK_TRANSPARENT?: JsonConstant,
119
+ WR_CLK_POLARITY?: JsonConstant,
120
+ WR_CLK_ENABLE?: JsonConstant,
121
+ [key: string]: any
122
+ };
123
+
124
+ export type JsonConstant = number | string;
125
+
126
+ export type Attributes = {
127
+ init: JsonConstant,
128
+ [key: string]: any
129
+ };
130
+ export type Cell = {
131
+ hide_name: 0 | 1,
132
+ type: string,
133
+ parameters: Parameters,
134
+ attributes: Attributes,
135
+ port_directions: { [key: string]: 'input' | 'output' },
136
+ connections: { [key: string]: BitVector }
137
+ };
138
+
139
+ export type Net = {
140
+ hide_name: 0 | 1,
141
+ bits: BitVector,
142
+ attributes: { [key: string]: string }
143
+ };
144
+
145
+ export type Module = {
146
+ ports: { [key: string]: Port },
147
+ cells: { [key: string]: Cell },
148
+ netnames: { [key: string]: Net }
149
+ };
150
+
151
+ export type Output = {
152
+ modules: { [key: string]: Module }
153
+ };
154
+
155
+ };
156
+
157
+ export type ConvertOptions = {
158
+ propagation?: number,
159
+ };
160
+
161
+ type Portmap = { [key: string]: string };
162
+ type Portmaps = { [key: string]: Portmap };
163
+
164
+ type Bit = Yosys.Bit | `bit${number}`;
165
+
166
+ type Net = Bit[];
167
+
168
+ type NetInfo = {
169
+ source: undefined | Digitaljs.Port,
170
+ targets: Digitaljs.Port[],
171
+ name: undefined | string,
172
+ source_positions: Digitaljs.SourcePosition[]
173
+ };
174
+
175
+ type BitInfo = {
176
+ id: string,
177
+ port: string,
178
+ num: number
179
+ };
180
+
181
+ const unary_gates = new Set([
182
+ '$not', '$neg', '$pos', '$reduce_and', '$reduce_or', '$reduce_xor',
183
+ '$reduce_xnor', '$reduce_bool', '$logic_not']);
184
+ const binary_gates = new Set([
185
+ '$and', '$or', '$xor', '$xnor',
186
+ '$add', '$sub', '$mul', '$div', '$mod', '$pow',
187
+ '$lt', '$le', '$eq', '$ne', '$ge', '$gt', '$eqx', '$nex',
188
+ '$shl', '$shr', '$sshl', '$sshr', '$shift', '$shiftx',
189
+ '$logic_and', '$logic_or']);
190
+ const gate_subst = new Map([
191
+ ['$not', 'Not'],
192
+ ['$and', 'And'],
193
+ ['$nand', 'Nand'],
194
+ ['$or', 'Or'],
195
+ ['$nor', 'Nor'],
196
+ ['$xor', 'Xor'],
197
+ ['$xnor', 'Xnor'],
198
+ ['$reduce_and', 'AndReduce'],
199
+ ['$reduce_nand', 'NandReduce'],
200
+ ['$reduce_or', 'OrReduce'],
201
+ ['$reduce_nor', 'NorReduce'],
202
+ ['$reduce_xor', 'XorReduce'],
203
+ ['$reduce_xnor', 'XnorReduce'],
204
+ ['$reduce_bool', 'OrReduce'],
205
+ ['$logic_not', 'NorReduce'],
206
+ ['$repeater', 'Repeater'],
207
+ ['$shl', 'ShiftLeft'],
208
+ ['$shr', 'ShiftRight'],
209
+ ['$lt', 'Lt'],
210
+ ['$le', 'Le'],
211
+ ['$eq', 'Eq'],
212
+ ['$ne', 'Ne'],
213
+ ['$gt', 'Gt'],
214
+ ['$ge', 'Ge'],
215
+ ['$constant', 'Constant'],
216
+ ['$neg', 'Negation'],
217
+ ['$pos', 'UnaryPlus'],
218
+ ['$add', 'Addition'],
219
+ ['$sub', 'Subtraction'],
220
+ ['$mul', 'Multiplication'],
221
+ ['$div', 'Division'],
222
+ ['$mod', 'Modulo'],
223
+ ['$pow', 'Power'],
224
+ ['$mux', 'Mux'],
225
+ ['$pmux', 'Mux1Hot'],
226
+ ['$mem', 'Memory'],
227
+ ['$mem_v2', 'Memory'],
228
+ ['$lut', 'Memory'],
229
+ ['$fsm', 'FSM'],
230
+ ['$clock', 'Clock'],
231
+ ['$button', 'Button'],
232
+ ['$lamp', 'Lamp'],
233
+ ['$numdisplay', 'NumDisplay'],
234
+ ['$numentry', 'NumEntry'],
235
+ ['$input', 'Input'],
236
+ ['$output', 'Output'],
237
+ ['$busgroup', 'BusGroup'],
238
+ ['$busungroup', 'BusUngroup'],
239
+ ['$busslice', 'BusSlice'],
240
+ ['$zeroextend', 'ZeroExtend'],
241
+ ['$signextend', 'SignExtend'],
242
+ ['$reduce_bool', 'OrReduce'],
243
+ ['$eqx', 'Eq'],
244
+ ['$nex', 'Ne'],
245
+ ['$sshl', 'ShiftLeft'],
246
+ ['$sshr', 'ShiftRight'],
247
+ ['$shift', 'ShiftRight'],
248
+ ['$shiftx', 'ShiftRight'],
249
+ ['$logic_and', 'And'],
250
+ ['$logic_or', 'Or'],
251
+ ['$dff', 'Dff'],
252
+ ['$dffe', 'Dff'],
253
+ ['$adff', 'Dff'],
254
+ ['$adffe', 'Dff'],
255
+ ['$sdff', 'Dff'],
256
+ ['$sdffe', 'Dff'],
257
+ ['$sdffce', 'Dff'],
258
+ ['$dlatch', 'Dff'],
259
+ ['$adlatch', 'Dff'],
260
+ ['$sr', 'Dff'],
261
+ ['$dffsr', 'Dff'],
262
+ ['$dffsre', 'Dff'],
263
+ ['$aldff', 'Dff'],
264
+ ['$aldffe', 'Dff']]);
265
+
266
+ function module_deps(data: Yosys.Output): [string, string | number][] {
267
+ const out: [string, string | number][] = [];
268
+ for (const [name, mod] of Object.entries(data.modules)) {
269
+ out.push([name, 1/0]);
270
+ for (const cname in mod.cells) {
271
+ const cell = mod.cells[cname];
272
+ if (cell.type in data.modules)
273
+ out.push([cell.type, name]);
274
+ }
275
+ }
276
+ return out;
277
+ }
278
+
279
+ function order_ports(data: Yosys.Output): Portmaps {
280
+ const unmap = {A: 'in', Y: 'out'};
281
+ const binmap = {A: 'in1', B: 'in2', Y: 'out'};
282
+ const out = {
283
+ '$mux': {A: 'in0', B: 'in1', S: 'sel', Y: 'out'},
284
+ '$dff': {CLK: 'clk', D: 'in', Q: 'out'},
285
+ '$dffe': {CLK: 'clk', EN: 'en', D: 'in', Q: 'out'},
286
+ '$adff': {CLK: 'clk', ARST: 'arst', D: 'in', Q: 'out'},
287
+ '$adffe': {CLK: 'clk', EN: 'en', ARST: 'arst', D: 'in', Q: 'out'},
288
+ '$sdff': {CLK: 'clk', SRST: 'srst', D: 'in', Q: 'out'},
289
+ '$sdffe': {CLK: 'clk', EN: 'en', SRST: 'srst', D: 'in', Q: 'out'},
290
+ '$sdffce': {CLK: 'clk', EN: 'en', SRST: 'srst', D: 'in', Q: 'out'},
291
+ '$dlatch': {EN: 'en', D: 'in', Q: 'out'},
292
+ '$adlatch': {EN: 'en', ARST: 'arst', D: 'in', Q: 'out'},
293
+ '$dffsr': {CLK: 'clk', SET: 'set', CLR: 'clr', D: 'in', Q: 'out'},
294
+ '$dffsre': {CLK: 'clk', EN: 'en', SET: 'set', CLR: 'clr', D: 'in', Q: 'out'},
295
+ '$aldff': {CLK: 'clk', ALOAD: 'aload', AD: 'ain', D: 'in', Q: 'out'},
296
+ '$aldffe': {CLK: 'clk', EN: 'en', ALOAD: 'aload', AD: 'ain', D: 'in', Q: 'out'},
297
+ '$sr': {SET: 'set', CLR: 'clr', Q: 'out'},
298
+ '$fsm': {ARST: 'arst', CLK: 'clk', CTRL_IN: 'in', CTRL_OUT: 'out'}
299
+ };
300
+ binary_gates.forEach((nm) => out[nm] = binmap);
301
+ unary_gates.forEach((nm) => out[nm] = unmap);
302
+ for (const [name, mod] of Object.entries(data.modules)) {
303
+ const portmap: Portmap = {};
304
+ const ins = [], outs = [];
305
+ for (const pname in mod.ports) {
306
+ portmap[pname] = pname;
307
+ }
308
+ out[name] = portmap;
309
+ }
310
+ return out;
311
+ }
312
+
313
+ function decode_json_bigint(param: string | number): bigInt.BigInteger {
314
+ if (typeof param == 'string')
315
+ return bigInt(param, 2)
316
+ else if (typeof param == 'number')
317
+ return bigInt(param)
318
+ else assert(false);
319
+ }
320
+
321
+ function decode_json_number(param: Yosys.JsonConstant): number {
322
+ if (typeof param == 'string')
323
+ return Number.parseInt(param, 2);
324
+ else if (typeof param == 'number')
325
+ return param
326
+ else assert(false);
327
+ }
328
+
329
+ function decode_json_bigint_as_array(param: string | number): number[] {
330
+ return decode_json_bigint(param).toArray(2).value;
331
+ }
332
+
333
+ function decode_json_constant(param: Yosys.JsonConstant, bits: number, fill : Yosys.BitChar = '0'): string {
334
+ if (typeof param == 'number')
335
+ return bigInt(param).toArray(2).value.map(String).reverse()
336
+ .concat(Array(bits).fill(fill)).slice(0, bits).reverse().join('');
337
+ else
338
+ return param;
339
+ }
340
+
341
+ function parse_source_positions(str: string): Digitaljs.SourcePosition[] {
342
+ const ret = [];
343
+ for (const entry of str.split('|')) {
344
+ const colonIdx = entry.lastIndexOf(':');
345
+ const name = entry.slice(0, colonIdx);
346
+ const pos = entry.slice(colonIdx+1);
347
+ const [from, to] = pos.split('-').map(s => s.split('.').map(v => Number(v))).map(([line, column]) => ({line, column}));
348
+ ret.push({name, from, to});
349
+ }
350
+ return ret;
351
+ }
352
+
353
+ function yosys_to_digitaljs(data: Yosys.Output, portmaps: Portmaps, options: ConvertOptions = {}): {[key: string]: Digitaljs.Module} {
354
+ const out = {};
355
+ for (const [name, mod] of Object.entries(data.modules)) {
356
+ out[name] = yosys_to_digitaljs_mod(name, mod, portmaps, options);
357
+ }
358
+ return out
359
+ }
360
+
361
+ function yosys_to_digitaljs_mod(name: string, mod: Yosys.Module, portmaps: Portmaps, options: ConvertOptions = {}): Digitaljs.Module {
362
+ function constbit(bit: Bit): bit is Yosys.BitChar {
363
+ return (Yosys.ConstChars as readonly string[]).includes(bit.toString());
364
+ }
365
+ const nets = new HashMap<Net, NetInfo>();
366
+ const netnames = new HashMap<Net, string[]>();
367
+ const netsrc = new HashMap<Net, Digitaljs.SourcePosition[]>();
368
+ const bits = new Map<Bit, BitInfo>();
369
+ const devnets = new Map<string, Map<string, Net>>();
370
+ let n = 0, pn = 0;
371
+ function gen_name(): string {
372
+ const nm = `dev${n++}`;
373
+ devnets.set(nm, new Map());
374
+ return nm;
375
+ }
376
+ function gen_bitname(): Bit {
377
+ return `bit${pn++}`;
378
+ }
379
+ function get_net(k: Net): NetInfo {
380
+ // create net if does not exist yet
381
+ if (!nets.has(k)) {
382
+ const nms = netnames.get(k);
383
+ const src = netsrc.get(k);
384
+ nets.set(k, {source: undefined, targets: [], name: nms ? nms[0] : undefined, source_positions: src || []});
385
+ }
386
+ return nets.get(k);
387
+ }
388
+ function add_net_source(k: Net, d: string, p: string, primary: boolean = false) {
389
+ if (k.length == 0) return; // for unconnected ports
390
+ const net = get_net(k);
391
+ if(net.source !== undefined) {
392
+ // multiple sources driving one net, disallowed in digitaljs
393
+ throw Error('Multiple sources driving net: ' + net.name);
394
+ }
395
+ net.source = { id: d, port: p };
396
+ if (primary) for (const [nbit, bit] of k.entries()) {
397
+ bits.set(bit, { id: d, port: p, num: nbit });
398
+ }
399
+ devnets.get(d).set(p, k);
400
+ }
401
+ function add_net_target(k: Net, d: string, p: string) {
402
+ if (k.length == 0) return; // for unconnected ports
403
+ const net = get_net(k);
404
+ net.targets.push({ id: d, port: p });
405
+ devnets.get(d).set(p, k);
406
+ }
407
+ const mout = {
408
+ devices: {},
409
+ connectors: []
410
+ }
411
+ function add_device(dev : Digitaljs.Device): string {
412
+ const dname = gen_name();
413
+ if (options.propagation !== undefined)
414
+ dev.propagation = options.propagation;
415
+ mout.devices[dname] = dev;
416
+ return dname;
417
+ }
418
+ function add_busgroup(nbits: Net, groups: Net[]) {
419
+ if (get_net(nbits).source !== undefined)
420
+ return; // the bits were already grouped
421
+ const dname = add_device({
422
+ type: 'BusGroup',
423
+ groups: groups.map(g => g.length)
424
+ });
425
+ add_net_source(nbits, dname, 'out');
426
+ for (const [gn, group] of groups.entries()) {
427
+ add_net_target(group, dname, 'in' + gn);
428
+ }
429
+ }
430
+ function connect_device(dname: string, cell: Yosys.Cell, portmap: Portmap) {
431
+ for (const [pname, pdir] of Object.entries(cell.port_directions)) {
432
+ const pconn = cell.connections[pname];
433
+ switch (pdir) {
434
+ case 'input':
435
+ add_net_target(pconn, dname, portmap[pname]);
436
+ break;
437
+ case 'output':
438
+ add_net_source(pconn, dname, portmap[pname], true);
439
+ break;
440
+ default:
441
+ throw Error('Invalid port direction: ' + pdir);
442
+ }
443
+ }
444
+ }
445
+ function connect_pmux(dname: string, cell: Yosys.Cell) {
446
+ add_net_target(cell.connections.A, dname, 'in0');
447
+ add_net_target(cell.connections.S.slice().reverse(), dname, 'sel');
448
+ add_net_source(cell.connections.Y, dname, 'out', true);
449
+ for (const i of Array(decode_json_number(cell.parameters.S_WIDTH)).keys()) {
450
+ const p = (decode_json_number(cell.parameters.S_WIDTH)-i-1) * decode_json_number(cell.parameters.WIDTH);
451
+ add_net_target(cell.connections.B.slice(p, p + decode_json_number(cell.parameters.WIDTH)),
452
+ dname, 'in' + (i+1));
453
+ }
454
+ }
455
+ function connect_mem(dname: string, cell: Yosys.Cell, dev: Digitaljs.Device) {
456
+ for (const [k, port] of dev.rdports.entries()) {
457
+ const portname = "rd" + k;
458
+ add_net_target(cell.connections.RD_ADDR.slice(dev.abits * k, dev.abits * (k+1)),
459
+ dname, portname + "addr");
460
+ add_net_source(cell.connections.RD_DATA.slice(dev.bits * k, dev.bits * (k+1)),
461
+ dname, portname + "data", true);
462
+ if ('clock_polarity' in port)
463
+ add_net_target([cell.connections.RD_CLK[k]], dname, portname + "clk");
464
+ if ('enable_polarity' in port)
465
+ add_net_target([cell.connections.RD_EN[k]], dname, portname + "en");
466
+ if ('arst_polarity' in port)
467
+ add_net_target([cell.connections.RD_ARST[k]], dname, portname + "arst");
468
+ if ('srst_polarity' in port)
469
+ add_net_target([cell.connections.RD_SRST[k]], dname, portname + "srst");
470
+ }
471
+ for (const [k, port] of dev.wrports.entries()) {
472
+ const portname = "wr" + k;
473
+ add_net_target(cell.connections.WR_ADDR.slice(dev.abits * k, dev.abits * (k+1)),
474
+ dname, portname + "addr");
475
+ add_net_target(cell.connections.WR_DATA.slice(dev.bits * k, dev.bits * (k+1)),
476
+ dname, portname + "data");
477
+ if ('clock_polarity' in port)
478
+ add_net_target([cell.connections.WR_CLK[k]], dname, portname + "clk");
479
+ if ('enable_polarity' in port) {
480
+ if (port.no_bit_enable)
481
+ add_net_target([cell.connections.WR_EN[dev.bits * k]], dname, portname + "en");
482
+ else
483
+ add_net_target(cell.connections.WR_EN.slice(dev.bits * k, dev.bits * (k+1)),
484
+ dname, portname + "en");
485
+ }
486
+ }
487
+ }
488
+ // Find net names
489
+ for (const [nname, data] of Object.entries(mod.netnames)) {
490
+ if (data.hide_name) continue;
491
+ let l = netnames.get(data.bits);
492
+ if (l === undefined) {
493
+ l = [];
494
+ netnames.set(data.bits, l);
495
+ }
496
+ l.push(nname);
497
+ if (typeof data.attributes == 'object' && data.attributes.src) {
498
+ let l = netsrc.get(data.bits);
499
+ if (l === undefined) {
500
+ l = [];
501
+ netsrc.set(data.bits, l);
502
+ }
503
+ const positions = parse_source_positions(data.attributes.src);
504
+ l.push(...positions);
505
+ }
506
+ }
507
+ // Add inputs/outputs
508
+ for (const [pname, port] of Object.entries(mod.ports)) {
509
+ const dir = port.direction == "input" ? "Input" :
510
+ port.direction == "output" ? "Output" :
511
+ undefined;
512
+ const dname = add_device({
513
+ type: dir,
514
+ net: pname,
515
+ order: n,
516
+ bits: port.bits.length
517
+ });
518
+ switch (port.direction) {
519
+ case 'input':
520
+ add_net_source(port.bits, dname, 'out', true);
521
+ break;
522
+ case 'output':
523
+ add_net_target(port.bits, dname, 'in');
524
+ break;
525
+ default: throw Error('Invalid port direction: ' + port.direction);
526
+ }
527
+ }
528
+ // Add gates
529
+ for (const [cname, cell] of Object.entries(mod.cells)) {
530
+ const dev : Digitaljs.Device = {
531
+ label: cname,
532
+ type: gate_subst.get(cell.type)
533
+ };
534
+ if (dev.type == undefined) {
535
+ dev.type = 'Subcircuit';
536
+ dev.celltype = cell.type;
537
+ }
538
+ if (typeof cell.attributes == 'object' && cell.attributes.src) {
539
+ dev.source_positions = parse_source_positions(cell.attributes.src);
540
+ }
541
+ const dname = add_device(dev);
542
+ function match_port(con: Net, nsig: Yosys.JsonConstant, sz: number) {
543
+ const sig = decode_json_number(nsig);
544
+ if (con.length > sz)
545
+ con.splice(sz);
546
+ else if (con.length < sz) {
547
+ const ccon = con.slice();
548
+ const pad = sig ? con.slice(-1)[0] : '0';
549
+ con.splice(con.length, 0, ...Array(sz - con.length).fill(pad));
550
+ if (!con.every(constbit) && get_net(con).source === undefined) {
551
+ // WARNING: potentially troublesome hack for readability
552
+ // handled generally in the grouping phase,
553
+ // but it's hard to add sign extensions there
554
+ const extname = add_device({
555
+ type: sig ? 'SignExtend' : 'ZeroExtend',
556
+ extend: { input: ccon.length, output: con.length }
557
+ });
558
+ add_net_target(ccon, extname, 'in');
559
+ add_net_source(con, extname, 'out');
560
+ }
561
+ }
562
+ }
563
+ function zero_extend_output(con: Net) {
564
+ if (con.length > 1) {
565
+ const ccon = con.slice();
566
+ con.splice(1);
567
+ const extname = add_device({
568
+ type: 'ZeroExtend',
569
+ extend: { input: con.length, output: ccon.length }
570
+ });
571
+ add_net_source(ccon, extname, 'out');
572
+ add_net_target(con, extname, 'in');
573
+ }
574
+ }
575
+ if (unary_gates.has(cell.type)) {
576
+ assert(cell.connections.A.length == decode_json_number(cell.parameters.A_WIDTH));
577
+ assert(cell.connections.Y.length == decode_json_number(cell.parameters.Y_WIDTH));
578
+ assert(cell.port_directions.A == 'input');
579
+ assert(cell.port_directions.Y == 'output');
580
+ }
581
+ if (binary_gates.has(cell.type)) {
582
+ assert(cell.connections.A.length == decode_json_number(cell.parameters.A_WIDTH));
583
+ assert(cell.connections.B.length == decode_json_number(cell.parameters.B_WIDTH));
584
+ assert(cell.connections.Y.length == decode_json_number(cell.parameters.Y_WIDTH));
585
+ assert(cell.port_directions.A == 'input');
586
+ assert(cell.port_directions.B == 'input');
587
+ assert(cell.port_directions.Y == 'output');
588
+ }
589
+ if (['$dff', '$dffe', '$adff', '$adffe', '$sdff', '$sdffe', '$sdffce', '$dlatch', '$adlatch', '$dffsr', '$dffsre', '$aldff', '$aldffe'].includes(cell.type)) {
590
+ assert(cell.connections.D.length == decode_json_number(cell.parameters.WIDTH));
591
+ assert(cell.connections.Q.length == decode_json_number(cell.parameters.WIDTH));
592
+ assert(cell.port_directions.D == 'input');
593
+ assert(cell.port_directions.Q == 'output');
594
+ if (cell.type != '$dlatch' && cell.type != '$adlatch') {
595
+ assert(cell.connections.CLK.length == 1);
596
+ assert(cell.port_directions.CLK == 'input');
597
+ }
598
+ }
599
+ if (['$dffe', '$adffe', '$sdffe', '$sdffce', '$dffsre', '$aldffe', '$dlatch', '$adlatch'].includes(cell.type)) {
600
+ assert(cell.connections.EN.length == 1);
601
+ assert(cell.port_directions.EN == 'input');
602
+ }
603
+ if (['$adff', '$adffe', '$adlatch'].includes(cell.type)) {
604
+ assert(cell.connections.ARST.length == 1);
605
+ assert(cell.port_directions.ARST == 'input');
606
+ }
607
+ if (['$sdff', '$sdffe', '$sdffce'].includes(cell.type)) {
608
+ assert(cell.connections.SRST.length == 1);
609
+ assert(cell.port_directions.SRST == 'input');
610
+ }
611
+ if (['$dffsr', '$dffsre'].includes(cell.type)) {
612
+ assert(cell.connections.SET.length == decode_json_number(cell.parameters.WIDTH));
613
+ assert(cell.connections.CLR.length == decode_json_number(cell.parameters.WIDTH));
614
+ assert(cell.port_directions.SET == 'input');
615
+ assert(cell.port_directions.CLR == 'input');
616
+ }
617
+ switch (cell.type) {
618
+ case '$neg': case '$pos':
619
+ dev.bits = {
620
+ in: cell.connections.A.length,
621
+ out: cell.connections.Y.length
622
+ };
623
+ dev.signed = Boolean(decode_json_number(cell.parameters.A_SIGNED));
624
+ break;
625
+ case '$not':
626
+ match_port(cell.connections.A, cell.parameters.A_SIGNED, cell.connections.Y.length);
627
+ dev.bits = cell.connections.Y.length;
628
+ break;
629
+ case '$add': case '$sub': case '$mul': case '$div': case '$mod': case '$pow':
630
+ dev.bits = {
631
+ in1: cell.connections.A.length,
632
+ in2: cell.connections.B.length,
633
+ out: cell.connections.Y.length
634
+ };
635
+ dev.signed = {
636
+ in1: Boolean(decode_json_number(cell.parameters.A_SIGNED)),
637
+ in2: Boolean(decode_json_number(cell.parameters.B_SIGNED))
638
+ }
639
+ break;
640
+ case '$and': case '$or': case '$xor': case '$xnor':
641
+ match_port(cell.connections.A, cell.parameters.A_SIGNED, cell.connections.Y.length);
642
+ match_port(cell.connections.B, cell.parameters.B_SIGNED, cell.connections.Y.length);
643
+ dev.bits = cell.connections.Y.length;
644
+ break;
645
+ case '$reduce_and': case '$reduce_or': case '$reduce_xor': case '$reduce_xnor':
646
+ case '$reduce_bool': case '$logic_not':
647
+ dev.bits = cell.connections.A.length;
648
+ zero_extend_output(cell.connections.Y);
649
+ if (dev.bits == 1) {
650
+ if (['$reduce_xnor', '$logic_not'].includes(cell.type))
651
+ dev.type = 'Not';
652
+ else
653
+ dev.type = 'Repeater';
654
+ }
655
+ break;
656
+ case '$eq': case '$ne': case '$lt': case '$le': case '$gt': case '$ge':
657
+ case '$eqx': case '$nex':
658
+ dev.bits = {
659
+ in1: cell.connections.A.length,
660
+ in2: cell.connections.B.length
661
+ };
662
+ dev.signed = {
663
+ in1: Boolean(decode_json_number(cell.parameters.A_SIGNED)),
664
+ in2: Boolean(decode_json_number(cell.parameters.B_SIGNED))
665
+ };
666
+ zero_extend_output(cell.connections.Y);
667
+ break;
668
+ case '$shl': case '$shr': case '$sshl': case '$sshr':
669
+ case '$shift': case '$shiftx':
670
+ dev.bits = {
671
+ in1: cell.connections.A.length,
672
+ in2: cell.connections.B.length,
673
+ out: cell.connections.Y.length
674
+ };
675
+ dev.signed = {
676
+ in1: Boolean(decode_json_number(cell.parameters.A_SIGNED)),
677
+ in2: Boolean(decode_json_number(cell.parameters.B_SIGNED) && ['$shift', '$shiftx'].includes(cell.type)),
678
+ out: Boolean(decode_json_number(cell.parameters.A_SIGNED) && ['$sshl', '$sshr'].includes(cell.type))
679
+ };
680
+ dev.fillx = cell.type == '$shiftx';
681
+ break;
682
+ case '$logic_and': case '$logic_or': {
683
+ function reduce_input(con: Net) {
684
+ const ccon = con.slice();
685
+ con.splice(0, con.length, gen_bitname());
686
+ const extname = add_device({
687
+ type: 'OrReduce',
688
+ bits: ccon.length
689
+ });
690
+ add_net_source(con, extname, 'out');
691
+ add_net_target(ccon, extname, 'in');
692
+ }
693
+ if (cell.connections.A.length > 1)
694
+ reduce_input(cell.connections.A);
695
+ if (cell.connections.B.length > 1)
696
+ reduce_input(cell.connections.B);
697
+ zero_extend_output(cell.connections.Y);
698
+ break;
699
+ }
700
+ case '$mux':
701
+ assert(cell.connections.A.length == decode_json_number(cell.parameters.WIDTH));
702
+ assert(cell.connections.B.length == decode_json_number(cell.parameters.WIDTH));
703
+ assert(cell.connections.Y.length == decode_json_number(cell.parameters.WIDTH));
704
+ assert(cell.port_directions.A == 'input');
705
+ assert(cell.port_directions.B == 'input');
706
+ assert(cell.port_directions.Y == 'output');
707
+ dev.bits = {
708
+ in: decode_json_number(cell.parameters.WIDTH),
709
+ sel: 1
710
+ };
711
+ break;
712
+ case '$pmux':
713
+ assert(cell.connections.B.length == decode_json_number(cell.parameters.WIDTH) * decode_json_number(cell.parameters.S_WIDTH));
714
+ assert(cell.connections.A.length == decode_json_number(cell.parameters.WIDTH));
715
+ assert(cell.connections.S.length == decode_json_number(cell.parameters.S_WIDTH));
716
+ assert(cell.connections.Y.length == decode_json_number(cell.parameters.WIDTH));
717
+ assert(cell.port_directions.A == 'input');
718
+ assert(cell.port_directions.B == 'input');
719
+ assert(cell.port_directions.S == 'input');
720
+ assert(cell.port_directions.Y == 'output');
721
+ dev.bits = {
722
+ in: decode_json_number(cell.parameters.WIDTH),
723
+ sel: decode_json_number(cell.parameters.S_WIDTH)
724
+ };
725
+ break;
726
+ case '$dff':
727
+ dev.bits = decode_json_number(cell.parameters.WIDTH);
728
+ dev.polarity = {
729
+ clock: Boolean(decode_json_number(cell.parameters.CLK_POLARITY))
730
+ };
731
+ break;
732
+ case '$dffe':
733
+ dev.bits = decode_json_number(cell.parameters.WIDTH);
734
+ dev.polarity = {
735
+ clock: Boolean(decode_json_number(cell.parameters.CLK_POLARITY)),
736
+ enable: Boolean(decode_json_number(cell.parameters.EN_POLARITY))
737
+ };
738
+ break;
739
+ case '$aldff':
740
+ dev.bits = decode_json_number(cell.parameters.WIDTH);
741
+ dev.polarity = {
742
+ clock: Boolean(decode_json_number(cell.parameters.CLK_POLARITY)),
743
+ aload: Boolean(decode_json_number(cell.parameters.ALOAD_POLARITY))
744
+ };
745
+ break;
746
+ case '$aldffe':
747
+ dev.bits = decode_json_number(cell.parameters.WIDTH);
748
+ dev.polarity = {
749
+ clock: Boolean(decode_json_number(cell.parameters.CLK_POLARITY)),
750
+ enable: Boolean(decode_json_number(cell.parameters.EN_POLARITY)),
751
+ aload: Boolean(decode_json_number(cell.parameters.ALOAD_POLARITY))
752
+ };
753
+ break;
754
+ case '$adff':
755
+ dev.bits = decode_json_number(cell.parameters.WIDTH);
756
+ dev.polarity = {
757
+ clock: Boolean(decode_json_number(cell.parameters.CLK_POLARITY)),
758
+ arst: Boolean(decode_json_number(cell.parameters.ARST_POLARITY))
759
+ };
760
+ dev.arst_value = decode_json_constant(cell.parameters.ARST_VALUE, dev.bits);
761
+ break;
762
+ case '$sdff':
763
+ dev.bits = decode_json_number(cell.parameters.WIDTH);
764
+ dev.polarity = {
765
+ clock: Boolean(decode_json_number(cell.parameters.CLK_POLARITY)),
766
+ srst: Boolean(decode_json_number(cell.parameters.SRST_POLARITY))
767
+ };
768
+ dev.srst_value = decode_json_constant(cell.parameters.SRST_VALUE, dev.bits);
769
+ break;
770
+ case '$adffe':
771
+ dev.bits = decode_json_number(cell.parameters.WIDTH);
772
+ dev.polarity = {
773
+ clock: Boolean(decode_json_number(cell.parameters.CLK_POLARITY)),
774
+ arst: Boolean(decode_json_number(cell.parameters.ARST_POLARITY)),
775
+ enable: Boolean(decode_json_number(cell.parameters.EN_POLARITY))
776
+ };
777
+ dev.arst_value = decode_json_constant(cell.parameters.ARST_VALUE, dev.bits);
778
+ break;
779
+ case '$sdffe':
780
+ dev.bits = decode_json_number(cell.parameters.WIDTH);
781
+ dev.polarity = {
782
+ clock: Boolean(decode_json_number(cell.parameters.CLK_POLARITY)),
783
+ srst: Boolean(decode_json_number(cell.parameters.SRST_POLARITY)),
784
+ enable: Boolean(decode_json_number(cell.parameters.EN_POLARITY))
785
+ };
786
+ dev.srst_value = decode_json_constant(cell.parameters.SRST_VALUE, dev.bits);
787
+ break;
788
+ case '$sdffce':
789
+ dev.bits = decode_json_number(cell.parameters.WIDTH);
790
+ dev.polarity = {
791
+ clock: Boolean(decode_json_number(cell.parameters.CLK_POLARITY)),
792
+ srst: Boolean(decode_json_number(cell.parameters.SRST_POLARITY)),
793
+ enable: Boolean(decode_json_number(cell.parameters.EN_POLARITY))
794
+ };
795
+ dev.enable_srst = true;
796
+ dev.srst_value = decode_json_constant(cell.parameters.SRST_VALUE, dev.bits);
797
+ break;
798
+ case '$dlatch':
799
+ dev.bits = decode_json_number(cell.parameters.WIDTH);
800
+ dev.polarity = {
801
+ enable: Boolean(decode_json_number(cell.parameters.EN_POLARITY))
802
+ };
803
+ break;
804
+ case '$adlatch':
805
+ dev.bits = decode_json_number(cell.parameters.WIDTH);
806
+ dev.polarity = {
807
+ enable: Boolean(decode_json_number(cell.parameters.EN_POLARITY)),
808
+ arst: Boolean(decode_json_number(cell.parameters.ARST_POLARITY))
809
+ };
810
+ dev.arst_value = decode_json_constant(cell.parameters.ARST_VALUE, dev.bits);
811
+ break;
812
+ case '$dffsr':
813
+ dev.bits = decode_json_number(cell.parameters.WIDTH);
814
+ dev.polarity = {
815
+ clock: Boolean(decode_json_number(cell.parameters.CLK_POLARITY)),
816
+ set: Boolean(decode_json_number(cell.parameters.SET_POLARITY)),
817
+ clr: Boolean(decode_json_number(cell.parameters.CLR_POLARITY))
818
+ };
819
+ break;
820
+ case '$dffsre':
821
+ dev.bits = decode_json_number(cell.parameters.WIDTH);
822
+ dev.polarity = {
823
+ clock: Boolean(decode_json_number(cell.parameters.CLK_POLARITY)),
824
+ enable: Boolean(decode_json_number(cell.parameters.EN_POLARITY)),
825
+ set: Boolean(decode_json_number(cell.parameters.SET_POLARITY)),
826
+ clr: Boolean(decode_json_number(cell.parameters.CLR_POLARITY))
827
+ };
828
+ break;
829
+ case '$sr':
830
+ assert(cell.connections.Q.length == decode_json_number(cell.parameters.WIDTH));
831
+ assert(cell.port_directions.Q == 'output');
832
+ dev.no_data = true;
833
+ dev.bits = decode_json_number(cell.parameters.WIDTH);
834
+ dev.polarity = {
835
+ set: Boolean(decode_json_number(cell.parameters.SET_POLARITY)),
836
+ clr: Boolean(decode_json_number(cell.parameters.CLR_POLARITY))
837
+ };
838
+ break;
839
+ case '$fsm': {
840
+ assert(cell.connections.ARST.length == 1);
841
+ assert(cell.connections.CLK.length == 1);
842
+ assert(cell.connections.CTRL_IN.length == decode_json_number(cell.parameters.CTRL_IN_WIDTH));
843
+ assert(cell.connections.CTRL_OUT.length == decode_json_number(cell.parameters.CTRL_OUT_WIDTH));
844
+ const TRANS_NUM = decode_json_number(cell.parameters.TRANS_NUM);
845
+ const STATE_NUM_LOG2 = decode_json_number(cell.parameters.STATE_NUM_LOG2);
846
+ const step = 2*STATE_NUM_LOG2
847
+ + decode_json_number(cell.parameters.CTRL_IN_WIDTH)
848
+ + decode_json_number(cell.parameters.CTRL_OUT_WIDTH);
849
+ const tt = typeof(cell.parameters.TRANS_TABLE) == "number"
850
+ ? Vector3vl.fromBin(bigInt(cell.parameters.TRANS_TABLE).toString(2), TRANS_NUM * step).toBin() // workaround for yosys silliness
851
+ : cell.parameters.TRANS_TABLE;
852
+ assert(tt.length == TRANS_NUM * step);
853
+ dev.polarity = {
854
+ clock: Boolean(decode_json_number(cell.parameters.CLK_POLARITY)),
855
+ arst: Boolean(decode_json_number(cell.parameters.ARST_POLARITY))
856
+ };
857
+ dev.wirename = cell.parameters.NAME;
858
+ dev.bits = {
859
+ in: decode_json_number(cell.parameters.CTRL_IN_WIDTH),
860
+ out: decode_json_number(cell.parameters.CTRL_OUT_WIDTH)
861
+ };
862
+ dev.states = decode_json_number(cell.parameters.STATE_NUM);
863
+ dev.init_state = decode_json_number(cell.parameters.STATE_RST);
864
+ dev.trans_table = [];
865
+ for (let i = 0; i < TRANS_NUM; i++) {
866
+ let base = i * step;
867
+ const f = (sz) => {
868
+ const ret = tt.slice(base, base + sz);
869
+ base += sz;
870
+ return ret;
871
+ };
872
+ const o = {
873
+ state_in: parseInt(f(STATE_NUM_LOG2), 2),
874
+ ctrl_in: f(decode_json_number(cell.parameters.CTRL_IN_WIDTH)).replace(/-/g, 'x'),
875
+ state_out: parseInt(f(STATE_NUM_LOG2), 2),
876
+ ctrl_out: f(decode_json_number(cell.parameters.CTRL_OUT_WIDTH))
877
+ };
878
+ dev.trans_table.push(o);
879
+ }
880
+ break;
881
+ }
882
+ case '$mem':
883
+ case '$mem_v2': {
884
+ const RD_PORTS = decode_json_number(cell.parameters.RD_PORTS);
885
+ const WR_PORTS = decode_json_number(cell.parameters.WR_PORTS);
886
+ assert(cell.connections.RD_EN.length == RD_PORTS);
887
+ assert(cell.connections.RD_CLK.length == RD_PORTS);
888
+ assert(cell.connections.RD_DATA.length == RD_PORTS * decode_json_number(cell.parameters.WIDTH));
889
+ assert(cell.connections.RD_ADDR.length == RD_PORTS * decode_json_number(cell.parameters.ABITS));
890
+ assert(cell.connections.WR_EN.length == WR_PORTS * decode_json_number(cell.parameters.WIDTH));
891
+ assert(cell.connections.WR_CLK.length == WR_PORTS);
892
+ assert(cell.connections.WR_DATA.length == WR_PORTS * decode_json_number(cell.parameters.WIDTH));
893
+ assert(cell.connections.WR_ADDR.length == WR_PORTS * decode_json_number(cell.parameters.ABITS));
894
+ if (cell.type == "$mem_v2") {
895
+ assert(cell.connections.RD_ARST.length == RD_PORTS);
896
+ assert(cell.connections.RD_SRST.length == RD_PORTS);
897
+ }
898
+ dev.bits = decode_json_number(cell.parameters.WIDTH);
899
+ dev.abits = decode_json_number(cell.parameters.ABITS);
900
+ dev.words = decode_json_number(cell.parameters.SIZE);
901
+ dev.offset = decode_json_number(cell.parameters.OFFSET);
902
+ dev.rdports = [];
903
+ dev.wrports = [];
904
+ const rdpol = decode_json_bigint_as_array(cell.parameters.RD_CLK_POLARITY).reverse();
905
+ const rden = decode_json_bigint_as_array(cell.parameters.RD_CLK_ENABLE).reverse();
906
+ const rdtr = cell.type == "$mem_v2"
907
+ ? []
908
+ : decode_json_bigint_as_array(cell.parameters.RD_TRANSPARENT).reverse();
909
+ const wrpol = decode_json_bigint_as_array(cell.parameters.WR_CLK_POLARITY).reverse();
910
+ const wren = decode_json_bigint_as_array(cell.parameters.WR_CLK_ENABLE).reverse();
911
+ const init = typeof(cell.parameters.INIT) == 'number'
912
+ ? bigInt(cell.parameters.INIT).toArray(2).value.map(String).reverse()
913
+ : cell.parameters.INIT.split('').reverse();
914
+ const v2_feature = (param) => cell.type == "$mem_v2" ? decode_json_bigint_as_array(param).reverse() : [];
915
+ const v2_feature_const = (param, size) => cell.type == "$mem_v2" ? decode_json_constant(param, size) : "";
916
+ const rdtrmask = v2_feature(cell.parameters.RD_TRANSPARENCY_MASK);
917
+ const rdcolmask = v2_feature(cell.parameters.RD_COLLISION_X_MASK);
918
+ const rdensrst = v2_feature(cell.parameters.RD_CE_OVER_SRST);
919
+ const rdinit = v2_feature_const(cell.parameters.RD_INIT_VALUE, dev.bits * RD_PORTS);
920
+ const rdarst = v2_feature_const(cell.parameters.RD_ARST_VALUE, dev.bits * RD_PORTS);
921
+ const rdsrst = v2_feature_const(cell.parameters.RD_SRST_VALUE, dev.bits * RD_PORTS);
922
+ if (cell.parameters.INIT) {
923
+ const l = init.slice(-1)[0] == 'x' ? 'x' : '0';
924
+ const memdata = new Mem3vl(dev.bits, dev.words);
925
+ for (const k of Array(dev.words).keys()) {
926
+ const wrd = init.slice(dev.bits * k, dev.bits * (k+1));
927
+ while (wrd.length < dev.bits) wrd.push(l);
928
+ memdata.set(k, Vector3vl.fromBin(wrd.reverse().join('')));
929
+ }
930
+ dev.memdata = memdata.toJSON();
931
+ }
932
+ for (const k of Array(RD_PORTS).keys()) {
933
+ const port: Digitaljs.MemReadPort = {
934
+ };
935
+ if (rden[k]) {
936
+ port.clock_polarity = Boolean(rdpol[k]);
937
+ if (cell.connections.RD_EN[k] != '1')
938
+ port.enable_polarity = true;
939
+ };
940
+ if (rdtr[k])
941
+ port.transparent = true;
942
+ if (cell.type == "$mem_v2") {
943
+ if (rdensrst[k])
944
+ port.enable_srst = true;
945
+ function mk_init(s: string, f: (v: string) => void) {
946
+ const v = s.slice(dev.bits * k, dev.bits * (k+1));
947
+ if (!v.split('').every(c => c == 'x'))
948
+ f(v);
949
+ };
950
+ mk_init(rdinit, v => port.init_value = v);
951
+ if (cell.connections.RD_ARST[k] != '0') {
952
+ port.arst_polarity = true;
953
+ mk_init(rdarst, v => port.arst_value = v);
954
+ }
955
+ if (cell.connections.RD_SRST[k] != '0') {
956
+ port.srst_polarity = true;
957
+ mk_init(rdsrst, v => port.srst_value = v);
958
+ }
959
+ function mk_mask(s: number[], f: (v: boolean | boolean[]) => void) {
960
+ const v = Array(WR_PORTS).fill(0);
961
+ s.slice(WR_PORTS * k, WR_PORTS * (k+1)).map((c, i) => { v[i] = c });
962
+ if (v.every(c => c))
963
+ f(true);
964
+ else if (v.some(c => c))
965
+ f(v.map(c => Boolean(c)));
966
+ }
967
+ mk_mask(rdtrmask, v => port.transparent = v);
968
+ mk_mask(rdcolmask, v => port.collision = v);
969
+ }
970
+ dev.rdports.push(port);
971
+ }
972
+ for (const k of Array(WR_PORTS).keys()) {
973
+ const port: Digitaljs.MemWritePort = {
974
+ };
975
+ if (wren[k]) {
976
+ port.clock_polarity = Boolean(wrpol[k]);
977
+ const wr_en_connections = cell.connections.WR_EN.slice(dev.bits * k, dev.bits * (k+1));
978
+ if (wr_en_connections.some(z => z != '1')) {
979
+ port.enable_polarity = true;
980
+ if (wr_en_connections.every(z => z == wr_en_connections[0]))
981
+ port.no_bit_enable = true;
982
+ }
983
+ };
984
+ dev.wrports.push(port);
985
+ }
986
+ break;
987
+ }
988
+ case '$lut':
989
+ assert(cell.connections.A.length == decode_json_number(cell.parameters.WIDTH));
990
+ assert(cell.connections.Y.length == 1);
991
+ assert(cell.port_directions.A == 'input');
992
+ assert(cell.port_directions.Y == 'output');
993
+ dev.abits = cell.connections.A.length;
994
+ dev.bits = cell.connections.Y.length;
995
+ dev.rdports = [{}];
996
+ dev.wrports = [];
997
+ dev.memdata = cell.parameters.LUT.split('').reverse();
998
+ assert(dev.memdata.length == Math.pow(2, dev.abits));
999
+
1000
+ // Rewrite cell connections to be $mem compatible for port mapping
1001
+ cell.connections.RD_ADDR = cell.connections.A;
1002
+ cell.connections.RD_DATA = cell.connections.Y;
1003
+ delete cell.connections.A;
1004
+ delete cell.connections.Y;
1005
+ break;
1006
+ default:
1007
+ }
1008
+ if (dev.type == 'Dff') {
1009
+ // find register initial value, if exists
1010
+ // Yosys puts initial values in net attributes; there can be many for single actual net!
1011
+ const nms = netnames.get(cell.connections.Q);
1012
+ if (nms !== undefined) {
1013
+ for (const nm of nms) {
1014
+ if (mod.netnames[nm].attributes.init !== undefined)
1015
+ dev.initial = decode_json_constant(mod.netnames[nm].attributes.init, dev.bits);
1016
+ }
1017
+ }
1018
+ }
1019
+ const portmap = portmaps[cell.type];
1020
+ if (portmap) connect_device(dname, cell, portmap);
1021
+ else if (cell.type == '$pmux') connect_pmux(dname, cell);
1022
+ else if (cell.type == '$mem') connect_mem(dname, cell, dev);
1023
+ else if (cell.type == '$mem_v2') connect_mem(dname, cell, dev);
1024
+ else if (cell.type == '$lut') connect_mem(dname, cell, dev);
1025
+ else throw Error('Invalid cell type: ' + cell.type);
1026
+ }
1027
+ // Group bits into nets for complex sources
1028
+ for (const [nbits, net] of nets.entries()) {
1029
+ if (net.source !== undefined) continue;
1030
+ const groups: Net[] = [[]];
1031
+ let pbitinfo: BitInfo | 'const' | undefined = undefined;
1032
+ for (const bit of nbits) {
1033
+ let bitinfo: BitInfo | 'const' = bits.get(bit);
1034
+ if (bitinfo == undefined && constbit(bit))
1035
+ bitinfo = 'const';
1036
+ if (groups.slice(-1)[0].length > 0 &&
1037
+ (typeof bitinfo != typeof pbitinfo ||
1038
+ typeof bitinfo == 'object' &&
1039
+ typeof pbitinfo == 'object' &&
1040
+ (bitinfo.id != pbitinfo.id ||
1041
+ bitinfo.port != pbitinfo.port ||
1042
+ bitinfo.num != pbitinfo.num + 1))) {
1043
+ groups.push([]);
1044
+ }
1045
+ groups.slice(-1)[0].push(bit);
1046
+ pbitinfo = bitinfo;
1047
+ }
1048
+ if (groups.length == 1) continue;
1049
+ if (groups.slice(-1)[0].every(x => x == '0')) {
1050
+ // infer zero-extend
1051
+ const ilen = nbits.length - groups.slice(-1)[0].length;
1052
+ const dname = add_device({
1053
+ type: 'ZeroExtend',
1054
+ extend: { output: nbits.length, input: ilen }
1055
+ });
1056
+ const zbits = nbits.slice(0, ilen);
1057
+ add_net_source(nbits, dname, 'out');
1058
+ add_net_target(zbits, dname, 'in');
1059
+ if (groups.length > 2)
1060
+ add_busgroup(zbits, groups.slice(0, groups.length - 1));
1061
+ } else add_busgroup(nbits, groups);
1062
+ }
1063
+ // Add constants
1064
+ for (const [nbits, net] of nets.entries()) {
1065
+ if (net.source !== undefined) continue;
1066
+ if (!nbits.every(constbit))
1067
+ continue;
1068
+ const dname = add_device({
1069
+ // label: String(val), // TODO
1070
+ type: 'Constant',
1071
+ constant: nbits.slice().reverse().join('')
1072
+ });
1073
+ add_net_source(nbits, dname, 'out');
1074
+ }
1075
+ // Select bits from complex targets
1076
+ for (const [nbits, net] of nets.entries()) {
1077
+ if (net.source !== undefined) continue;
1078
+ // constants should be already handled!
1079
+ assert(nbits.every(x => constbit(x) || (typeof x == 'number' && x > 1)));
1080
+ const bitinfos = nbits.map(x => bits.get(x));
1081
+ if (!bitinfos.every(x => typeof x == 'object'))
1082
+ continue; // ignore not fully driven ports
1083
+ // complex sources should be already handled!
1084
+ assert(bitinfos.every(info => info.id == bitinfos[0].id &&
1085
+ info.port == bitinfos[0].port));
1086
+ const cconn = devnets.get(bitinfos[0].id).get(bitinfos[0].port);
1087
+ const dname = add_device({
1088
+ type: 'BusSlice',
1089
+ slice: {
1090
+ first: bitinfos[0].num,
1091
+ count: bitinfos.length,
1092
+ total: cconn.length
1093
+ }
1094
+ });
1095
+ add_net_source(nbits, dname, 'out');
1096
+ add_net_target(cconn, dname, 'in');
1097
+ }
1098
+ // Generate connections between devices
1099
+ for (const [nbits, net] of nets.entries()) {
1100
+ if (net.source === undefined) {
1101
+ console.warn('Undriven net in ' + name + ': ' + nbits);
1102
+ continue;
1103
+ }
1104
+ let first = true;
1105
+ for (const target in net.targets) {
1106
+ const conn: Digitaljs.Connector = {
1107
+ to: net.targets[target],
1108
+ from: net.source
1109
+ };
1110
+ if (net.name) conn.name = net.name;
1111
+ if (net.source_positions) conn.source_positions = net.source_positions;
1112
+ if (!first && mout.devices[conn.from.id].type == "Constant") {
1113
+ // replicate constants for better clarity
1114
+ const dname = add_device({
1115
+ type: 'Constant',
1116
+ constant: mout.devices[conn.from.id].constant
1117
+ });
1118
+ conn.from = {id: dname, port: 'out'};
1119
+ }
1120
+ mout.connectors.push(conn);
1121
+ first = false;
1122
+ }
1123
+ }
1124
+ return mout;
1125
+ }
1126
+
1127
+ export function yosys2digitaljs(obj: Yosys.Output, options: ConvertOptions = {}): Digitaljs.TopModule {
1128
+ const portmaps = order_ports(obj);
1129
+ const out = yosys_to_digitaljs(obj, portmaps, options);
1130
+ const toporder = topsort(module_deps(obj));
1131
+ toporder.pop();
1132
+ const toplevel = toporder.pop();
1133
+ const output: Digitaljs.TopModule = { subcircuits: {}, ... out[toplevel] };
1134
+ for (const x of toporder)
1135
+ output.subcircuits[x] = out[x];
1136
+ return output;
1137
+ }
1138
+
1139
+ export function io_ui(output: Digitaljs.Module) {
1140
+ for (const [name, dev] of Object.entries(output.devices)) {
1141
+ if (dev.type == 'Input' || dev.type == 'Output') {
1142
+ dev.label = dev.net;
1143
+ }
1144
+ // use clock for clocky named inputs
1145
+ if (dev.type == 'Input' && dev.bits == 1 && (dev.label == 'clk' || dev.label == 'clock')) {
1146
+ dev.type = 'Clock';
1147
+ dev.propagation = 100;
1148
+ }
1149
+ if (dev.type == 'Input')
1150
+ dev.type = dev.bits == 1 ? 'Button' : 'NumEntry';
1151
+ if (dev.type == 'Output') {
1152
+ if (dev.bits == 1)
1153
+ dev.type = 'Lamp';
1154
+ else if (dev.bits == 8 && (dev.label == 'display7' || dev.label.startsWith('display7_')))
1155
+ dev.type = 'Display7';
1156
+ else
1157
+ dev.type = 'NumDisplay';
1158
+ }
1159
+ }
1160
+ }
1161
+
1162
+ function ansi_c_escape_contents(cmd: string): string {
1163
+ function func(ch: string) {
1164
+ if (ch == '\t') return '\\t';
1165
+ if (ch == '\r') return '\\r';
1166
+ if (ch == '\n') return '\\n';
1167
+ return '\\x' + ch.charCodeAt(0).toString(16).padStart(2, '0');
1168
+ }
1169
+ return cmd.replace(/(["'\\])/g,'\\$1')
1170
+ .replace(/[\x00-\x1F\x7F-\x9F]/g, func);
1171
+ }
1172
+
1173
+ function ansi_c_escape(cmd: string): string {
1174
+ return '"' + ansi_c_escape_contents(cmd) + '"';
1175
+ }
1176
+
1177
+ function shell_escape_contents(cmd: string): string {
1178
+ return cmd.replace(/(["\r\n$`\\])/g,'\\$1');
1179
+ }
1180
+
1181
+ function shell_escape(cmd: string): string {
1182
+ return '"' + shell_escape_contents(cmd) + '"';
1183
+ }
1184
+
1185
+ function process_filename(filename: string): string {
1186
+ const flags = /\.sv$/.test(filename) ? "-sv" : "";
1187
+ return `read_verilog ${flags} ${ansi_c_escape(filename)}`;
1188
+ }
1189
+
1190
+ export function prepare_yosys_script(filenames: string[], options: Options): string {
1191
+ const optimize_simp = options.optimize ? "opt" : "opt_clean";
1192
+ const optimize = options.optimize ? "opt -full" : "opt_clean";
1193
+ const fsmexpand = options.fsmexpand ? " -expand" : "";
1194
+ const fsmpass = options.fsm == "nomap"
1195
+ ? "fsm -nomap" + fsmexpand
1196
+ : options.fsm
1197
+ ? "fsm" + fsmexpand
1198
+ : "";
1199
+
1200
+ const readVerilogFilesScript = filenames
1201
+ .map((filename) => process_filename(filename))
1202
+
1203
+ const yosysScript = [...readVerilogFilesScript, 'hierarchy -auto-top', 'proc', optimize_simp, fsmpass, 'memory -nomap', 'wreduce -memx', optimize]
1204
+ return yosysScript.join('; ');
1205
+ }
1206
+
1207
+ export function prepare_verilator_args(filenames: string[]): string[] {
1208
+ const processed_filenames = filenames.map(shell_escape);
1209
+ return ['-lint-only', '-Wall', '-Wno-DECLFILENAME', '-Wno-UNOPT', '-Wno-UNOPTFLAT', ...processed_filenames];
1210
+ }