-
Notifications
You must be signed in to change notification settings - Fork 11
/
yosys_json.py
417 lines (326 loc) · 13.6 KB
/
yosys_json.py
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2021 The SymbiFlow Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
""" Utility for converting yosys json to logical netlist. """
import argparse
import json
from fpga_interchange.interchange_capnp import Interchange, write_capnp_file
from fpga_interchange.logical_netlist import LogicalNetlist, Cell, \
CellInstance, Direction, Library
def is_bus(bits, offset, upto):
""" Returns true if this port/net is a bus.
>>> is_bus([2], offset=0, upto=0)
False
>>> is_bus([2, 3], offset=0, upto=0)
True
>>> is_bus([2], offset=1, upto=0)
True
>>> is_bus([2], offset=0, upto=1)
True
"""
return len(bits) > 1 or offset != 0 or upto != 0
def interp_yosys_net(bits, offset, upto):
""" Convert yosys json bits/offset/upto into (net selection, net bit)
Yosys JSON encodes multi-bit nets as a triple of bits / offset / upto:
- bits is a list of net bits that uniquely identifies what net the
signal is tied too.
- offset (default: 0) is the net offset. Examples:
wire [7:4] ex1; // offset = 4
wire [3:0] ex2; // offset = 0 (implicitly)
wire [0:3] ex3; // offset = 0 (implicitly)
wire [5:7] ex4; // offset = 5
- upto (default: 0) determines if the net is count up or count down.
wire [7:4] ex1; // upto = 0 (implicitly)
wire [3:0] ex2; // upto = 0 (implicitly)
wire [0:3] ex3; // upto = 1
wire [5:7] ex4; // upto = 1
>>> bits = [2, 3, 4, 5]
>>> tuple(interp_yosys_net(bits, offset=0, upto=0))
((0, 2), (1, 3), (2, 4), (3, 5))
>>> tuple(interp_yosys_net(bits, offset=4, upto=0))
((4, 2), (5, 3), (6, 4), (7, 5))
>>> tuple(interp_yosys_net(bits, offset=0, upto=1))
((3, 2), (2, 3), (1, 4), (0, 5))
>>> tuple(interp_yosys_net(bits, offset=4, upto=1))
((7, 2), (6, 3), (5, 4), (4, 5))
"""
if not upto:
for idx, bit in enumerate(bits):
yield idx + offset, bit
else:
for idx, bit in enumerate(bits):
yield offset + (len(bits) - 1) - idx, bit
# FIXME: These constants should likely be from the device database.
VCC_CELL_TYPE = 'VCC'
GND_CELL_TYPE = 'GND'
VCC_PORT = 'P'
GND_PORT = 'G'
def create_unique_name(names, base_name):
if base_name not in names:
return base_name
idx = 0
while True:
name = '{}_{}'.format(base_name, idx)
if name not in names:
return name
idx += 1
def make_vcc_cell(cell, module_data):
cell_names = set(cell.cell_instances.keys()) | set(
module_data['cells'].keys())
vcc_cell = create_unique_name(cell_names, '$__vcc')
cell.add_cell_instance(name=vcc_cell, cell_name=VCC_CELL_TYPE)
return vcc_cell
def make_gnd_cell(cell, module_data):
cell_names = set(cell.cell_instances.keys()) | set(
module_data['cells'].keys())
gnd_cell = create_unique_name(cell_names, '$__gnd')
cell.add_cell_instance(name=gnd_cell, cell_name=GND_CELL_TYPE)
return gnd_cell
def convert_cell(module_name, module_data, library, libraries, modules,
verbose, errors):
for cell_name, cell_data in module_data['cells'].items():
# Don't import modules that are missing children, they likely aren't
# important.
if cell_data['type'] not in modules:
errors[
module_name] = 'Failed to import cell type {} because it has a undefined cell {}'.format(
module_name, cell_data['type'])
return
property_map = {}
if 'attributes' in module_data:
property_map = module_data['attributes']
cell = Cell(module_name, property_map)
libraries[library].add_cell(cell)
net_duplicate_names = {}
def add_net(net_name, net_data, track_duplicates=False):
property_map = {}
if 'attributes' in net_data:
property_map.update(net_data['attributes'])
offset = net_data.get('offset', 0)
upto = net_data.get('upto', 0)
if is_bus(net_data['bits'], offset, upto):
for bit_index, bit in interp_yosys_net(net_data['bits'], offset,
upto):
name = '{}[{}]'.format(net_name, bit_index)
cell.add_net(name, property_map)
if bit == '0':
cell.connect_net_to_instance(
name, make_gnd_cell(cell, module_data), GND_PORT)
elif bit == '1':
cell.connect_net_to_instance(
name, make_vcc_cell(cell, module_data), VCC_PORT)
else:
assert isinstance(bit, int), bit
if bit in net_bits:
if track_duplicates:
net_duplicate_names[net_bits[bit]].append(name)
continue
assert bit not in net_bits, (module_name, bit,
net_bits.keys())
net_bits[bit] = name
net_duplicate_names[name] = []
else:
cell.add_net(net_name, property_map)
bit = net_data['bits'][0]
if bit == '0':
cell.connect_net_to_instance(net_name,
make_gnd_cell(cell, module_data),
GND_PORT)
elif bit == '1':
cell.connect_net_to_instance(net_name,
make_vcc_cell(cell, module_data),
VCC_PORT)
else:
assert isinstance(bit, int)
if bit in net_bits:
if track_duplicates:
net_duplicate_names[net_bits[bit]].append(net_name)
return
assert bit not in net_bits, (module_name, bit, net_bits.keys())
net_bits[bit] = net_name
net_duplicate_names[net_name] = []
net_bits = {}
for net_name, net_data in module_data['netnames'].items():
if net_name in module_data['ports']:
continue
if net_data.get('hide_name', 0):
continue
add_net(net_name, net_data, track_duplicates=False)
for net_name, net_data in module_data['netnames'].items():
if net_name not in module_data['ports']:
continue
add_net(net_name, net_data, track_duplicates=True)
for net_name, net_data in module_data['netnames'].items():
if net_data.get('hide_name', 0) != 1:
continue
add_net(net_name, net_data, track_duplicates=False)
vcc_cell = None
vcc_net = None
gnd_cell = None
gnd_net = None
def get_net(bit):
if bit == '0':
nonlocal gnd_cell
nonlocal gnd_net
if gnd_cell is None:
gnd_cell = make_gnd_cell(cell, module_data)
net_names = set(cell.nets.keys()) | set(
module_data['netnames'].keys())
gnd_net = create_unique_name(net_names, '$__gnd_net')
cell.add_net(gnd_net)
cell.connect_net_to_instance(gnd_net, gnd_cell, GND_PORT)
return gnd_net
elif bit == '1':
nonlocal vcc_cell
nonlocal vcc_net
if vcc_cell is None:
vcc_cell = make_vcc_cell(cell, module_data)
net_names = set(cell.nets.keys()) | set(
module_data['netnames'].keys())
vcc_net = create_unique_name(net_names, '$__vcc_net')
cell.add_net(vcc_net)
cell.connect_net_to_instance(vcc_net, vcc_cell, VCC_PORT)
return vcc_net
else:
assert isinstance(bit, int)
return net_bits[bit]
for port_name, port_data in module_data['ports'].items():
if port_data['direction'] == 'input':
direction = Direction.Input
elif port_data['direction'] == 'output':
direction = Direction.Output
else:
assert port_data['direction'] == 'inout'
direction = Direction.Inout
property_map = {}
if 'attributes' in port_data:
property_map = port_data['attributes']
offset = net_data.get('offset', 0)
upto = net_data.get('upto', False)
if is_bus(port_data['bits'], offset, upto):
start = offset
end = start + len(port_data['bits']) - 1
if upto:
start, end = end, start
cell.add_bus_port(
name=port_name,
direction=direction,
start=start,
end=end,
property_map=property_map)
for bit_index, bit in interp_yosys_net(port_data['bits'], offset,
upto):
cell.connect_net_to_cell_port(
get_net(bit), port_name, bit_index)
else:
cell.add_port(
name=port_name, direction=direction, property_map=property_map)
cell.connect_net_to_cell_port(
get_net(port_data['bits'][0]), port_name)
for cell_name, cell_data in module_data['cells'].items():
property_map = {}
if 'attributes' in cell_data:
property_map.update(cell_data['attributes'])
if 'parameters' in cell_data:
property_map.update(cell_data['parameters'])
cell.add_cell_instance(
name=cell_name,
cell_name=cell_data['type'],
property_map=property_map)
cell_type = modules[cell_data['type']]
for port_name, bits in cell_data['connections'].items():
port = cell_type['ports'][port_name]
offset = port.get('offset', 0)
upto = port.get('upto', False)
if is_bus(bits, offset, upto):
for bit_index, bit in interp_yosys_net(bits, offset, upto):
cell.connect_net_to_instance(
get_net(bit), cell_name, port_name, bit_index)
else:
cell.connect_net_to_instance(
get_net(bits[0]), cell_name, port_name)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--schema_dir', required=True)
parser.add_argument('--device', required=True)
parser.add_argument('--top', required=True)
parser.add_argument('--verbose', action='store_true')
parser.add_argument(
'--library',
default='work',
help='Library to put non-primitive elements')
parser.add_argument('yosys_json')
parser.add_argument('netlist')
args = parser.parse_args()
with open(args.yosys_json) as f:
yosys_json = json.load(f)
assert 'modules' in yosys_json, yosys_json.keys()
if args.top not in yosys_json['modules']:
raise RuntimeError(
'Could not find top module in yosys modules: {}'.format(', '.join(
yosys_json['modules'].keys())))
interchange = Interchange(args.schema_dir)
with open(args.device, 'rb') as f:
device = interchange.read_device_resources(f)
primitives = device.get_primitive_library()
primitive_cells = primitives.get_master_cell_list()
primitive_lib = {}
for lib_name, lib in primitives.libraries.items():
for cell in lib.cells.values():
primitive_lib[cell.name] = lib_name
name = args.top
property_map = {}
top_module = yosys_json['modules'][args.top]
if 'attributes' in top_module:
property_map.update(top_module['attributes'])
top_instance_name = args.top
top_instance = CellInstance(
property_map=property_map, view='netlist', cell_name=args.top)
libraries = {
args.library: Library(args.library),
}
module_errors = {}
for module_name, module_data in yosys_json['modules'].items():
if module_name in primitive_cells:
if args.verbose:
print('Skipping {} because it is a library cell'.format(
module_name))
continue
convert_cell(module_name, module_data, args.library, libraries,
yosys_json['modules'], args.verbose, module_errors)
netlist = LogicalNetlist(
name=name,
property_map=property_map,
top_instance_name=top_instance_name,
top_instance=top_instance,
libraries=libraries)
required_cells = set()
for lib_name, lib in netlist.libraries.items():
for cell in lib.cells.values():
for cell_instance in cell.cell_instances.values():
required_cells.add(cell_instance.cell_name)
required_cells -= set(netlist.get_master_cell_list().keys())
for required_cell in sorted(required_cells):
if required_cell not in primitive_cells:
if required_cell in module_errors:
raise RuntimeError(module_errors[required_cell])
else:
raise RuntimeError(
'Failed to find cell type {}'.format(required_cell))
lib_name = primitive_lib[required_cell]
if lib_name not in libraries:
libraries[lib_name] = Library(lib_name)
prim_cell = primitive_cells[required_cell]
netlist.libraries[lib_name].add_cell(prim_cell)
netlist_capnp = netlist.convert_to_capnp(interchange)
with open(args.netlist, 'wb') as f:
write_capnp_file(netlist_capnp, f)
if __name__ == "__main__":
main()