add redirection of __Cat__ to allow overrides for more advanced behaviour
[nmigen.git] / nmigen / back / rtlil.py
1 import io
2 from collections import OrderedDict
3 from contextlib import contextmanager
4
5 from .._utils import bits_for, flatten
6 from ..hdl import ast, ir, mem, xfrm
7
8
9 __all__ = ["convert", "convert_fragment"]
10
11
12 class ImplementationLimit(Exception):
13 pass
14
15
16 _escape_map = str.maketrans({
17 "\"": "\\\"",
18 "\\": "\\\\",
19 "\t": "\\t",
20 "\r": "\\r",
21 "\n": "\\n",
22 })
23
24
25 def _signed(value):
26 if isinstance(value, str):
27 return False
28 elif isinstance(value, int):
29 return value < 0
30 elif isinstance(value, ast.Const):
31 return value.signed
32 else:
33 assert False, "Invalid constant {!r}".format(value)
34
35
36 def _const(value):
37 if isinstance(value, str):
38 return "\"{}\"".format(value.translate(_escape_map))
39 elif isinstance(value, int):
40 if value in range(0, 2**31-1):
41 return "{:d}".format(value)
42 else:
43 # This code path is only used for Instances, where Verilog-like behavior is desirable.
44 # Verilog ensures that integers with unspecified width are 32 bits wide or more.
45 width = max(32, bits_for(value))
46 return _const(ast.Const(value, width))
47 elif isinstance(value, ast.Const):
48 value_twos_compl = value.value & ((1 << value.width) - 1)
49 return "{}'{:0{}b}".format(value.width, value_twos_compl, value.width)
50 else:
51 assert False, "Invalid constant {!r}".format(value)
52
53
54 class _Namer:
55 def __init__(self):
56 super().__init__()
57 self._anon = 0
58 self._index = 0
59 self._names = set()
60
61 def anonymous(self):
62 name = "U$${}".format(self._anon)
63 assert name not in self._names
64 self._anon += 1
65 return name
66
67 def _make_name(self, name, local):
68 if name is None:
69 self._index += 1
70 name = "${}".format(self._index)
71 elif not local and name[0] not in "\\$":
72 name = "\\{}".format(name)
73 while name in self._names:
74 self._index += 1
75 name = "{}${}".format(name, self._index)
76 self._names.add(name)
77 return name
78
79
80 class _BufferedBuilder:
81 def __init__(self):
82 super().__init__()
83 self._buffer = io.StringIO()
84
85 def __str__(self):
86 return self._buffer.getvalue()
87
88 def _append(self, fmt, *args, **kwargs):
89 self._buffer.write(fmt.format(*args, **kwargs))
90
91
92 class _ProxiedBuilder:
93 def _append(self, *args, **kwargs):
94 self.rtlil._append(*args, **kwargs)
95
96
97 class _AttrBuilder:
98 def _attribute(self, name, value, *, indent=0):
99 self._append("{}attribute \\{} {}\n",
100 " " * indent, name, _const(value))
101
102 def _attributes(self, attrs, *, src=None, **kwargs):
103 for name, value in attrs.items():
104 self._attribute(name, value, **kwargs)
105 if src:
106 self._attribute("src", src, **kwargs)
107
108
109 class _Builder(_Namer, _BufferedBuilder):
110 def module(self, name=None, attrs={}):
111 name = self._make_name(name, local=False)
112 return _ModuleBuilder(self, name, attrs)
113
114
115 class _ModuleBuilder(_Namer, _BufferedBuilder, _AttrBuilder):
116 def __init__(self, rtlil, name, attrs):
117 super().__init__()
118 self.rtlil = rtlil
119 self.name = name
120 self.attrs = {"generator": "nMigen"}
121 self.attrs.update(attrs)
122
123 def __enter__(self):
124 self._attributes(self.attrs)
125 self._append("module {}\n", self.name)
126 return self
127
128 def __exit__(self, *args):
129 self._append("end\n")
130 self.rtlil._buffer.write(str(self))
131
132 def wire(self, width, port_id=None, port_kind=None, name=None, attrs={}, src=""):
133 # Very large wires are unlikely to work. Verilog 1364-2005 requires the limit on vectors
134 # to be at least 2**16 bits, and Yosys 0.9 cannot read RTLIL with wires larger than 2**32
135 # bits. In practice, wires larger than 2**16 bits, although accepted, cause performance
136 # problems without an immediately visible cause, so conservatively limit wire size.
137 if width > 2 ** 16:
138 raise ImplementationLimit("Wire created at {} is {} bits wide, which is unlikely to "
139 "synthesize correctly"
140 .format(src or "unknown location", width))
141
142 self._attributes(attrs, src=src, indent=1)
143 name = self._make_name(name, local=False)
144 if port_id is None:
145 self._append(" wire width {} {}\n", width, name)
146 else:
147 assert port_kind in ("input", "output", "inout")
148 self._append(" wire width {} {} {} {}\n", width, port_kind, port_id, name)
149 return name
150
151 def connect(self, lhs, rhs):
152 self._append(" connect {} {}\n", lhs, rhs)
153
154 def memory(self, width, size, name=None, attrs={}, src=""):
155 self._attributes(attrs, src=src, indent=1)
156 name = self._make_name(name, local=False)
157 self._append(" memory width {} size {} {}\n", width, size, name)
158 return name
159
160 def cell(self, kind, name=None, params={}, ports={}, attrs={}, src=""):
161 self._attributes(attrs, src=src, indent=1)
162 name = self._make_name(name, local=False)
163 self._append(" cell {} {}\n", kind, name)
164 for param, value in params.items():
165 if isinstance(value, float):
166 self._append(" parameter real \\{} \"{!r}\"\n",
167 param, value)
168 elif _signed(value):
169 self._append(" parameter signed \\{} {}\n",
170 param, _const(value))
171 else:
172 self._append(" parameter \\{} {}\n",
173 param, _const(value))
174 for port, wire in ports.items():
175 self._append(" connect {} {}\n", port, wire)
176 self._append(" end\n")
177 return name
178
179 def process(self, name=None, attrs={}, src=""):
180 name = self._make_name(name, local=True)
181 return _ProcessBuilder(self, name, attrs, src)
182
183
184 class _ProcessBuilder(_BufferedBuilder, _AttrBuilder):
185 def __init__(self, rtlil, name, attrs, src):
186 super().__init__()
187 self.rtlil = rtlil
188 self.name = name
189 self.attrs = {}
190 self.src = src
191
192 def __enter__(self):
193 self._attributes(self.attrs, src=self.src, indent=1)
194 self._append(" process {}\n", self.name)
195 return self
196
197 def __exit__(self, *args):
198 self._append(" end\n")
199 self.rtlil._buffer.write(str(self))
200
201 def case(self):
202 return _CaseBuilder(self, indent=2)
203
204 def sync(self, kind, cond=None):
205 return _SyncBuilder(self, kind, cond)
206
207
208 class _CaseBuilder(_ProxiedBuilder):
209 def __init__(self, rtlil, indent):
210 self.rtlil = rtlil
211 self.indent = indent
212
213 def __enter__(self):
214 return self
215
216 def __exit__(self, *args):
217 pass
218
219 def assign(self, lhs, rhs):
220 self._append("{}assign {} {}\n", " " * self.indent, lhs, rhs)
221
222 def switch(self, cond, attrs={}, src=""):
223 return _SwitchBuilder(self.rtlil, cond, attrs, src, self.indent)
224
225
226 class _SwitchBuilder(_ProxiedBuilder, _AttrBuilder):
227 def __init__(self, rtlil, cond, attrs, src, indent):
228 self.rtlil = rtlil
229 self.cond = cond
230 self.attrs = attrs
231 self.src = src
232 self.indent = indent
233
234 def __enter__(self):
235 self._attributes(self.attrs, src=self.src, indent=self.indent)
236 self._append("{}switch {}\n", " " * self.indent, self.cond)
237 return self
238
239 def __exit__(self, *args):
240 self._append("{}end\n", " " * self.indent)
241
242 def case(self, *values, attrs={}, src=""):
243 self._attributes(attrs, src=src, indent=self.indent + 1)
244 if values == ():
245 self._append("{}case\n", " " * (self.indent + 1))
246 else:
247 self._append("{}case {}\n", " " * (self.indent + 1),
248 ", ".join("{}'{}".format(len(value), value) for value in values))
249 return _CaseBuilder(self.rtlil, self.indent + 2)
250
251
252 class _SyncBuilder(_ProxiedBuilder):
253 def __init__(self, rtlil, kind, cond):
254 self.rtlil = rtlil
255 self.kind = kind
256 self.cond = cond
257
258 def __enter__(self):
259 if self.cond is None:
260 self._append(" sync {}\n", self.kind)
261 else:
262 self._append(" sync {} {}\n", self.kind, self.cond)
263 return self
264
265 def __exit__(self, *args):
266 pass
267
268 def update(self, lhs, rhs):
269 self._append(" update {} {}\n", lhs, rhs)
270
271
272 def _src(src_loc):
273 if src_loc is None:
274 return None
275 file, line = src_loc
276 return "{}:{}".format(file, line)
277
278
279 class _LegalizeValue(Exception):
280 def __init__(self, value, branches, src_loc):
281 self.value = value
282 self.branches = list(branches)
283 self.src_loc = src_loc
284
285
286 class _ValueCompilerState:
287 def __init__(self, rtlil):
288 self.rtlil = rtlil
289 self.wires = ast.SignalDict()
290 self.driven = ast.SignalDict()
291 self.ports = ast.SignalDict()
292 self.anys = ast.ValueDict()
293
294 self.expansions = ast.ValueDict()
295
296 def add_driven(self, signal, sync):
297 self.driven[signal] = sync
298
299 def add_port(self, signal, kind):
300 assert kind in ("i", "o", "io")
301 if kind == "i":
302 kind = "input"
303 elif kind == "o":
304 kind = "output"
305 elif kind == "io":
306 kind = "inout"
307 self.ports[signal] = (len(self.ports), kind)
308
309 def resolve(self, signal, prefix=None):
310 if len(signal) == 0:
311 return "{ }", "{ }"
312
313 if signal in self.wires:
314 return self.wires[signal]
315
316 if signal in self.ports:
317 port_id, port_kind = self.ports[signal]
318 else:
319 port_id = port_kind = None
320 if prefix is not None:
321 wire_name = "{}_{}".format(prefix, signal.name)
322 else:
323 wire_name = signal.name
324
325 attrs = dict(signal.attrs)
326 if signal._enum_class is not None:
327 attrs["enum_base_type"] = signal._enum_class.__name__
328 for value in signal._enum_class:
329 attrs["enum_value_{:0{}b}".format(value.value, signal.width)] = value.name
330
331 wire_curr = self.rtlil.wire(width=signal.width, name=wire_name,
332 port_id=port_id, port_kind=port_kind,
333 attrs=attrs, src=_src(signal.src_loc))
334 if signal in self.driven and self.driven[signal]:
335 wire_next = self.rtlil.wire(width=signal.width, name=wire_curr + "$next",
336 src=_src(signal.src_loc))
337 else:
338 wire_next = None
339 self.wires[signal] = (wire_curr, wire_next)
340
341 return wire_curr, wire_next
342
343 def resolve_curr(self, signal, prefix=None):
344 wire_curr, wire_next = self.resolve(signal, prefix)
345 return wire_curr
346
347 def expand(self, value):
348 if not self.expansions:
349 return value
350 return self.expansions.get(value, value)
351
352 @contextmanager
353 def expand_to(self, value, expansion):
354 try:
355 assert value not in self.expansions
356 self.expansions[value] = expansion
357 yield
358 finally:
359 del self.expansions[value]
360
361
362 class _ValueCompiler(xfrm.ValueVisitor):
363 def __init__(self, state):
364 self.s = state
365
366 def on_unknown(self, value):
367 if value is None:
368 return None
369 else:
370 super().on_unknown(value)
371
372 def on_ClockSignal(self, value):
373 raise NotImplementedError # :nocov:
374
375 def on_ResetSignal(self, value):
376 raise NotImplementedError # :nocov:
377
378 def on_Sample(self, value):
379 raise NotImplementedError # :nocov:
380
381 def on_Initial(self, value):
382 raise NotImplementedError # :nocov:
383
384 def on_Cat(self, value):
385 return "{{ {} }}".format(" ".join(reversed([self(o) for o in value.parts])))
386
387 def _prepare_value_for_Slice(self, value):
388 raise NotImplementedError # :nocov:
389
390 def on_Slice(self, value):
391 if value.start == 0 and value.stop == len(value.value):
392 return self(value.value)
393
394 if isinstance(value.value, ast.UserValue):
395 sigspec = self._prepare_value_for_Slice(value.value._lazy_lower())
396 else:
397 sigspec = self._prepare_value_for_Slice(value.value)
398
399 if value.start == value.stop:
400 return "{}"
401 elif value.start + 1 == value.stop:
402 return "{} [{}]".format(sigspec, value.start)
403 else:
404 return "{} [{}:{}]".format(sigspec, value.stop - 1, value.start)
405
406 def on_ArrayProxy(self, value):
407 index = self.s.expand(value.index)
408 if isinstance(index, ast.Const):
409 if index.value < len(value.elems):
410 elem = value.elems[index.value]
411 else:
412 elem = value.elems[-1]
413 return self.match_shape(elem, *value.shape())
414 else:
415 max_index = 1 << len(value.index)
416 max_elem = len(value.elems)
417 raise _LegalizeValue(value.index, range(min(max_index, max_elem)), value.src_loc)
418
419
420 class _RHSValueCompiler(_ValueCompiler):
421 operator_map = {
422 (1, "~"): "$not",
423 (1, "-"): "$neg",
424 (1, "b"): "$reduce_bool",
425 (1, "r|"): "$reduce_or",
426 (1, "r&"): "$reduce_and",
427 (1, "r^"): "$reduce_xor",
428 (2, "+"): "$add",
429 (2, "-"): "$sub",
430 (2, "*"): "$mul",
431 (2, "//"): "$div",
432 (2, "%"): "$mod",
433 (2, "**"): "$pow",
434 (2, "<<"): "$sshl",
435 (2, ">>"): "$sshr",
436 (2, "&"): "$and",
437 (2, "^"): "$xor",
438 (2, "|"): "$or",
439 (2, "=="): "$eq",
440 (2, "!="): "$ne",
441 (2, "<"): "$lt",
442 (2, "<="): "$le",
443 (2, ">"): "$gt",
444 (2, ">="): "$ge",
445 (3, "m"): "$mux",
446 }
447
448 def on_value(self, value):
449 return super().on_value(self.s.expand(value))
450
451 def on_Const(self, value):
452 return _const(value)
453
454 def on_AnyConst(self, value):
455 if value in self.s.anys:
456 return self.s.anys[value]
457
458 res_bits, res_sign = value.shape()
459 res = self.s.rtlil.wire(width=res_bits, src=_src(value.src_loc))
460 self.s.rtlil.cell("$anyconst", ports={
461 "\\Y": res,
462 }, params={
463 "WIDTH": res_bits,
464 }, src=_src(value.src_loc))
465 self.s.anys[value] = res
466 return res
467
468 def on_AnySeq(self, value):
469 if value in self.s.anys:
470 return self.s.anys[value]
471
472 res_bits, res_sign = value.shape()
473 res = self.s.rtlil.wire(width=res_bits, src=_src(value.src_loc))
474 self.s.rtlil.cell("$anyseq", ports={
475 "\\Y": res,
476 }, params={
477 "WIDTH": res_bits,
478 }, src=_src(value.src_loc))
479 self.s.anys[value] = res
480 return res
481
482 def on_Signal(self, value):
483 wire_curr, wire_next = self.s.resolve(value)
484 return wire_curr
485
486 def on_Operator_unary(self, value):
487 arg, = value.operands
488 if value.operator in ("u", "s"):
489 # These operators don't change the bit pattern, only its interpretation.
490 return self(arg)
491
492 arg_bits, arg_sign = arg.shape()
493 res_bits, res_sign = value.shape()
494 res = self.s.rtlil.wire(width=res_bits, src=_src(value.src_loc))
495 self.s.rtlil.cell(self.operator_map[(1, value.operator)], ports={
496 "\\A": self(arg),
497 "\\Y": res,
498 }, params={
499 "A_SIGNED": arg_sign,
500 "A_WIDTH": arg_bits,
501 "Y_WIDTH": res_bits,
502 }, src=_src(value.src_loc))
503 return res
504
505 def match_shape(self, value, new_bits, new_sign):
506 if isinstance(value, ast.Const):
507 return self(ast.Const(value.value, ast.Shape(new_bits, new_sign)))
508
509 value_bits, value_sign = value.shape()
510 if new_bits <= value_bits:
511 return self(ast.Slice(value, 0, new_bits))
512
513 res = self.s.rtlil.wire(width=new_bits, src=_src(value.src_loc))
514 self.s.rtlil.cell("$pos", ports={
515 "\\A": self(value),
516 "\\Y": res,
517 }, params={
518 "A_SIGNED": value_sign,
519 "A_WIDTH": value_bits,
520 "Y_WIDTH": new_bits,
521 }, src=_src(value.src_loc))
522 return res
523
524 def on_Operator_binary(self, value):
525 lhs, rhs = value.operands
526 lhs_bits, lhs_sign = lhs.shape()
527 rhs_bits, rhs_sign = rhs.shape()
528 if lhs_sign == rhs_sign or value.operator in ("<<", ">>", "**"):
529 lhs_wire = self(lhs)
530 rhs_wire = self(rhs)
531 else:
532 lhs_sign = rhs_sign = True
533 lhs_bits = rhs_bits = max(lhs_bits, rhs_bits)
534 lhs_wire = self.match_shape(lhs, lhs_bits, lhs_sign)
535 rhs_wire = self.match_shape(rhs, rhs_bits, rhs_sign)
536 res_bits, res_sign = value.shape()
537 res = self.s.rtlil.wire(width=res_bits, src=_src(value.src_loc))
538 self.s.rtlil.cell(self.operator_map[(2, value.operator)], ports={
539 "\\A": lhs_wire,
540 "\\B": rhs_wire,
541 "\\Y": res,
542 }, params={
543 "A_SIGNED": lhs_sign,
544 "A_WIDTH": lhs_bits,
545 "B_SIGNED": rhs_sign,
546 "B_WIDTH": rhs_bits,
547 "Y_WIDTH": res_bits,
548 }, src=_src(value.src_loc))
549 if value.operator in ("//", "%"):
550 # RTLIL leaves division by zero undefined, but we require it to return zero.
551 divmod_res = res
552 res = self.s.rtlil.wire(width=res_bits, src=_src(value.src_loc))
553 self.s.rtlil.cell("$mux", ports={
554 "\\A": divmod_res,
555 "\\B": self(ast.Const(0, ast.Shape(res_bits, res_sign))),
556 "\\S": self(rhs == 0),
557 "\\Y": res,
558 }, params={
559 "WIDTH": res_bits
560 }, src=_src(value.src_loc))
561 return res
562
563 def on_Operator_mux(self, value):
564 sel, val1, val0 = value.operands
565 val1_bits, val1_sign = val1.shape()
566 val0_bits, val0_sign = val0.shape()
567 res_bits, res_sign = value.shape()
568 val1_bits = val0_bits = res_bits = max(val1_bits, val0_bits, res_bits)
569 val1_wire = self.match_shape(val1, val1_bits, val1_sign)
570 val0_wire = self.match_shape(val0, val0_bits, val0_sign)
571 res = self.s.rtlil.wire(width=res_bits, src=_src(value.src_loc))
572 self.s.rtlil.cell("$mux", ports={
573 "\\A": val0_wire,
574 "\\B": val1_wire,
575 "\\S": self(sel),
576 "\\Y": res,
577 }, params={
578 "WIDTH": res_bits
579 }, src=_src(value.src_loc))
580 return res
581
582 def on_Operator(self, value):
583 if len(value.operands) == 1:
584 return self.on_Operator_unary(value)
585 elif len(value.operands) == 2:
586 return self.on_Operator_binary(value)
587 elif len(value.operands) == 3:
588 assert value.operator == "m"
589 return self.on_Operator_mux(value)
590 else:
591 raise TypeError # :nocov:
592
593 def _prepare_value_for_Slice(self, value):
594 if isinstance(value, (ast.Signal, ast.Slice, ast._InternalCat)):
595 sigspec = self(value)
596 else:
597 sigspec = self.s.rtlil.wire(len(value), src=_src(value.src_loc))
598 self.s.rtlil.connect(sigspec, self(value))
599 return sigspec
600
601 def on_Part(self, value):
602 lhs, rhs = value.value, value.offset
603 if value.stride != 1:
604 rhs *= value.stride
605 lhs_bits, lhs_sign = lhs.shape()
606 rhs_bits, rhs_sign = rhs.shape()
607 res_bits, res_sign = value.shape()
608 res = self.s.rtlil.wire(width=res_bits, src=_src(value.src_loc))
609 # Note: Verilog's x[o+:w] construct produces a $shiftx cell, not a $shift cell.
610 # However, nMigen's semantics defines the out-of-range bits to be zero, so it is correct
611 # to use a $shift cell here instead, even though it produces less idiomatic Verilog.
612 self.s.rtlil.cell("$shift", ports={
613 "\\A": self(lhs),
614 "\\B": self(rhs),
615 "\\Y": res,
616 }, params={
617 "A_SIGNED": lhs_sign,
618 "A_WIDTH": lhs_bits,
619 "B_SIGNED": rhs_sign,
620 "B_WIDTH": rhs_bits,
621 "Y_WIDTH": res_bits,
622 }, src=_src(value.src_loc))
623 return res
624
625 def on_Repl(self, value):
626 return "{{ {} }}".format(" ".join(self(value.value) for _ in range(value.count)))
627
628
629 class _LHSValueCompiler(_ValueCompiler):
630 def on_Const(self, value):
631 raise TypeError # :nocov:
632
633 def on_AnyConst(self, value):
634 raise TypeError # :nocov:
635
636 def on_AnySeq(self, value):
637 raise TypeError # :nocov:
638
639 def on_Operator(self, value):
640 raise TypeError # :nocov:
641
642 def match_shape(self, value, new_bits, new_sign):
643 value_bits, value_sign = value.shape()
644 if new_bits == value_bits:
645 return self(value)
646 elif new_bits < value_bits:
647 return self(ast.Slice(value, 0, new_bits))
648 else: # new_bits > value_bits
649 dummy_bits = new_bits - value_bits
650 dummy_wire = self.s.rtlil.wire(dummy_bits)
651 return "{{ {} {} }}".format(dummy_wire, self(value))
652
653 def on_Signal(self, value):
654 if value not in self.s.driven:
655 raise ValueError("No LHS wire for non-driven signal {}".format(repr(value)))
656 wire_curr, wire_next = self.s.resolve(value)
657 return wire_next or wire_curr
658
659 def _prepare_value_for_Slice(self, value):
660 assert isinstance(value, (ast.Signal, ast.Slice, ast._InternalCat))
661 return self(value)
662
663 def on_Part(self, value):
664 offset = self.s.expand(value.offset)
665 if isinstance(offset, ast.Const):
666 start = offset.value * value.stride
667 stop = start + value.width
668 slice = self(ast.Slice(value.value, start, min(len(value.value), stop)))
669 if len(value.value) >= stop:
670 return slice
671 else:
672 dummy_wire = self.s.rtlil.wire(stop - len(value.value))
673 return "{{ {} {} }}".format(dummy_wire, slice)
674 else:
675 # Only so many possible parts. The amount of branches is exponential; if value.offset
676 # is large (e.g. 32-bit wide), trying to naively legalize it is likely to exhaust
677 # system resources.
678 max_branches = len(value.value) // value.stride + 1
679 raise _LegalizeValue(value.offset,
680 range(1 << len(value.offset))[:max_branches],
681 value.src_loc)
682
683 def on_Repl(self, value):
684 raise TypeError # :nocov:
685
686
687 class _StatementCompiler(xfrm.StatementVisitor):
688 def __init__(self, state, rhs_compiler, lhs_compiler):
689 self.state = state
690 self.rhs_compiler = rhs_compiler
691 self.lhs_compiler = lhs_compiler
692
693 self._case = None
694 self._test_cache = {}
695 self._has_rhs = False
696 self._wrap_assign = False
697
698 @contextmanager
699 def case(self, switch, values, attrs={}, src=""):
700 try:
701 old_case = self._case
702 with switch.case(*values, attrs=attrs, src=src) as self._case:
703 yield
704 finally:
705 self._case = old_case
706
707 def _check_rhs(self, value):
708 if self._has_rhs or next(iter(value._rhs_signals()), None) is not None:
709 self._has_rhs = True
710
711 def on_Assign(self, stmt):
712 self._check_rhs(stmt.rhs)
713
714 lhs_bits, lhs_sign = stmt.lhs.shape()
715 rhs_bits, rhs_sign = stmt.rhs.shape()
716 if lhs_bits == rhs_bits:
717 rhs_sigspec = self.rhs_compiler(stmt.rhs)
718 else:
719 # In RTLIL, LHS and RHS of assignment must have exactly same width.
720 rhs_sigspec = self.rhs_compiler.match_shape(
721 stmt.rhs, lhs_bits, lhs_sign)
722 if self._wrap_assign:
723 # In RTLIL, all assigns are logically sequenced before all switches, even if they are
724 # interleaved in the source. In nMigen, the source ordering is used. To handle this
725 # mismatch, we wrap all assigns following a switch in a dummy switch.
726 with self._case.switch("{ }") as wrap_switch:
727 with wrap_switch.case() as wrap_case:
728 wrap_case.assign(self.lhs_compiler(stmt.lhs), rhs_sigspec)
729 else:
730 self._case.assign(self.lhs_compiler(stmt.lhs), rhs_sigspec)
731
732 def on_property(self, stmt):
733 self(stmt._check.eq(stmt.test))
734 self(stmt._en.eq(1))
735
736 en_wire = self.rhs_compiler(stmt._en)
737 check_wire = self.rhs_compiler(stmt._check)
738 self.state.rtlil.cell("$" + stmt._kind, ports={
739 "\\A": check_wire,
740 "\\EN": en_wire,
741 }, src=_src(stmt.src_loc))
742
743 on_Assert = on_property
744 on_Assume = on_property
745 on_Cover = on_property
746
747 def on_Switch(self, stmt):
748 self._check_rhs(stmt.test)
749
750 if not self.state.expansions:
751 # We repeatedly translate the same switches over and over (see the LHSGroupAnalyzer
752 # related code below), and translating the switch test only once helps readability.
753 if stmt not in self._test_cache:
754 self._test_cache[stmt] = self.rhs_compiler(stmt.test)
755 test_sigspec = self._test_cache[stmt]
756 else:
757 # However, if the switch test contains an illegal value, then it may not be cached
758 # (since the illegal value will be repeatedly replaced with different constants), so
759 # don't cache anything in that case.
760 test_sigspec = self.rhs_compiler(stmt.test)
761
762 with self._case.switch(test_sigspec, src=_src(stmt.src_loc)) as switch:
763 for values, stmts in stmt.cases.items():
764 case_attrs = {}
765 if values in stmt.case_src_locs:
766 case_attrs["src"] = _src(stmt.case_src_locs[values])
767 if isinstance(stmt.test, ast.Signal) and stmt.test.decoder:
768 decoded_values = []
769 for value in values:
770 if "-" in value:
771 decoded_values.append("<multiple>")
772 else:
773 decoded_values.append(stmt.test.decoder(int(value, 2)))
774 case_attrs["nmigen.decoding"] = "|".join(decoded_values)
775 with self.case(switch, values, attrs=case_attrs):
776 self._wrap_assign = False
777 self.on_statements(stmts)
778 self._wrap_assign = True
779
780 def on_statement(self, stmt):
781 try:
782 super().on_statement(stmt)
783 except _LegalizeValue as legalize:
784 with self._case.switch(self.rhs_compiler(legalize.value),
785 src=_src(legalize.src_loc)) as switch:
786 shape = legalize.value.shape()
787 tests = ["{:0{}b}".format(v, shape.width) for v in legalize.branches]
788 if tests:
789 tests[-1] = "-" * shape.width
790 for branch, test in zip(legalize.branches, tests):
791 with self.case(switch, (test,)):
792 self._wrap_assign = False
793 branch_value = ast.Const(branch, shape)
794 with self.state.expand_to(legalize.value, branch_value):
795 self.on_statement(stmt)
796 self._wrap_assign = True
797
798 def on_statements(self, stmts):
799 for stmt in stmts:
800 self.on_statement(stmt)
801
802
803 def _convert_fragment(builder, fragment, name_map, hierarchy):
804 if isinstance(fragment, ir.Instance):
805 port_map = OrderedDict()
806 for port_name, (value, dir) in fragment.named_ports.items():
807 port_map["\\{}".format(port_name)] = value
808
809 if fragment.type[0] == "$":
810 return fragment.type, port_map
811 else:
812 return "\\{}".format(fragment.type), port_map
813
814 module_name = hierarchy[-1] or "anonymous"
815 module_attrs = OrderedDict()
816 if len(hierarchy) == 1:
817 module_attrs["top"] = 1
818 module_attrs["nmigen.hierarchy"] = ".".join(name or "anonymous" for name in hierarchy)
819
820 with builder.module(module_name, attrs=module_attrs) as module:
821 compiler_state = _ValueCompilerState(module)
822 rhs_compiler = _RHSValueCompiler(compiler_state)
823 lhs_compiler = _LHSValueCompiler(compiler_state)
824 stmt_compiler = _StatementCompiler(compiler_state, rhs_compiler, lhs_compiler)
825
826 verilog_trigger = None
827 verilog_trigger_sync_emitted = False
828
829 # If the fragment is completely empty, add a dummy wire to it, or Yosys will interpret
830 # it as a black box by default (when read as Verilog).
831 if not fragment.ports and not fragment.statements and not fragment.subfragments:
832 module.wire(1, name="$empty_module_filler")
833
834 # Register all signals driven in the current fragment. This must be done first, as it
835 # affects further codegen; e.g. whether \sig$next signals will be generated and used.
836 for domain, signal in fragment.iter_drivers():
837 compiler_state.add_driven(signal, sync=domain is not None)
838
839 # Transform all signals used as ports in the current fragment eagerly and outside of
840 # any hierarchy, to make sure they get sensible (non-prefixed) names.
841 for signal in fragment.ports:
842 compiler_state.add_port(signal, fragment.ports[signal])
843 compiler_state.resolve_curr(signal)
844
845 # Transform all clocks clocks and resets eagerly and outside of any hierarchy, to make
846 # sure they get sensible (non-prefixed) names. This does not affect semantics.
847 for domain, _ in fragment.iter_sync():
848 cd = fragment.domains[domain]
849 compiler_state.resolve_curr(cd.clk)
850 if cd.rst is not None:
851 compiler_state.resolve_curr(cd.rst)
852
853 # Transform all subfragments to their respective cells. Transforming signals connected
854 # to their ports into wires eagerly makes sure they get sensible (prefixed with submodule
855 # name) names.
856 memories = OrderedDict()
857 for subfragment, sub_name in fragment.subfragments:
858 if sub_name is None:
859 sub_name = module.anonymous()
860
861 sub_params = OrderedDict()
862 if hasattr(subfragment, "parameters"):
863 for param_name, param_value in subfragment.parameters.items():
864 if isinstance(param_value, mem.Memory):
865 memory = param_value
866 if memory not in memories:
867 memories[memory] = module.memory(width=memory.width, size=memory.depth,
868 name=memory.name, attrs=memory.attrs)
869 addr_bits = bits_for(memory.depth)
870 data_parts = []
871 data_mask = (1 << memory.width) - 1
872 for addr in range(memory.depth):
873 if addr < len(memory.init):
874 data = memory.init[addr] & data_mask
875 else:
876 data = 0
877 data_parts.append("{:0{}b}".format(data, memory.width))
878 module.cell("$meminit", ports={
879 "\\ADDR": rhs_compiler(ast.Const(0, addr_bits)),
880 "\\DATA": "{}'".format(memory.width * memory.depth) +
881 "".join(reversed(data_parts)),
882 }, params={
883 "MEMID": memories[memory],
884 "ABITS": addr_bits,
885 "WIDTH": memory.width,
886 "WORDS": memory.depth,
887 "PRIORITY": 0,
888 })
889
890 param_value = memories[memory]
891
892 sub_params[param_name] = param_value
893
894 sub_type, sub_port_map = \
895 _convert_fragment(builder, subfragment, name_map,
896 hierarchy=hierarchy + (sub_name,))
897
898 sub_ports = OrderedDict()
899 for port, value in sub_port_map.items():
900 if not isinstance(subfragment, ir.Instance):
901 for signal in value._rhs_signals():
902 compiler_state.resolve_curr(signal, prefix=sub_name)
903 if len(value) > 0:
904 sub_ports[port] = rhs_compiler(value)
905
906 module.cell(sub_type, name=sub_name, ports=sub_ports, params=sub_params,
907 attrs=subfragment.attrs)
908
909 # If we emit all of our combinatorial logic into a single RTLIL process, Verilog
910 # simulators will break horribly, because Yosys write_verilog transforms RTLIL processes
911 # into always @* blocks with blocking assignment, and that does not create delta cycles.
912 #
913 # Therefore, we translate the fragment as many times as there are independent groups
914 # of signals (a group is a transitive closure of signals that appear together on LHS),
915 # splitting them into many RTLIL (and thus Verilog) processes.
916 lhs_grouper = xfrm.LHSGroupAnalyzer()
917 lhs_grouper.on_statements(fragment.statements)
918
919 for group, group_signals in lhs_grouper.groups().items():
920 lhs_group_filter = xfrm.LHSGroupFilter(group_signals)
921 group_stmts = lhs_group_filter(fragment.statements)
922
923 with module.process(name="$group_{}".format(group)) as process:
924 with process.case() as case:
925 # For every signal in comb domain, assign \sig$next to the reset value.
926 # For every signal in sync domains, assign \sig$next to the current
927 # value (\sig).
928 for domain, signal in fragment.iter_drivers():
929 if signal not in group_signals:
930 continue
931 if domain is None:
932 prev_value = ast.Const(signal.reset, signal.width)
933 else:
934 prev_value = signal
935 case.assign(lhs_compiler(signal), rhs_compiler(prev_value))
936
937 # Convert statements into decision trees.
938 stmt_compiler._case = case
939 stmt_compiler._has_rhs = False
940 stmt_compiler._wrap_assign = False
941 stmt_compiler(group_stmts)
942
943 # Verilog `always @*` blocks will not run if `*` does not match anything, i.e.
944 # if the implicit sensitivity list is empty. We check this while translating,
945 # by looking for any signals on RHS. If there aren't any, we add some logic
946 # whose only purpose is to trigger Verilog simulators when it converts
947 # through RTLIL and to Verilog, by populating the sensitivity list.
948 #
949 # Unfortunately, while this workaround allows true (event-driven) Verilog
950 # simulators to work properly, and is universally ignored by synthesizers,
951 # Verilator rejects it.
952 #
953 # Yosys >=0.9+3468 emits a better workaround on its own, so this code can be
954 # removed completely once support for Yosys 0.9 is dropped.
955 if not stmt_compiler._has_rhs:
956 if verilog_trigger is None:
957 verilog_trigger = \
958 module.wire(1, name="$verilog_initial_trigger")
959 case.assign(verilog_trigger, verilog_trigger)
960
961 # For every signal in the sync domain, assign \sig's initial value (which will
962 # end up as the \init reg attribute) to the reset value.
963 with process.sync("init") as sync:
964 for domain, signal in fragment.iter_sync():
965 if signal not in group_signals:
966 continue
967 wire_curr, wire_next = compiler_state.resolve(signal)
968 sync.update(wire_curr, rhs_compiler(ast.Const(signal.reset, signal.width)))
969
970 # The Verilog simulator trigger needs to change at time 0, so if we haven't
971 # yet done that in some process, do it.
972 if verilog_trigger and not verilog_trigger_sync_emitted:
973 sync.update(verilog_trigger, "1'0")
974 verilog_trigger_sync_emitted = True
975
976 # For every signal in every sync domain, assign \sig to \sig$next. The sensitivity
977 # list, however, differs between domains: for domains with sync reset, it is
978 # `[pos|neg]edge clk`, for sync domains with async reset it is `[pos|neg]edge clk
979 # or posedge rst`.
980 for domain, signals in fragment.drivers.items():
981 if domain is None:
982 continue
983
984 signals = signals & group_signals
985 if not signals:
986 continue
987
988 cd = fragment.domains[domain]
989
990 triggers = []
991 triggers.append((cd.clk_edge + "edge", compiler_state.resolve_curr(cd.clk)))
992 if cd.async_reset:
993 triggers.append(("posedge", compiler_state.resolve_curr(cd.rst)))
994
995 for trigger in triggers:
996 with process.sync(*trigger) as sync:
997 for signal in signals:
998 wire_curr, wire_next = compiler_state.resolve(signal)
999 sync.update(wire_curr, wire_next)
1000
1001 # Any signals that are used but neither driven nor connected to an input port always
1002 # assume their reset values. We need to assign the reset value explicitly, since only
1003 # driven sync signals are handled by the logic above.
1004 #
1005 # Because this assignment is done at a late stage, a single Signal object can get assigned
1006 # many times, once in each module it is used. This is a deliberate decision; the possible
1007 # alternatives are to add ports for undriven signals (which requires choosing one module
1008 # to drive it to reset value arbitrarily) or to replace them with their reset value (which
1009 # removes valuable source location information).
1010 driven = ast.SignalSet()
1011 for domain, signals in fragment.iter_drivers():
1012 driven.update(flatten(signal._lhs_signals() for signal in signals))
1013 driven.update(fragment.iter_ports(dir="i"))
1014 driven.update(fragment.iter_ports(dir="io"))
1015 for subfragment, sub_name in fragment.subfragments:
1016 driven.update(subfragment.iter_ports(dir="o"))
1017 driven.update(subfragment.iter_ports(dir="io"))
1018
1019 for wire in compiler_state.wires:
1020 if wire in driven:
1021 continue
1022 wire_curr, _ = compiler_state.wires[wire]
1023 module.connect(wire_curr, rhs_compiler(ast.Const(wire.reset, wire.width)))
1024
1025 # Collect the names we've given to our ports in RTLIL, and correlate these with the signals
1026 # represented by these ports. If we are a submodule, this will be necessary to create a cell
1027 # for us in the parent module.
1028 port_map = OrderedDict()
1029 for signal in fragment.ports:
1030 port_map[compiler_state.resolve_curr(signal)] = signal
1031
1032 # Finally, collect tha names we've given to each wire in RTLIL, and provide these to
1033 # the caller, to allow manipulating them in the toolchain.
1034 for signal in compiler_state.wires:
1035 wire_name = compiler_state.resolve_curr(signal)
1036 if wire_name.startswith("\\"):
1037 wire_name = wire_name[1:]
1038 name_map[signal] = hierarchy + (wire_name,)
1039
1040 return module.name, port_map
1041
1042
1043 def convert_fragment(fragment, name="top"):
1044 assert isinstance(fragment, ir.Fragment)
1045 builder = _Builder()
1046 name_map = ast.SignalDict()
1047 _convert_fragment(builder, fragment, name_map, hierarchy=(name,))
1048 return str(builder), name_map
1049
1050
1051 def convert(elaboratable, name="top", platform=None, **kwargs):
1052 fragment = ir.Fragment.get(elaboratable, platform).prepare(**kwargs)
1053 il_text, name_map = convert_fragment(fragment, name)
1054 return il_text