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