1 import builtins
as _builtins
2 import collections
as _collections
4 from litex
.gen
.fhdl
import tracer
as _tracer
5 from litex
.gen
.util
.misc
import flat_iteration
as _flat_iteration
9 """Deterministic Unique IDentifier"""
12 self
.duid
= DUID
.__next
_uid
17 """Base class for operands
19 Instances of `_Value` or its subclasses can be operands to
20 arithmetic, comparison, bitwise, and logic operators.
21 They can be assigned (:meth:`eq`) or indexed/sliced (using the usual
22 Python indexing and slicing notation).
24 Values created from integers have the minimum bit width to necessary to
25 represent the integer.
28 # Special case: Constants and Signals are part of a set or used as
29 # dictionary keys, and Python needs to check for equality.
30 if isinstance(self
, _Operator
) and self
.op
== "==":
32 if isinstance(a
, Constant
) and isinstance(b
, Constant
):
33 return a
.value
== b
.value
34 if isinstance(a
, Signal
) and isinstance(b
, Signal
):
36 if (isinstance(a
, Constant
) and isinstance(b
, Signal
)
37 or isinstance(a
, Signal
) and isinstance(b
, Constant
)):
39 raise TypeError("Attempted to convert Migen value to boolean")
42 return _Operator("~", [self
])
44 return _Operator("-", [self
])
46 def __add__(self
, other
):
47 return _Operator("+", [self
, other
])
48 def __radd__(self
, other
):
49 return _Operator("+", [other
, self
])
50 def __sub__(self
, other
):
51 return _Operator("-", [self
, other
])
52 def __rsub__(self
, other
):
53 return _Operator("-", [other
, self
])
54 def __mul__(self
, other
):
55 return _Operator("*", [self
, other
])
56 def __rmul__(self
, other
):
57 return _Operator("*", [other
, self
])
58 def __lshift__(self
, other
):
59 return _Operator("<<<", [self
, other
])
60 def __rlshift__(self
, other
):
61 return _Operator("<<<", [other
, self
])
62 def __rshift__(self
, other
):
63 return _Operator(">>>", [self
, other
])
64 def __rrshift__(self
, other
):
65 return _Operator(">>>", [other
, self
])
66 def __and__(self
, other
):
67 return _Operator("&", [self
, other
])
68 def __rand__(self
, other
):
69 return _Operator("&", [other
, self
])
70 def __xor__(self
, other
):
71 return _Operator("^", [self
, other
])
72 def __rxor__(self
, other
):
73 return _Operator("^", [other
, self
])
74 def __or__(self
, other
):
75 return _Operator("|", [self
, other
])
76 def __ror__(self
, other
):
77 return _Operator("|", [other
, self
])
79 def __lt__(self
, other
):
80 return _Operator("<", [self
, other
])
81 def __le__(self
, other
):
82 return _Operator("<=", [self
, other
])
83 def __eq__(self
, other
):
84 return _Operator("==", [self
, other
])
85 def __ne__(self
, other
):
86 return _Operator("!=", [self
, other
])
87 def __gt__(self
, other
):
88 return _Operator(">", [self
, other
])
89 def __ge__(self
, other
):
90 return _Operator(">=", [self
, other
])
93 from litex
.gen
.fhdl
.bitcontainer
import value_bits_sign
94 return value_bits_sign(self
)[0]
96 def __getitem__(self
, key
):
98 if isinstance(key
, int):
103 return _Slice(self
, key
, key
+1)
104 elif isinstance(key
, slice):
105 start
, stop
, step
= key
.indices(n
)
107 return Cat(self
[i
] for i
in range(start
, stop
, step
))
108 return _Slice(self
, start
, stop
)
110 raise TypeError("Cannot use type {} ({}) as key".format(
111 type(key
), repr(key
)))
119 Value to be assigned.
124 Assignment statement that can be used in combinatorial or
127 return _Assign(self
, r
)
130 raise TypeError("unhashable type: '{}'".format(type(self
).__name
__))
134 """Ensures that the passed object is a Migen value. Booleans and integers
135 are automatically wrapped into ``Constant``."""
136 if isinstance(value
, (bool, int)):
137 value
= Constant(value
)
138 if not isinstance(value
, _Value
):
139 raise TypeError("Object is not a Migen value")
143 class _Operator(_Value
):
144 def __init__(self
, op
, operands
):
145 _Value
.__init
__(self
)
147 self
.operands
= [wrap(o
) for o
in operands
]
150 def Mux(sel
, val1
, val0
):
151 """Multiplex between two values
164 Output `_Value`. If `sel` is asserted, the Mux returns
167 return _Operator("m", [sel
, val1
, val0
])
170 class _Slice(_Value
):
171 def __init__(self
, value
, start
, stop
):
172 _Value
.__init
__(self
)
173 if not isinstance(start
, int) or not isinstance(stop
, int):
174 raise TypeError("Slice boundaries must be integers")
175 self
.value
= wrap(value
)
181 """Concatenate values
183 Form a compound `_Value` from several smaller ones by concatenation.
184 The first argument occupies the lower bits of the result.
185 The return value can be used on either side of an assignment, that
186 is, the concatenated value can be used as an argument on the RHS or
187 as a target on the LHS. If it is used on the LHS, it must solely
188 consist of `Signal` s, slices of `Signal` s, and other concatenations
189 meeting these properties. The bit length of the return value is the sum of
190 the bit lengths of the arguments::
192 len(Cat(args)) == sum(len(arg) for arg in args)
196 *args : _Values or iterables of _Values, inout
197 `_Value` s to be concatenated.
202 Resulting `_Value` obtained by concatentation.
204 def __init__(self
, *args
):
205 _Value
.__init
__(self
)
206 self
.l
= [wrap(v
) for v
in _flat_iteration(args
)]
209 class Replicate(_Value
):
212 An input value is replicated (repeated) several times
213 to be used on the RHS of assignments::
215 len(Replicate(s, n)) == len(s)*n
220 Input value to be replicated.
222 Number of replications.
229 def __init__(self
, v
, n
):
230 _Value
.__init
__(self
)
231 if not isinstance(n
, int) or n
< 0:
232 raise TypeError("Replication count must be a positive integer")
237 class Constant(_Value
):
238 """A constant, HDL-literal integer `_Value`
243 bits_sign : int or tuple or None
244 Either an integer `bits` or a tuple `(bits, signed)`
245 specifying the number of bits in this `Constant` and whether it is
246 signed (can represent negative values). `bits_sign` defaults
247 to the minimum width and signedness of `value`.
249 def __init__(self
, value
, bits_sign
=None):
250 from litex
.gen
.fhdl
.bitcontainer
import bits_for
252 _Value
.__init
__(self
)
254 self
.value
= int(value
)
255 if bits_sign
is None:
256 bits_sign
= bits_for(self
.value
), self
.value
< 0
257 elif isinstance(bits_sign
, int):
258 bits_sign
= bits_sign
, self
.value
< 0
259 self
.nbits
, self
.signed
= bits_sign
260 if not isinstance(self
.nbits
, int) or self
.nbits
<= 0:
261 raise TypeError("Width must be a strictly positive integer")
267 C
= Constant
# shorthand
270 class Signal(_Value
):
271 """A `_Value` that can change
273 The `Signal` object represents a value that is expected to change
274 in the circuit. It does exactly what Verilog's `wire` and
275 `reg` and VHDL's `signal` do.
277 A `Signal` can be indexed to access a subset of its bits. Negative
278 indices (`signal[-1]`) and the extended Python slicing notation
279 (`signal[start:stop:step]`) are supported.
280 The indices 0 and -1 are the least and most significant bits
285 bits_sign : int or tuple
286 Either an integer `bits` or a tuple `(bits, signed)`
287 specifying the number of bits in this `Signal` and whether it is
288 signed (can represent negative values). `signed` defaults to
291 Name hint for this signal. If `None` (default) the name is
292 inferred from the variable name this `Signal` is assigned to.
293 Name collisions are automatically resolved by prepending
294 names of objects that contain this `Signal` and by
295 appending integer sequences.
299 Reset (synchronous) or default (combinatorial) value.
300 When this `Signal` is assigned to in synchronous context and the
301 corresponding clock domain is reset, the `Signal` assumes the
302 given value. When this `Signal` is unassigned in combinatorial
303 context (due to conditional assignments not being taken),
304 the `Signal` assumes its `reset` value. Defaults to 0.
305 name_override : str or None
306 Do not use the inferred name but the given one.
309 If `bits_sign` is `None`, the signal bit width and signedness are
310 determined by the integer range given by `min` (inclusive,
311 defaults to 0) and `max` (exclusive, defaults to 2).
312 related : Signal or None
314 def __init__(self
, bits_sign
=None, name
=None, variable
=False, reset
=0, name_override
=None, min=None, max=None, related
=None, attribute
=""):
315 from litex
.gen
.fhdl
.bitcontainer
import bits_for
317 _Value
.__init
__(self
)
319 # determine number of bits and signedness
320 if bits_sign
is None:
325 max -= 1 # make both bounds inclusive
327 self
.signed
= min < 0 or max < 0
328 self
.nbits
= _builtins
.max(bits_for(min, self
.signed
), bits_for(max, self
.signed
))
330 assert(min is None and max is None)
331 if isinstance(bits_sign
, tuple):
332 self
.nbits
, self
.signed
= bits_sign
334 self
.nbits
, self
.signed
= bits_sign
, False
335 if not isinstance(self
.nbits
, int) or self
.nbits
<= 0:
336 raise ValueError("Signal width must be a strictly positive integer")
338 self
.variable
= variable
# deprecated
340 self
.name_override
= name_override
341 self
.backtrace
= _tracer
.trace_back(name
)
342 self
.related
= related
343 self
.attribute
= attribute
345 def __setattr__(self
, k
, v
):
348 _Value
.__setattr
__(self
, k
, v
)
351 return "<Signal " + (self
.backtrace
[-1][0] or "anonymous") + " at " + hex(id(self
)) + ">"
354 def like(cls
, other
, **kwargs
):
355 """Create Signal based on another.
360 Object to base this Signal on.
362 See `migen.fhdl.bitcontainer.value_bits_sign` for details.
364 from litex
.gen
.fhdl
.bitcontainer
import value_bits_sign
365 return cls(bits_sign
=value_bits_sign(other
), **kwargs
)
371 class ClockSignal(_Value
):
372 """Clock signal for a given clock domain
374 `ClockSignal` s for a given clock domain can be retrieved multiple
375 times. They all ultimately refer to the same signal.
380 Clock domain to obtain a clock signal for. Defaults to `"sys"`.
382 def __init__(self
, cd
="sys"):
383 _Value
.__init
__(self
)
384 if not isinstance(cd
, str):
385 raise TypeError("Argument of ClockSignal must be a string")
389 class ResetSignal(_Value
):
390 """Reset signal for a given clock domain
392 `ResetSignal` s for a given clock domain can be retrieved multiple
393 times. They all ultimately refer to the same signal.
398 Clock domain to obtain a reset signal for. Defaults to `"sys"`.
399 allow_reset_less : bool
400 If the clock domain is resetless, return 0 instead of reporting an
403 def __init__(self
, cd
="sys", allow_reset_less
=False):
404 _Value
.__init
__(self
)
405 if not isinstance(cd
, str):
406 raise TypeError("Argument of ResetSignal must be a string")
408 self
.allow_reset_less
= allow_reset_less
418 class _Assign(_Statement
):
419 def __init__(self
, l
, r
):
424 def _check_statement(s
):
425 if isinstance(s
, _collections
.Iterable
):
426 return all(_check_statement(ss
) for ss
in s
)
428 return isinstance(s
, _Statement
)
431 class If(_Statement
):
432 """Conditional execution of statements
439 Statements to execute if `cond` is asserted.
455 def __init__(self
, cond
, *t
):
456 if not _check_statement(t
):
457 raise TypeError("Not all test body objects are Migen statements")
458 self
.cond
= wrap(cond
)
463 """Add an `else` conditional block
468 Statements to execute if all previous conditions fail.
470 if not _check_statement(f
):
471 raise TypeError("Not all test body objects are Migen statements")
472 _insert_else(self
, list(f
))
475 def Elif(self
, cond
, *t
):
476 """Add an `else if` conditional block
483 Statements to execute if previous conditions fail and `cond`
486 _insert_else(self
, [If(cond
, *t
)])
490 def _insert_else(obj
, clause
):
493 assert(len(o
.f
) == 1)
494 assert(isinstance(o
.f
[0], If
))
499 class Case(_Statement
):
500 """Case/Switch statement
505 Selector value used to decide which block to execute
507 Dictionary of cases. The keys are numeric constants to compare
508 with `test`. The values are statements to be executed the
509 corresponding key matches `test`. The dictionary may contain a
510 string key `"default"` to mark a fall-through case that is
511 executed if no other key matches.
520 ... "default": b.eq(0),
523 def __init__(self
, test
, cases
):
524 self
.test
= wrap(test
)
526 for k
, v
in cases
.items():
527 if isinstance(k
, (bool, int)):
529 if (not isinstance(k
, Constant
)
530 and not (isinstance(k
, str) and k
== "default")):
531 raise TypeError("Case object is not a Migen constant")
532 if not isinstance(v
, _collections
.Iterable
):
534 if not _check_statement(v
):
535 raise TypeError("Not all objects for case {} "
536 "are Migen statements".format(k
))
539 def makedefault(self
, key
=None):
540 """Mark a key as the default case
542 Deletes/substitutes any previously existing default case.
546 key : int, Constant or None
547 Key to use as default case if no other key matches.
548 By default, the largest key is the default key.
551 for choice
in self
.cases
.keys():
553 or (isinstance(choice
, str) and choice
== "default")
554 or choice
.value
> key
.value
):
556 if not isinstance(key
, str) or key
!= "default":
558 stmts
= self
.cases
[key
]
560 self
.cases
["default"] = stmts
567 class _ArrayProxy(_Value
):
568 def __init__(self
, choices
, key
):
569 _Value
.__init
__(self
)
572 if isinstance(c
, (bool, int)):
574 self
.choices
.append(c
)
577 def __getattr__(self
, attr
):
578 return _ArrayProxy([getattr(choice
, attr
) for choice
in self
.choices
],
581 def __getitem__(self
, key
):
582 return _ArrayProxy([choice
.__getitem
__(key
) for choice
in self
.choices
],
587 """Addressable multiplexer
589 An array is created from an iterable of values and indexed using the
590 usual Python simple indexing notation (no negative indices or
591 slices). It can be indexed by numeric constants, `_Value` s, or
594 The result of indexing the array is a proxy for the entry at the
595 given index that can be used on either RHS or LHS of assignments.
597 An array can be indexed multiple times.
599 Multidimensional arrays are supported by packing inner arrays into
604 values : iterable of ints, _Values, Signals
605 Entries of the array. Each entry can be a numeric constant, a
606 `Signal` or a `Record`.
610 >>> a = Array(range(10))
611 >>> b = Signal(max=10)
612 >>> c = Signal(max=10)
615 def __getitem__(self
, key
):
616 if isinstance(key
, Constant
):
617 return list.__getitem
__(self
, key
.value
)
618 elif isinstance(key
, _Value
):
619 return _ArrayProxy(self
, key
)
621 return list.__getitem
__(self
, key
)
625 """Synchronous domain
630 Domain name. If None (the default) the name is inferred from the
631 variable name this `ClockDomain` is assigned to (stripping any
634 The domain does not use a reset signal. Registers within this
635 domain are still all initialized to their reset state once, e.g.
636 through Verilog `"initial"` statements.
641 The clock for this domain. Can be driven or used to drive other
642 signals (preferably in combinatorial context).
643 rst : Signal or None, inout
644 Reset signal for this domain. Can be driven or used to drive.
646 def __init__(self
, name
=None, reset_less
=False):
647 self
.name
= _tracer
.get_obj_var_name(name
)
648 if self
.name
is None:
649 raise ValueError("Cannot extract clock domain name from code, need to specify.")
650 if self
.name
.startswith("cd_"):
651 self
.name
= self
.name
[3:]
652 if self
.name
[0].isdigit():
653 raise ValueError("Clock domain name cannot start with a number.")
654 self
.clk
= Signal(name_override
=self
.name
+ "_clk")
658 self
.rst
= Signal(name_override
=self
.name
+ "_rst")
660 def rename(self
, new_name
):
661 """Rename the clock domain
669 self
.clk
.name_override
= new_name
+ "_clk"
670 if self
.rst
is not None:
671 self
.rst
.name_override
= new_name
+ "_rst"
674 class _ClockDomainList(list):
675 def __getitem__(self
, key
):
676 if isinstance(key
, str):
682 return list.__getitem
__(self
, key
)
685 (SPECIAL_INPUT
, SPECIAL_OUTPUT
, SPECIAL_INOUT
) = range(3)
689 def __init__(self
, comb
=None, sync
=None, specials
=None, clock_domains
=None):
690 if comb
is None: comb
= []
691 if sync
is None: sync
= dict()
692 if specials
is None: specials
= set()
693 if clock_domains
is None: clock_domains
= _ClockDomainList()
697 self
.specials
= specials
698 self
.clock_domains
= _ClockDomainList(clock_domains
)
700 def __add__(self
, other
):
701 newsync
= _collections
.defaultdict(list)
702 for k
, v
in self
.sync
.items():
704 for k
, v
in other
.sync
.items():
706 return _Fragment(self
.comb
+ other
.comb
, newsync
,
707 self
.specials | other
.specials
,
708 self
.clock_domains
+ other
.clock_domains
)
710 def __iadd__(self
, other
):
711 newsync
= _collections
.defaultdict(list)
712 for k
, v
in self
.sync
.items():
714 for k
, v
in other
.sync
.items():
716 self
.comb
+= other
.comb
718 self
.specials |
= other
.specials
719 self
.clock_domains
+= other
.clock_domains
722 class Display(_Statement
):
723 def __init__(self
, s
, *args
):