3 from collections
import defaultdict
, OrderedDict
4 from contextlib
import contextmanager
6 from .._utils
import bits_for
, flatten
7 from ..hdl
import ast
, rec
, ir
, mem
, xfrm
10 __all__
= ["convert", "convert_fragment"]
13 class ImplementationLimit(Exception):
17 _escape_map
= str.maketrans({
27 if isinstance(value
, str):
29 elif isinstance(value
, int):
31 elif isinstance(value
, ast
.Const
):
34 assert False, "Invalid constant {!r}".format(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
)
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
)
52 assert False, "Invalid constant {!r}".format(value
)
63 name
= "U$${}".format(self
._anon
)
64 assert name
not in self
._names
68 def _make_name(self
, name
, local
):
71 name
= "${}".format(self
._index
)
72 elif not local
and name
[0] not in "\\$":
73 name
= "\\{}".format(name
)
74 while name
in self
._names
:
76 name
= "{}${}".format(name
, self
._index
)
81 class _BufferedBuilder
:
84 self
._buffer
= io
.StringIO()
87 return self
._buffer
.getvalue()
89 def _append(self
, fmt
, *args
, **kwargs
):
90 self
._buffer
.write(fmt
.format(*args
, **kwargs
))
93 class _ProxiedBuilder
:
94 def _append(self
, *args
, **kwargs
):
95 self
.rtlil
._append
(*args
, **kwargs
)
99 def _attribute(self
, name
, value
, *, indent
=0):
100 self
._append
("{}attribute \\{} {}\n",
101 " " * indent
, name
, _const(value
))
103 def _attributes(self
, attrs
, *, src
=None, **kwargs
):
104 for name
, value
in attrs
.items():
105 self
._attribute
(name
, value
, **kwargs
)
107 self
._attribute
("src", src
, **kwargs
)
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
)
116 class _ModuleBuilder(_Namer
, _BufferedBuilder
, _AttrBuilder
):
117 def __init__(self
, rtlil
, name
, attrs
):
121 self
.attrs
= {"generator": "nMigen"}
122 self
.attrs
.update(attrs
)
125 self
._attributes
(self
.attrs
)
126 self
._append
("module {}\n", self
.name
)
129 def __exit__(self
, *args
):
130 self
._append
("end\n")
131 self
.rtlil
._buffer
.write(str(self
))
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.
139 raise ImplementationLimit("Wire created at {} is {} bits wide, which is unlikely to "
140 "synthesize correctly"
141 .format(src
or "unknown location", width
))
143 self
._attributes
(attrs
, src
=src
, indent
=1)
144 name
= self
._make
_name
(name
, local
=False)
146 self
._append
(" wire width {} {}\n", width
, name
)
148 assert port_kind
in ("input", "output", "inout")
149 self
._append
(" wire width {} {} {} {}\n", width
, port_kind
, port_id
, name
)
152 def connect(self
, lhs
, rhs
):
153 self
._append
(" connect {} {}\n", lhs
, rhs
)
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
)
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",
170 self
._append
(" parameter signed \\{} {}\n",
171 param
, _const(value
))
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")
180 def process(self
, name
=None, attrs
={}, src
=""):
181 name
= self
._make
_name
(name
, local
=True)
182 return _ProcessBuilder(self
, name
, attrs
, src
)
185 class _ProcessBuilder(_BufferedBuilder
, _AttrBuilder
):
186 def __init__(self
, rtlil
, name
, attrs
, src
):
194 self
._attributes
(self
.attrs
, src
=self
.src
, indent
=1)
195 self
._append
(" process {}\n", self
.name
)
198 def __exit__(self
, *args
):
199 self
._append
(" end\n")
200 self
.rtlil
._buffer
.write(str(self
))
203 return _CaseBuilder(self
, indent
=2)
205 def sync(self
, kind
, cond
=None):
206 return _SyncBuilder(self
, kind
, cond
)
209 class _CaseBuilder(_ProxiedBuilder
):
210 def __init__(self
, rtlil
, indent
):
217 def __exit__(self
, *args
):
220 def assign(self
, lhs
, rhs
):
221 self
._append
("{}assign {} {}\n", " " * self
.indent
, lhs
, rhs
)
223 def switch(self
, cond
, attrs
={}, src
=""):
224 return _SwitchBuilder(self
.rtlil
, cond
, attrs
, src
, self
.indent
)
227 class _SwitchBuilder(_ProxiedBuilder
, _AttrBuilder
):
228 def __init__(self
, rtlil
, cond
, attrs
, src
, indent
):
236 self
._attributes
(self
.attrs
, src
=self
.src
, indent
=self
.indent
)
237 self
._append
("{}switch {}\n", " " * self
.indent
, self
.cond
)
240 def __exit__(self
, *args
):
241 self
._append
("{}end\n", " " * self
.indent
)
243 def case(self
, *values
, attrs
={}, src
=""):
244 self
._attributes
(attrs
, src
=src
, indent
=self
.indent
+ 1)
246 self
._append
("{}case\n", " " * (self
.indent
+ 1))
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)
253 class _SyncBuilder(_ProxiedBuilder
):
254 def __init__(self
, rtlil
, kind
, cond
):
260 if self
.cond
is None:
261 self
._append
(" sync {}\n", self
.kind
)
263 self
._append
(" sync {} {}\n", self
.kind
, self
.cond
)
266 def __exit__(self
, *args
):
269 def update(self
, lhs
, rhs
):
270 self
._append
(" update {} {}\n", lhs
, rhs
)
277 return "{}:{}".format(file, line
)
280 class _LegalizeValue(Exception):
281 def __init__(self
, value
, branches
, src_loc
):
283 self
.branches
= list(branches
)
284 self
.src_loc
= src_loc
287 class _ValueCompilerState
:
288 def __init__(self
, rtlil
):
290 self
.wires
= ast
.SignalDict()
291 self
.driven
= ast
.SignalDict()
292 self
.ports
= ast
.SignalDict()
293 self
.anys
= ast
.ValueDict()
295 self
.expansions
= ast
.ValueDict()
297 def add_driven(self
, signal
, sync
):
298 self
.driven
[signal
] = sync
300 def add_port(self
, signal
, kind
):
301 assert kind
in ("i", "o", "io")
308 self
.ports
[signal
] = (len(self
.ports
), kind
)
310 def resolve(self
, signal
, prefix
=None):
314 if signal
in self
.wires
:
315 return self
.wires
[signal
]
317 if signal
in self
.ports
:
318 port_id
, port_kind
= self
.ports
[signal
]
320 port_id
= port_kind
= None
321 if prefix
is not None:
322 wire_name
= "{}_{}".format(prefix
, signal
.name
)
324 wire_name
= signal
.name
326 attrs
= dict(signal
.attrs
)
327 if signal
._enum
_class
is not None:
328 attrs
["enum_base_type"] = signal
._enum
_class
.__name
__
329 for value
in signal
._enum
_class
:
330 attrs
["enum_value_{:0{}b}".format(value
.value
, signal
.width
)] = value
.name
332 wire_curr
= self
.rtlil
.wire(width
=signal
.width
, name
=wire_name
,
333 port_id
=port_id
, port_kind
=port_kind
,
334 attrs
=attrs
, src
=_src(signal
.src_loc
))
335 if signal
in self
.driven
and self
.driven
[signal
]:
336 wire_next
= self
.rtlil
.wire(width
=signal
.width
, name
=wire_curr
+ "$next",
337 src
=_src(signal
.src_loc
))
340 self
.wires
[signal
] = (wire_curr
, wire_next
)
342 return wire_curr
, wire_next
344 def resolve_curr(self
, signal
, prefix
=None):
345 wire_curr
, wire_next
= self
.resolve(signal
, prefix
)
348 def expand(self
, value
):
349 if not self
.expansions
:
351 return self
.expansions
.get(value
, value
)
354 def expand_to(self
, value
, expansion
):
356 assert value
not in self
.expansions
357 self
.expansions
[value
] = expansion
360 del self
.expansions
[value
]
363 class _ValueCompiler(xfrm
.ValueVisitor
):
364 def __init__(self
, state
):
367 def on_unknown(self
, value
):
371 super().on_unknown(value
)
373 def on_ClockSignal(self
, value
):
374 raise NotImplementedError # :nocov:
376 def on_ResetSignal(self
, value
):
377 raise NotImplementedError # :nocov:
379 def on_Sample(self
, value
):
380 raise NotImplementedError # :nocov:
382 def on_Initial(self
, value
):
383 raise NotImplementedError # :nocov:
385 def on_Cat(self
, value
):
386 return "{{ {} }}".format(" ".join(reversed([self(o
) for o
in value
.parts
])))
388 def _prepare_value_for_Slice(self
, value
):
389 raise NotImplementedError # :nocov:
391 def on_Slice(self
, value
):
392 if value
.start
== 0 and value
.stop
== len(value
.value
):
393 return self(value
.value
)
395 if isinstance(value
.value
, ast
.UserValue
):
396 sigspec
= self
._prepare
_value
_for
_Slice
(value
.value
._lazy
_lower
())
398 sigspec
= self
._prepare
_value
_for
_Slice
(value
.value
)
400 if value
.start
== value
.stop
:
402 elif value
.start
+ 1 == value
.stop
:
403 return "{} [{}]".format(sigspec
, value
.start
)
405 return "{} [{}:{}]".format(sigspec
, value
.stop
- 1, value
.start
)
407 def on_ArrayProxy(self
, value
):
408 index
= self
.s
.expand(value
.index
)
409 if isinstance(index
, ast
.Const
):
410 if index
.value
< len(value
.elems
):
411 elem
= value
.elems
[index
.value
]
413 elem
= value
.elems
[-1]
414 return self
.match_shape(elem
, *value
.shape())
416 max_index
= 1 << len(value
.index
)
417 max_elem
= len(value
.elems
)
418 raise _LegalizeValue(value
.index
, range(min(max_index
, max_elem
)), value
.src_loc
)
421 class _RHSValueCompiler(_ValueCompiler
):
425 (1, "b"): "$reduce_bool",
426 (1, "r|"): "$reduce_or",
427 (1, "r&"): "$reduce_and",
428 (1, "r^"): "$reduce_xor",
449 def on_value(self
, value
):
450 return super().on_value(self
.s
.expand(value
))
452 def on_Const(self
, value
):
455 def on_AnyConst(self
, value
):
456 if value
in self
.s
.anys
:
457 return self
.s
.anys
[value
]
459 res_bits
, res_sign
= value
.shape()
460 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=_src(value
.src_loc
))
461 self
.s
.rtlil
.cell("$anyconst", ports
={
465 }, src
=_src(value
.src_loc
))
466 self
.s
.anys
[value
] = res
469 def on_AnySeq(self
, value
):
470 if value
in self
.s
.anys
:
471 return self
.s
.anys
[value
]
473 res_bits
, res_sign
= value
.shape()
474 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=_src(value
.src_loc
))
475 self
.s
.rtlil
.cell("$anyseq", ports
={
479 }, src
=_src(value
.src_loc
))
480 self
.s
.anys
[value
] = res
483 def on_Signal(self
, value
):
484 wire_curr
, wire_next
= self
.s
.resolve(value
)
487 def on_Operator_unary(self
, value
):
488 arg
, = value
.operands
489 if value
.operator
in ("u", "s"):
490 # These operators don't change the bit pattern, only its interpretation.
493 arg_bits
, arg_sign
= arg
.shape()
494 res_bits
, res_sign
= value
.shape()
495 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=_src(value
.src_loc
))
496 self
.s
.rtlil
.cell(self
.operator_map
[(1, value
.operator
)], ports
={
500 "A_SIGNED": arg_sign
,
503 }, src
=_src(value
.src_loc
))
506 def match_shape(self
, value
, new_bits
, new_sign
):
507 if isinstance(value
, ast
.Const
):
508 return self(ast
.Const(value
.value
, ast
.Shape(new_bits
, new_sign
)))
510 value_bits
, value_sign
= value
.shape()
511 if new_bits
<= value_bits
:
512 return self(ast
.Slice(value
, 0, new_bits
))
514 res
= self
.s
.rtlil
.wire(width
=new_bits
, src
=_src(value
.src_loc
))
515 self
.s
.rtlil
.cell("$pos", ports
={
519 "A_SIGNED": value_sign
,
520 "A_WIDTH": value_bits
,
522 }, src
=_src(value
.src_loc
))
525 def on_Operator_binary(self
, value
):
526 lhs
, rhs
= value
.operands
527 lhs_bits
, lhs_sign
= lhs
.shape()
528 rhs_bits
, rhs_sign
= rhs
.shape()
529 if lhs_sign
== rhs_sign
or value
.operator
in ("<<", ">>", "**"):
533 lhs_sign
= rhs_sign
= True
534 lhs_bits
= rhs_bits
= max(lhs_bits
, rhs_bits
)
535 lhs_wire
= self
.match_shape(lhs
, lhs_bits
, lhs_sign
)
536 rhs_wire
= self
.match_shape(rhs
, rhs_bits
, rhs_sign
)
537 res_bits
, res_sign
= value
.shape()
538 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=_src(value
.src_loc
))
539 self
.s
.rtlil
.cell(self
.operator_map
[(2, value
.operator
)], ports
={
544 "A_SIGNED": lhs_sign
,
546 "B_SIGNED": rhs_sign
,
549 }, src
=_src(value
.src_loc
))
550 if value
.operator
in ("//", "%"):
551 # RTLIL leaves division by zero undefined, but we require it to return zero.
553 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=_src(value
.src_loc
))
554 self
.s
.rtlil
.cell("$mux", ports
={
556 "\\B": self(ast
.Const(0, ast
.Shape(res_bits
, res_sign
))),
557 "\\S": self(rhs
== 0),
561 }, src
=_src(value
.src_loc
))
564 def on_Operator_mux(self
, value
):
565 sel
, val1
, val0
= value
.operands
566 val1_bits
, val1_sign
= val1
.shape()
567 val0_bits
, val0_sign
= val0
.shape()
568 res_bits
, res_sign
= value
.shape()
569 val1_bits
= val0_bits
= res_bits
= max(val1_bits
, val0_bits
, res_bits
)
570 val1_wire
= self
.match_shape(val1
, val1_bits
, val1_sign
)
571 val0_wire
= self
.match_shape(val0
, val0_bits
, val0_sign
)
572 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=_src(value
.src_loc
))
573 self
.s
.rtlil
.cell("$mux", ports
={
580 }, src
=_src(value
.src_loc
))
583 def on_Operator(self
, value
):
584 if len(value
.operands
) == 1:
585 return self
.on_Operator_unary(value
)
586 elif len(value
.operands
) == 2:
587 return self
.on_Operator_binary(value
)
588 elif len(value
.operands
) == 3:
589 assert value
.operator
== "m"
590 return self
.on_Operator_mux(value
)
592 raise TypeError # :nocov:
594 def _prepare_value_for_Slice(self
, value
):
595 if isinstance(value
, (ast
.Signal
, ast
.Slice
, ast
.Cat
)):
596 sigspec
= self(value
)
598 sigspec
= self
.s
.rtlil
.wire(len(value
), src
=_src(value
.src_loc
))
599 self
.s
.rtlil
.connect(sigspec
, self(value
))
602 def on_Part(self
, value
):
603 lhs
, rhs
= value
.value
, value
.offset
604 if value
.stride
!= 1:
606 lhs_bits
, lhs_sign
= lhs
.shape()
607 rhs_bits
, rhs_sign
= rhs
.shape()
608 res_bits
, res_sign
= value
.shape()
609 res
= self
.s
.rtlil
.wire(width
=res_bits
, src
=_src(value
.src_loc
))
610 # Note: Verilog's x[o+:w] construct produces a $shiftx cell, not a $shift cell.
611 # However, nMigen's semantics defines the out-of-range bits to be zero, so it is correct
612 # to use a $shift cell here instead, even though it produces less idiomatic Verilog.
613 self
.s
.rtlil
.cell("$shift", ports
={
618 "A_SIGNED": lhs_sign
,
620 "B_SIGNED": rhs_sign
,
623 }, src
=_src(value
.src_loc
))
626 def on_Repl(self
, value
):
627 return "{{ {} }}".format(" ".join(self(value
.value
) for _
in range(value
.count
)))
630 class _LHSValueCompiler(_ValueCompiler
):
631 def on_Const(self
, value
):
632 raise TypeError # :nocov:
634 def on_AnyConst(self
, value
):
635 raise TypeError # :nocov:
637 def on_AnySeq(self
, value
):
638 raise TypeError # :nocov:
640 def on_Operator(self
, value
):
641 raise TypeError # :nocov:
643 def match_shape(self
, value
, new_bits
, new_sign
):
644 value_bits
, value_sign
= value
.shape()
645 if new_bits
== value_bits
:
647 elif new_bits
< value_bits
:
648 return self(ast
.Slice(value
, 0, new_bits
))
649 else: # new_bits > value_bits
650 dummy_bits
= new_bits
- value_bits
651 dummy_wire
= self
.s
.rtlil
.wire(dummy_bits
)
652 return "{{ {} {} }}".format(dummy_wire
, self(value
))
654 def on_Signal(self
, value
):
655 if value
not in self
.s
.driven
:
656 raise ValueError("No LHS wire for non-driven signal {}".format(repr(value
)))
657 wire_curr
, wire_next
= self
.s
.resolve(value
)
658 return wire_next
or wire_curr
660 def _prepare_value_for_Slice(self
, value
):
661 assert isinstance(value
, (ast
.Signal
, ast
.Slice
, ast
.Cat
))
664 def on_Part(self
, value
):
665 offset
= self
.s
.expand(value
.offset
)
666 if isinstance(offset
, ast
.Const
):
667 start
= offset
.value
* value
.stride
668 stop
= start
+ value
.width
669 slice = self(ast
.Slice(value
.value
, start
, min(len(value
.value
), stop
)))
670 if len(value
.value
) >= stop
:
673 dummy_wire
= self
.s
.rtlil
.wire(stop
- len(value
.value
))
674 return "{{ {} {} }}".format(dummy_wire
, slice)
676 # Only so many possible parts. The amount of branches is exponential; if value.offset
677 # is large (e.g. 32-bit wide), trying to naively legalize it is likely to exhaust
679 max_branches
= len(value
.value
) // value
.stride
+ 1
680 raise _LegalizeValue(value
.offset
,
681 range(1 << len(value
.offset
))[:max_branches
],
684 def on_Repl(self
, value
):
685 raise TypeError # :nocov:
688 class _StatementCompiler(xfrm
.StatementVisitor
):
689 def __init__(self
, state
, rhs_compiler
, lhs_compiler
):
691 self
.rhs_compiler
= rhs_compiler
692 self
.lhs_compiler
= lhs_compiler
695 self
._test
_cache
= {}
696 self
._has
_rhs
= False
697 self
._wrap
_assign
= False
700 def case(self
, switch
, values
, attrs
={}, src
=""):
702 old_case
= self
._case
703 with switch
.case(*values
, attrs
=attrs
, src
=src
) as self
._case
:
706 self
._case
= old_case
708 def _check_rhs(self
, value
):
709 if self
._has
_rhs
or next(iter(value
._rhs
_signals
()), None) is not None:
712 def on_Assign(self
, stmt
):
713 self
._check
_rhs
(stmt
.rhs
)
715 lhs_bits
, lhs_sign
= stmt
.lhs
.shape()
716 rhs_bits
, rhs_sign
= stmt
.rhs
.shape()
717 if lhs_bits
== rhs_bits
:
718 rhs_sigspec
= self
.rhs_compiler(stmt
.rhs
)
720 # In RTLIL, LHS and RHS of assignment must have exactly same width.
721 rhs_sigspec
= self
.rhs_compiler
.match_shape(
722 stmt
.rhs
, lhs_bits
, lhs_sign
)
723 if self
._wrap
_assign
:
724 # In RTLIL, all assigns are logically sequenced before all switches, even if they are
725 # interleaved in the source. In nMigen, the source ordering is used. To handle this
726 # mismatch, we wrap all assigns following a switch in a dummy switch.
727 with self
._case
.switch("{ }") as wrap_switch
:
728 with wrap_switch
.case() as wrap_case
:
729 wrap_case
.assign(self
.lhs_compiler(stmt
.lhs
), rhs_sigspec
)
731 self
._case
.assign(self
.lhs_compiler(stmt
.lhs
), rhs_sigspec
)
733 def on_property(self
, stmt
):
734 self(stmt
._check
.eq(stmt
.test
))
737 en_wire
= self
.rhs_compiler(stmt
._en
)
738 check_wire
= self
.rhs_compiler(stmt
._check
)
739 self
.state
.rtlil
.cell("$" + stmt
._kind
, ports
={
742 }, src
=_src(stmt
.src_loc
))
744 on_Assert
= on_property
745 on_Assume
= on_property
746 on_Cover
= on_property
748 def on_Switch(self
, stmt
):
749 self
._check
_rhs
(stmt
.test
)
751 if not self
.state
.expansions
:
752 # We repeatedly translate the same switches over and over (see the LHSGroupAnalyzer
753 # related code below), and translating the switch test only once helps readability.
754 if stmt
not in self
._test
_cache
:
755 self
._test
_cache
[stmt
] = self
.rhs_compiler(stmt
.test
)
756 test_sigspec
= self
._test
_cache
[stmt
]
758 # However, if the switch test contains an illegal value, then it may not be cached
759 # (since the illegal value will be repeatedly replaced with different constants), so
760 # don't cache anything in that case.
761 test_sigspec
= self
.rhs_compiler(stmt
.test
)
763 with self
._case
.switch(test_sigspec
, src
=_src(stmt
.src_loc
)) as switch
:
764 for values
, stmts
in stmt
.cases
.items():
766 if values
in stmt
.case_src_locs
:
767 case_attrs
["src"] = _src(stmt
.case_src_locs
[values
])
768 if isinstance(stmt
.test
, ast
.Signal
) and stmt
.test
.decoder
:
772 decoded_values
.append("<multiple>")
774 decoded_values
.append(stmt
.test
.decoder(int(value
, 2)))
775 case_attrs
["nmigen.decoding"] = "|".join(decoded_values
)
776 with self
.case(switch
, values
, attrs
=case_attrs
):
777 self
._wrap
_assign
= False
778 self
.on_statements(stmts
)
779 self
._wrap
_assign
= True
781 def on_statement(self
, stmt
):
783 super().on_statement(stmt
)
784 except _LegalizeValue
as legalize
:
785 with self
._case
.switch(self
.rhs_compiler(legalize
.value
),
786 src
=_src(legalize
.src_loc
)) as switch
:
787 shape
= legalize
.value
.shape()
788 tests
= ["{:0{}b}".format(v
, shape
.width
) for v
in legalize
.branches
]
790 tests
[-1] = "-" * shape
.width
791 for branch
, test
in zip(legalize
.branches
, tests
):
792 with self
.case(switch
, (test
,)):
793 self
._wrap
_assign
= False
794 branch_value
= ast
.Const(branch
, shape
)
795 with self
.state
.expand_to(legalize
.value
, branch_value
):
796 self
.on_statement(stmt
)
797 self
._wrap
_assign
= True
799 def on_statements(self
, stmts
):
801 self
.on_statement(stmt
)
804 def _convert_fragment(builder
, fragment
, name_map
, hierarchy
):
805 if isinstance(fragment
, ir
.Instance
):
806 port_map
= OrderedDict()
807 for port_name
, (value
, dir) in fragment
.named_ports
.items():
808 port_map
["\\{}".format(port_name
)] = value
810 if fragment
.type[0] == "$":
811 return fragment
.type, port_map
813 return "\\{}".format(fragment
.type), port_map
815 module_name
= hierarchy
[-1] or "anonymous"
816 module_attrs
= OrderedDict()
817 if len(hierarchy
) == 1:
818 module_attrs
["top"] = 1
819 module_attrs
["nmigen.hierarchy"] = ".".join(name
or "anonymous" for name
in hierarchy
)
821 with builder
.module(module_name
, attrs
=module_attrs
) as module
:
822 compiler_state
= _ValueCompilerState(module
)
823 rhs_compiler
= _RHSValueCompiler(compiler_state
)
824 lhs_compiler
= _LHSValueCompiler(compiler_state
)
825 stmt_compiler
= _StatementCompiler(compiler_state
, rhs_compiler
, lhs_compiler
)
827 verilog_trigger
= None
828 verilog_trigger_sync_emitted
= False
830 # If the fragment is completely empty, add a dummy wire to it, or Yosys will interpret
831 # it as a black box by default (when read as Verilog).
832 if not fragment
.ports
and not fragment
.statements
and not fragment
.subfragments
:
833 module
.wire(1, name
="$empty_module_filler")
835 # Register all signals driven in the current fragment. This must be done first, as it
836 # affects further codegen; e.g. whether \sig$next signals will be generated and used.
837 for domain
, signal
in fragment
.iter_drivers():
838 compiler_state
.add_driven(signal
, sync
=domain
is not None)
840 # Transform all signals used as ports in the current fragment eagerly and outside of
841 # any hierarchy, to make sure they get sensible (non-prefixed) names.
842 for signal
in fragment
.ports
:
843 compiler_state
.add_port(signal
, fragment
.ports
[signal
])
844 compiler_state
.resolve_curr(signal
)
846 # Transform all clocks clocks and resets eagerly and outside of any hierarchy, to make
847 # sure they get sensible (non-prefixed) names. This does not affect semantics.
848 for domain
, _
in fragment
.iter_sync():
849 cd
= fragment
.domains
[domain
]
850 compiler_state
.resolve_curr(cd
.clk
)
851 if cd
.rst
is not None:
852 compiler_state
.resolve_curr(cd
.rst
)
854 # Transform all subfragments to their respective cells. Transforming signals connected
855 # to their ports into wires eagerly makes sure they get sensible (prefixed with submodule
857 memories
= OrderedDict()
858 for subfragment
, sub_name
in fragment
.subfragments
:
860 sub_name
= module
.anonymous()
862 sub_params
= OrderedDict()
863 if hasattr(subfragment
, "parameters"):
864 for param_name
, param_value
in subfragment
.parameters
.items():
865 if isinstance(param_value
, mem
.Memory
):
867 if memory
not in memories
:
868 memories
[memory
] = module
.memory(width
=memory
.width
, size
=memory
.depth
,
869 name
=memory
.name
, attrs
=memory
.attrs
)
870 addr_bits
= bits_for(memory
.depth
)
872 data_mask
= (1 << memory
.width
) - 1
873 for addr
in range(memory
.depth
):
874 if addr
< len(memory
.init
):
875 data
= memory
.init
[addr
] & data_mask
878 data_parts
.append("{:0{}b}".format(data
, memory
.width
))
879 module
.cell("$meminit", ports
={
880 "\\ADDR": rhs_compiler(ast
.Const(0, addr_bits
)),
881 "\\DATA": "{}'".format(memory
.width
* memory
.depth
) +
882 "".join(reversed(data_parts
)),
884 "MEMID": memories
[memory
],
886 "WIDTH": memory
.width
,
887 "WORDS": memory
.depth
,
891 param_value
= memories
[memory
]
893 sub_params
[param_name
] = param_value
895 sub_type
, sub_port_map
= \
896 _convert_fragment(builder
, subfragment
, name_map
,
897 hierarchy
=hierarchy
+ (sub_name
,))
899 sub_ports
= OrderedDict()
900 for port
, value
in sub_port_map
.items():
901 if not isinstance(subfragment
, ir
.Instance
):
902 for signal
in value
._rhs
_signals
():
903 compiler_state
.resolve_curr(signal
, prefix
=sub_name
)
905 sub_ports
[port
] = rhs_compiler(value
)
907 module
.cell(sub_type
, name
=sub_name
, ports
=sub_ports
, params
=sub_params
,
908 attrs
=subfragment
.attrs
)
910 # If we emit all of our combinatorial logic into a single RTLIL process, Verilog
911 # simulators will break horribly, because Yosys write_verilog transforms RTLIL processes
912 # into always @* blocks with blocking assignment, and that does not create delta cycles.
914 # Therefore, we translate the fragment as many times as there are independent groups
915 # of signals (a group is a transitive closure of signals that appear together on LHS),
916 # splitting them into many RTLIL (and thus Verilog) processes.
917 lhs_grouper
= xfrm
.LHSGroupAnalyzer()
918 lhs_grouper
.on_statements(fragment
.statements
)
920 for group
, group_signals
in lhs_grouper
.groups().items():
921 lhs_group_filter
= xfrm
.LHSGroupFilter(group_signals
)
922 group_stmts
= lhs_group_filter(fragment
.statements
)
924 with module
.process(name
="$group_{}".format(group
)) as process
:
925 with process
.case() as case
:
926 # For every signal in comb domain, assign \sig$next to the reset value.
927 # For every signal in sync domains, assign \sig$next to the current
929 for domain
, signal
in fragment
.iter_drivers():
930 if signal
not in group_signals
:
933 prev_value
= ast
.Const(signal
.reset
, signal
.width
)
936 case
.assign(lhs_compiler(signal
), rhs_compiler(prev_value
))
938 # Convert statements into decision trees.
939 stmt_compiler
._case
= case
940 stmt_compiler
._has
_rhs
= False
941 stmt_compiler
._wrap
_assign
= False
942 stmt_compiler(group_stmts
)
944 # Verilog `always @*` blocks will not run if `*` does not match anything, i.e.
945 # if the implicit sensitivity list is empty. We check this while translating,
946 # by looking for any signals on RHS. If there aren't any, we add some logic
947 # whose only purpose is to trigger Verilog simulators when it converts
948 # through RTLIL and to Verilog, by populating the sensitivity list.
950 # Unfortunately, while this workaround allows true (event-driven) Verilog
951 # simulators to work properly, and is universally ignored by synthesizers,
952 # Verilator rejects it.
954 # Yosys >=0.9+3468 emits a better workaround on its own, so this code can be
955 # removed completely once support for Yosys 0.9 is dropped.
956 if not stmt_compiler
._has
_rhs
:
957 if verilog_trigger
is None:
959 module
.wire(1, name
="$verilog_initial_trigger")
960 case
.assign(verilog_trigger
, verilog_trigger
)
962 # For every signal in the sync domain, assign \sig's initial value (which will
963 # end up as the \init reg attribute) to the reset value.
964 with process
.sync("init") as sync
:
965 for domain
, signal
in fragment
.iter_sync():
966 if signal
not in group_signals
:
968 wire_curr
, wire_next
= compiler_state
.resolve(signal
)
969 sync
.update(wire_curr
, rhs_compiler(ast
.Const(signal
.reset
, signal
.width
)))
971 # The Verilog simulator trigger needs to change at time 0, so if we haven't
972 # yet done that in some process, do it.
973 if verilog_trigger
and not verilog_trigger_sync_emitted
:
974 sync
.update(verilog_trigger
, "1'0")
975 verilog_trigger_sync_emitted
= True
977 # For every signal in every sync domain, assign \sig to \sig$next. The sensitivity
978 # list, however, differs between domains: for domains with sync reset, it is
979 # `[pos|neg]edge clk`, for sync domains with async reset it is `[pos|neg]edge clk
981 for domain
, signals
in fragment
.drivers
.items():
985 signals
= signals
& group_signals
989 cd
= fragment
.domains
[domain
]
992 triggers
.append((cd
.clk_edge
+ "edge", compiler_state
.resolve_curr(cd
.clk
)))
994 triggers
.append(("posedge", compiler_state
.resolve_curr(cd
.rst
)))
996 for trigger
in triggers
:
997 with process
.sync(*trigger
) as sync
:
998 for signal
in signals
:
999 wire_curr
, wire_next
= compiler_state
.resolve(signal
)
1000 sync
.update(wire_curr
, wire_next
)
1002 # Any signals that are used but neither driven nor connected to an input port always
1003 # assume their reset values. We need to assign the reset value explicitly, since only
1004 # driven sync signals are handled by the logic above.
1006 # Because this assignment is done at a late stage, a single Signal object can get assigned
1007 # many times, once in each module it is used. This is a deliberate decision; the possible
1008 # alternatives are to add ports for undriven signals (which requires choosing one module
1009 # to drive it to reset value arbitrarily) or to replace them with their reset value (which
1010 # removes valuable source location information).
1011 driven
= ast
.SignalSet()
1012 for domain
, signals
in fragment
.iter_drivers():
1013 driven
.update(flatten(signal
._lhs
_signals
() for signal
in signals
))
1014 driven
.update(fragment
.iter_ports(dir="i"))
1015 driven
.update(fragment
.iter_ports(dir="io"))
1016 for subfragment
, sub_name
in fragment
.subfragments
:
1017 driven
.update(subfragment
.iter_ports(dir="o"))
1018 driven
.update(subfragment
.iter_ports(dir="io"))
1020 for wire
in compiler_state
.wires
:
1023 wire_curr
, _
= compiler_state
.wires
[wire
]
1024 module
.connect(wire_curr
, rhs_compiler(ast
.Const(wire
.reset
, wire
.width
)))
1026 # Collect the names we've given to our ports in RTLIL, and correlate these with the signals
1027 # represented by these ports. If we are a submodule, this will be necessary to create a cell
1028 # for us in the parent module.
1029 port_map
= OrderedDict()
1030 for signal
in fragment
.ports
:
1031 port_map
[compiler_state
.resolve_curr(signal
)] = signal
1033 # Finally, collect tha names we've given to each wire in RTLIL, and provide these to
1034 # the caller, to allow manipulating them in the toolchain.
1035 for signal
in compiler_state
.wires
:
1036 wire_name
= compiler_state
.resolve_curr(signal
)
1037 if wire_name
.startswith("\\"):
1038 wire_name
= wire_name
[1:]
1039 name_map
[signal
] = hierarchy
+ (wire_name
,)
1041 return module
.name
, port_map
1044 def convert_fragment(fragment
, name
="top"):
1045 assert isinstance(fragment
, ir
.Fragment
)
1046 builder
= _Builder()
1047 name_map
= ast
.SignalDict()
1048 _convert_fragment(builder
, fragment
, name_map
, hierarchy
=(name
,))
1049 return str(builder
), name_map
1052 def convert(elaboratable
, name
="top", platform
=None, **kwargs
):
1053 fragment
= ir
.Fragment
.get(elaboratable
, platform
).prepare(**kwargs
)
1054 il_text
, name_map
= convert_fragment(fragment
, name
)