1 # SPDX-License-Identifier: LGPL-2.1-or-later
2 # See Notices.txt for copyright information
5 Copyright (C) 2020 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
7 dynamic-partitionable class similar to Signal, which, when the partition
8 is fully open will be identical to Signal. when partitions are closed,
9 the class turns into a SIMD variant of Signal. *this is dynamic*.
11 the basic fundamental idea is: write code once, and if you want a SIMD
12 version of it, use SimdSignal in place of Signal. job done.
13 this however requires the code to *not* be designed to use nmigen.If,
14 nmigen.Case, or other constructs: only Mux and other logic.
16 * http://bugs.libre-riscv.org/show_bug.cgi?id=132
19 from ieee754
.part_mul_add
.adder
import PartitionedAdder
20 from ieee754
.part_cmp
.eq_gt_ge
import PartitionedEqGtGe
21 from ieee754
.part_bits
.xor
import PartitionedXOR
22 from ieee754
.part_bits
.bool import PartitionedBool
23 from ieee754
.part_bits
.all
import PartitionedAll
24 from ieee754
.part_shift
.part_shift_dynamic
import PartitionedDynamicShift
25 from ieee754
.part_shift
.part_shift_scalar
import PartitionedScalarShift
26 from ieee754
.part_mul_add
.partpoints
import make_partition2
, PartitionPoints
27 from ieee754
.part_mux
.part_mux
import PMux
28 from ieee754
.part_ass
.passign
import PAssign
29 from ieee754
.part_cat
.pcat
import PCat
30 from ieee754
.part_repl
.prepl
import PRepl
31 from operator
import or_
, xor
, and_
, not_
33 from nmigen
import (Signal
, Const
, Cat
)
34 from nmigen
.hdl
.ast
import UserValue
, Shape
38 if isinstance(op1
, SimdSignal
):
43 def applyop(op1
, op2
, op
):
44 if isinstance(op1
, SimdSignal
):
45 result
= SimdSignal
.like(op1
)
47 result
= SimdSignal
.like(op2
)
48 result
.m
.d
.comb
+= result
.sig
.eq(op(getsig(op1
), getsig(op2
)))
54 # for sub-modules to be created on-demand. Mux is done slightly
55 # differently (has its own global)
56 for name
in ['add', 'eq', 'gt', 'ge', 'ls', 'xor', 'bool', 'all']:
60 # Prototype https://bugs.libre-soc.org/show_bug.cgi?id=713#c53
61 # this provides a "compatibility" layer with existing SimdSignal
62 # behaviour. the idea is that this interface defines which "combinations"
63 # of partition selections are relevant, and as an added bonus it says
64 # which partition lanes are completely irrelevant (padding, blank).
65 class PartType
: # TODO decide name
66 def __init__(self
, psig
):
70 return list(self
.psig
.partpoints
.values())
73 return Cat(self
.get_mask())
76 return range(1 << len(self
.get_mask()))
82 # this one would be an elwidth version
83 # see https://bugs.libre-soc.org/show_bug.cgi?id=713#c34
84 # it requires an "adapter" which is the layout() function
85 # where the PartitionPoints was *created* by the layout()
86 # function and this class then "understands" the relationship
87 # between elwidth and the PartitionPoints that were created
91 class ElWidthPartType
: # TODO decide name
92 def __init__(self
, psig
):
96 ppoints
, pbits
= layout()
97 return ppoints
.values() # i think
100 return self
.psig
.elwidth
103 ppoints
, pbits
= layout()
107 def blanklanes(self
):
111 class SimdSignal(UserValue
):
112 # XXX ################################################### XXX
113 # XXX Keep these functions in the same order as ast.Value XXX
114 # XXX ################################################### XXX
115 def __init__(self
, mask
, *args
, src_loc_at
=0, **kwargs
):
116 super().__init
__(src_loc_at
=src_loc_at
)
117 self
.sig
= Signal(*args
, **kwargs
)
118 width
= len(self
.sig
) # get signal width
119 # create partition points
120 if isinstance(mask
, PartitionPoints
):
121 self
.partpoints
= mask
123 self
.partpoints
= make_partition2(mask
, width
)
124 self
.ptype
= PartType(self
)
126 def set_module(self
, m
):
129 def get_modname(self
, category
):
130 modnames
[category
] += 1
131 return "%s_%d" % (category
, modnames
[category
])
134 def like(other
, *args
, **kwargs
):
135 """Builds a new SimdSignal with the same PartitionPoints and
136 Signal properties as the other"""
137 result
= SimdSignal(PartitionPoints(other
.partpoints
))
138 result
.sig
= Signal
.like(other
.sig
, *args
, **kwargs
)
145 # nmigen-redirected constructs (Mux, Cat, Switch, Assign)
147 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=716
148 #def __Part__(self, offset, width, stride=1, *, src_loc_at=0):
149 raise NotImplementedError("TODO: implement as "
150 "(self>>(offset*stride)[:width]")
151 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=716
152 def __Slice__(self
, start
, stop
, *, src_loc_at
=0):
153 # NO. Swizzled shall NOT be deployed, it violates
154 # Project Development Practices
155 raise NotImplementedError("TODO: need PartitionedSlice")
157 def __Repl__(self
, count
, *, src_loc_at
=0):
158 return PRepl(self
.m
, self
, count
, self
.ptype
)
160 def __Cat__(self
, *args
, src_loc_at
=0):
161 print ("partsig cat", self
, args
)
162 # TODO: need SwizzledSimdValue-aware Cat
163 args
= [self
] + list(args
)
165 assert isinstance(sig
, SimdSignal
), \
166 "All SimdSignal.__Cat__ arguments must be " \
167 "a SimdSignal. %s is not." % repr(sig
)
168 return PCat(self
.m
, args
, self
.ptype
)
170 def __Mux__(self
, val1
, val2
):
171 # print ("partsig mux", self, val1, val2)
172 assert len(val1
) == len(val2
), \
173 "SimdSignal width sources must be the same " \
174 "val1 == %d, val2 == %d" % (len(val1
), len(val2
))
175 return PMux(self
.m
, self
.partpoints
, self
, val1
, val2
, self
.ptype
)
177 def __Assign__(self
, val
, *, src_loc_at
=0):
178 print ("partsig assign", self
, val
)
179 # this is a truly awful hack, outlined here:
180 # https://bugs.libre-soc.org/show_bug.cgi?id=731#c13
181 # during the period between constructing Simd-aware sub-modules
182 # and the elaborate() being called on them there is a window of
183 # opportunity to indicate which of those submodules is LHS and
184 # which is RHS. manic laughter is permitted. *gibber*.
185 if hasattr(self
, "_hack_submodule"):
186 self
._hack
_submodule
.set_lhs_mode(True)
187 if hasattr(val
, "_hack_submodule"):
188 val
._hack
_submodule
.set_lhs_mode(False)
189 return PAssign(self
.m
, self
, val
, self
.ptype
)
191 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=458
192 # def __Switch__(self, cases, *, src_loc=None, src_loc_at=0,
195 # no override needed, Value.__bool__ sufficient
196 # def __bool__(self):
198 # unary ops that do not require partitioning
200 def __invert__(self
):
201 result
= SimdSignal
.like(self
)
202 self
.m
.d
.comb
+= result
.sig
.eq(~self
.sig
)
205 # unary ops that require partitioning
208 z
= Const(0, len(self
.sig
))
209 result
, _
= self
.sub_op(z
, self
)
212 # binary ops that need partitioning
214 def add_op(self
, op1
, op2
, carry
):
217 pa
= PartitionedAdder(len(op1
), self
.partpoints
)
218 setattr(self
.m
.submodules
, self
.get_modname('add'), pa
)
222 comb
+= pa
.carry_in
.eq(carry
)
223 result
= SimdSignal
.like(self
)
224 comb
+= result
.sig
.eq(pa
.output
)
225 return result
, pa
.carry_out
227 def sub_op(self
, op1
, op2
, carry
=~
0):
230 pa
= PartitionedAdder(len(op1
), self
.partpoints
)
231 setattr(self
.m
.submodules
, self
.get_modname('add'), pa
)
234 comb
+= pa
.b
.eq(~op2
)
235 comb
+= pa
.carry_in
.eq(carry
)
236 result
= SimdSignal
.like(self
)
237 comb
+= result
.sig
.eq(pa
.output
)
238 return result
, pa
.carry_out
240 def __add__(self
, other
):
241 result
, _
= self
.add_op(self
, other
, carry
=0)
244 def __radd__(self
, other
):
245 # https://bugs.libre-soc.org/show_bug.cgi?id=718
246 result
, _
= self
.add_op(other
, self
)
249 def __sub__(self
, other
):
250 result
, _
= self
.sub_op(self
, other
)
253 def __rsub__(self
, other
):
254 # https://bugs.libre-soc.org/show_bug.cgi?id=718
255 result
, _
= self
.sub_op(other
, self
)
258 def __mul__(self
, other
):
259 raise NotImplementedError # too complicated at the moment
260 return Operator("*", [self
, other
])
262 def __rmul__(self
, other
):
263 raise NotImplementedError # too complicated at the moment
264 return Operator("*", [other
, self
])
266 # not needed: same as Value.__check_divisor
267 # def __check_divisor(self):
269 def __mod__(self
, other
):
270 raise NotImplementedError
271 other
= Value
.cast(other
)
272 other
.__check
_divisor
()
273 return Operator("%", [self
, other
])
275 def __rmod__(self
, other
):
276 raise NotImplementedError
277 self
.__check
_divisor
()
278 return Operator("%", [other
, self
])
280 def __floordiv__(self
, other
):
281 raise NotImplementedError
282 other
= Value
.cast(other
)
283 other
.__check
_divisor
()
284 return Operator("//", [self
, other
])
286 def __rfloordiv__(self
, other
):
287 raise NotImplementedError
288 self
.__check
_divisor
()
289 return Operator("//", [other
, self
])
291 # not needed: same as Value.__check_shamt
292 # def __check_shamt(self):
294 # TODO: detect if the 2nd operand is a Const, a Signal or a
295 # SimdSignal. if it's a Const or a Signal, a global shift
296 # can occur. if it's a SimdSignal, that's much more interesting.
297 def ls_op(self
, op1
, op2
, carry
, shr_flag
=0):
299 if isinstance(op2
, Const
) or isinstance(op2
, Signal
):
301 pa
= PartitionedScalarShift(len(op1
), self
.partpoints
)
305 pa
= PartitionedDynamicShift(len(op1
), self
.partpoints
)
307 # TODO: case where the *shifter* is a SimdSignal but
308 # the thing *being* Shifted is a scalar (Signal, expression)
309 # https://bugs.libre-soc.org/show_bug.cgi?id=718
310 setattr(self
.m
.submodules
, self
.get_modname('ls'), pa
)
313 comb
+= pa
.data
.eq(op1
)
314 comb
+= pa
.shifter
.eq(op2
)
315 comb
+= pa
.shift_right
.eq(shr_flag
)
319 comb
+= pa
.shift_right
.eq(shr_flag
)
320 # XXX TODO: carry-in, carry-out (for arithmetic shift)
321 #comb += pa.carry_in.eq(carry)
322 return (pa
.output
, 0)
324 def __lshift__(self
, other
):
325 z
= Const(0, len(self
.partpoints
)+1)
326 result
, _
= self
.ls_op(self
, other
, carry
=z
) # TODO, carry
329 def __rlshift__(self
, other
):
330 # https://bugs.libre-soc.org/show_bug.cgi?id=718
331 raise NotImplementedError
332 return Operator("<<", [other
, self
])
334 def __rshift__(self
, other
):
335 z
= Const(0, len(self
.partpoints
)+1)
336 result
, _
= self
.ls_op(self
, other
, carry
=z
, shr_flag
=1) # TODO, carry
339 def __rrshift__(self
, other
):
340 # https://bugs.libre-soc.org/show_bug.cgi?id=718
341 raise NotImplementedError
342 return Operator(">>", [other
, self
])
344 # binary ops that don't require partitioning
346 def __and__(self
, other
):
347 return applyop(self
, other
, and_
)
349 def __rand__(self
, other
):
350 return applyop(other
, self
, and_
)
352 def __or__(self
, other
):
353 return applyop(self
, other
, or_
)
355 def __ror__(self
, other
):
356 return applyop(other
, self
, or_
)
358 def __xor__(self
, other
):
359 return applyop(self
, other
, xor
)
361 def __rxor__(self
, other
):
362 return applyop(other
, self
, xor
)
364 # binary comparison ops that need partitioning
366 def _compare(self
, width
, op1
, op2
, opname
, optype
):
367 # print (opname, op1, op2)
368 pa
= PartitionedEqGtGe(width
, self
.partpoints
)
369 setattr(self
.m
.submodules
, self
.get_modname(opname
), pa
)
371 comb
+= pa
.opcode
.eq(optype
) # set opcode
372 if isinstance(op1
, SimdSignal
):
373 comb
+= pa
.a
.eq(op1
.sig
)
376 if isinstance(op2
, SimdSignal
):
377 comb
+= pa
.b
.eq(op2
.sig
)
382 def __eq__(self
, other
):
383 width
= len(self
.sig
)
384 return self
._compare
(width
, self
, other
, "eq", PartitionedEqGtGe
.EQ
)
386 def __ne__(self
, other
):
387 width
= len(self
.sig
)
388 eq
= self
._compare
(width
, self
, other
, "eq", PartitionedEqGtGe
.EQ
)
389 ne
= Signal(eq
.width
)
390 self
.m
.d
.comb
+= ne
.eq(~eq
)
393 def __lt__(self
, other
):
394 width
= len(self
.sig
)
395 # swap operands, use gt to do lt
396 return self
._compare
(width
, other
, self
, "gt", PartitionedEqGtGe
.GT
)
398 def __le__(self
, other
):
399 width
= len(self
.sig
)
400 # swap operands, use ge to do le
401 return self
._compare
(width
, other
, self
, "ge", PartitionedEqGtGe
.GE
)
403 def __gt__(self
, other
):
404 width
= len(self
.sig
)
405 return self
._compare
(width
, self
, other
, "gt", PartitionedEqGtGe
.GT
)
407 def __ge__(self
, other
):
408 width
= len(self
.sig
)
409 return self
._compare
(width
, self
, other
, "ge", PartitionedEqGtGe
.GE
)
411 # no override needed: Value.__abs__ is general enough it does the job
417 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=716
418 # def __getitem__(self, key):
420 def __new_sign(self
, signed
):
421 shape
= Shape(len(self
), signed
=signed
)
422 result
= SimdSignal
.like(self
, shape
=shape
)
423 self
.m
.d
.comb
+= result
.sig
.eq(self
.sig
)
426 # http://bugs.libre-riscv.org/show_bug.cgi?id=719
427 def as_unsigned(self
):
428 return self
.__new
_sign
(False)
431 return self
.__new
_sign
(True)
436 """Conversion to boolean.
441 ``1`` if any bits are set, ``0`` otherwise.
443 width
= len(self
.sig
)
444 pa
= PartitionedBool(width
, self
.partpoints
)
445 setattr(self
.m
.submodules
, self
.get_modname("bool"), pa
)
446 self
.m
.d
.comb
+= pa
.a
.eq(self
.sig
)
450 """Check if any bits are ``1``.
455 ``1`` if any bits are set, ``0`` otherwise.
457 return self
!= Const(0) # leverage the __ne__ operator here
458 return Operator("r|", [self
])
461 """Check if all bits are ``1``.
466 ``1`` if all bits are set, ``0`` otherwise.
468 # something wrong with PartitionedAll, but self == Const(-1)"
469 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=176#c17
470 #width = len(self.sig)
471 #pa = PartitionedAll(width, self.partpoints)
472 #setattr(self.m.submodules, self.get_modname("all"), pa)
473 #self.m.d.comb += pa.a.eq(self.sig)
475 return self
== Const(-1) # leverage the __eq__ operator here
478 """Compute pairwise exclusive-or of every bit.
483 ``1`` if an odd number of bits are set, ``0`` if an
484 even number of bits are set.
486 width
= len(self
.sig
)
487 pa
= PartitionedXOR(width
, self
.partpoints
)
488 setattr(self
.m
.submodules
, self
.get_modname("xor"), pa
)
489 self
.m
.d
.comb
+= pa
.a
.eq(self
.sig
)
492 # not needed: Value.implies does the job
493 # def implies(premise, conclusion):
495 # TODO. contains a Value.cast which means an override is needed (on both)
496 # def bit_select(self, offset, width):
497 # def word_select(self, offset, width):
499 # not needed: Value.matches, amazingly, should do the job
500 # def matches(self, *patterns):
502 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=713
504 return self
.sig
.shape()