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
):
69 return list(self
.psig
.partpoints
.values())
71 return Cat(self
.get_mask())
73 return range(1<<len(self
.get_mask()))
78 # this one would be an elwidth version
79 # see https://bugs.libre-soc.org/show_bug.cgi?id=713#c34
80 # it requires an "adapter" which is the layout() function
81 # where the PartitionPoints was *created* by the layout()
82 # function and this class then "understands" the relationship
83 # between elwidth and the PartitionPoints that were created
85 class ElWidthPartType
: # TODO decide name
86 def __init__(self
, psig
):
89 ppoints
, pbits
= layout()
90 return ppoints
.values() # i think
92 return self
.psig
.elwidth
94 ppoints
, pbits
= layout()
101 class SimdSignal(UserValue
):
102 # XXX ################################################### XXX
103 # XXX Keep these functions in the same order as ast.Value XXX
104 # XXX ################################################### XXX
105 def __init__(self
, mask
, *args
, src_loc_at
=0, **kwargs
):
106 super().__init
__(src_loc_at
=src_loc_at
)
107 self
.sig
= Signal(*args
, **kwargs
)
108 width
= len(self
.sig
) # get signal width
109 # create partition points
110 if isinstance(mask
, PartitionPoints
):
111 self
.partpoints
= mask
113 self
.partpoints
= make_partition2(mask
, width
)
114 self
.ptype
= PartType(self
)
116 def set_module(self
, m
):
119 def get_modname(self
, category
):
120 modnames
[category
] += 1
121 return "%s_%d" % (category
, modnames
[category
])
124 def like(other
, *args
, **kwargs
):
125 """Builds a new SimdSignal with the same PartitionPoints and
126 Signal properties as the other"""
127 result
= SimdSignal(PartitionPoints(other
.partpoints
))
128 result
.sig
= Signal
.like(other
.sig
, *args
, **kwargs
)
135 # nmigen-redirected constructs (Mux, Cat, Switch, Assign)
137 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=458
138 #def __Part__(self, offset, width, stride=1, *, src_loc_at=0):
140 def __Repl__(self
, count
, *, src_loc_at
=0):
141 return PRepl(self
.m
, self
, count
, self
.ptype
)
143 def __Cat__(self
, *args
, src_loc_at
=0):
144 args
= [self
] + list(args
)
146 assert isinstance(sig
, SimdSignal
), \
147 "All SimdSignal.__Cat__ arguments must be " \
148 "a SimdSignal. %s is not." % repr(sig
)
149 return PCat(self
.m
, args
, self
.ptype
)
151 def __Mux__(self
, val1
, val2
):
152 # print ("partsig mux", self, val1, val2)
153 assert len(val1
) == len(val2
), \
154 "SimdSignal width sources must be the same " \
155 "val1 == %d, val2 == %d" % (len(val1
), len(val2
))
156 return PMux(self
.m
, self
.partpoints
, self
, val1
, val2
, self
.ptype
)
158 def __Assign__(self
, val
, *, src_loc_at
=0):
159 # print ("partsig ass", self, val)
160 return PAssign(self
.m
, self
, val
, self
.ptype
)
162 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=458
163 #def __Switch__(self, cases, *, src_loc=None, src_loc_at=0,
166 # no override needed, Value.__bool__ sufficient
167 # def __bool__(self):
169 # unary ops that do not require partitioning
171 def __invert__(self
):
172 result
= SimdSignal
.like(self
)
173 self
.m
.d
.comb
+= result
.sig
.eq(~self
.sig
)
176 # unary ops that require partitioning
179 z
= Const(0, len(self
.sig
))
180 result
, _
= self
.sub_op(z
, self
)
183 # binary ops that need partitioning
185 def add_op(self
, op1
, op2
, carry
):
188 pa
= PartitionedAdder(len(op1
), self
.partpoints
)
189 setattr(self
.m
.submodules
, self
.get_modname('add'), pa
)
193 comb
+= pa
.carry_in
.eq(carry
)
194 result
= SimdSignal
.like(self
)
195 comb
+= result
.sig
.eq(pa
.output
)
196 return result
, pa
.carry_out
198 def sub_op(self
, op1
, op2
, carry
=~
0):
201 pa
= PartitionedAdder(len(op1
), self
.partpoints
)
202 setattr(self
.m
.submodules
, self
.get_modname('add'), pa
)
205 comb
+= pa
.b
.eq(~op2
)
206 comb
+= pa
.carry_in
.eq(carry
)
207 result
= SimdSignal
.like(self
)
208 comb
+= result
.sig
.eq(pa
.output
)
209 return result
, pa
.carry_out
211 def __add__(self
, other
):
212 result
, _
= self
.add_op(self
, other
, carry
=0)
215 def __radd__(self
, other
):
216 # https://bugs.libre-soc.org/show_bug.cgi?id=718
217 result
, _
= self
.add_op(other
, self
)
220 def __sub__(self
, other
):
221 result
, _
= self
.sub_op(self
, other
)
224 def __rsub__(self
, other
):
225 # https://bugs.libre-soc.org/show_bug.cgi?id=718
226 result
, _
= self
.sub_op(other
, self
)
229 def __mul__(self
, other
):
230 raise NotImplementedError # too complicated at the moment
231 return Operator("*", [self
, other
])
233 def __rmul__(self
, other
):
234 raise NotImplementedError # too complicated at the moment
235 return Operator("*", [other
, self
])
237 # not needed: same as Value.__check_divisor
238 #def __check_divisor(self):
240 def __mod__(self
, other
):
241 raise NotImplementedError
242 other
= Value
.cast(other
)
243 other
.__check
_divisor
()
244 return Operator("%", [self
, other
])
246 def __rmod__(self
, other
):
247 raise NotImplementedError
248 self
.__check
_divisor
()
249 return Operator("%", [other
, self
])
251 def __floordiv__(self
, other
):
252 raise NotImplementedError
253 other
= Value
.cast(other
)
254 other
.__check
_divisor
()
255 return Operator("//", [self
, other
])
257 def __rfloordiv__(self
, other
):
258 raise NotImplementedError
259 self
.__check
_divisor
()
260 return Operator("//", [other
, self
])
262 # not needed: same as Value.__check_shamt
263 #def __check_shamt(self):
265 # TODO: detect if the 2nd operand is a Const, a Signal or a
266 # SimdSignal. if it's a Const or a Signal, a global shift
267 # can occur. if it's a SimdSignal, that's much more interesting.
268 def ls_op(self
, op1
, op2
, carry
, shr_flag
=0):
270 if isinstance(op2
, Const
) or isinstance(op2
, Signal
):
272 pa
= PartitionedScalarShift(len(op1
), self
.partpoints
)
276 pa
= PartitionedDynamicShift(len(op1
), self
.partpoints
)
278 # TODO: case where the *shifter* is a SimdSignal but
279 # the thing *being* Shifted is a scalar (Signal, expression)
280 # https://bugs.libre-soc.org/show_bug.cgi?id=718
281 setattr(self
.m
.submodules
, self
.get_modname('ls'), pa
)
284 comb
+= pa
.data
.eq(op1
)
285 comb
+= pa
.shifter
.eq(op2
)
286 comb
+= pa
.shift_right
.eq(shr_flag
)
290 comb
+= pa
.shift_right
.eq(shr_flag
)
291 # XXX TODO: carry-in, carry-out (for arithmetic shift)
292 #comb += pa.carry_in.eq(carry)
293 return (pa
.output
, 0)
295 def __lshift__(self
, other
):
296 z
= Const(0, len(self
.partpoints
)+1)
297 result
, _
= self
.ls_op(self
, other
, carry
=z
) # TODO, carry
300 def __rlshift__(self
, other
):
301 # https://bugs.libre-soc.org/show_bug.cgi?id=718
302 raise NotImplementedError
303 return Operator("<<", [other
, self
])
305 def __rshift__(self
, other
):
306 z
= Const(0, len(self
.partpoints
)+1)
307 result
, _
= self
.ls_op(self
, other
, carry
=z
, shr_flag
=1) # TODO, carry
310 def __rrshift__(self
, other
):
311 # https://bugs.libre-soc.org/show_bug.cgi?id=718
312 raise NotImplementedError
313 return Operator(">>", [other
, self
])
315 # binary ops that don't require partitioning
317 def __and__(self
, other
):
318 return applyop(self
, other
, and_
)
320 def __rand__(self
, other
):
321 return applyop(other
, self
, and_
)
323 def __or__(self
, other
):
324 return applyop(self
, other
, or_
)
326 def __ror__(self
, other
):
327 return applyop(other
, self
, or_
)
329 def __xor__(self
, other
):
330 return applyop(self
, other
, xor
)
332 def __rxor__(self
, other
):
333 return applyop(other
, self
, xor
)
335 # binary comparison ops that need partitioning
337 def _compare(self
, width
, op1
, op2
, opname
, optype
):
338 # print (opname, op1, op2)
339 pa
= PartitionedEqGtGe(width
, self
.partpoints
)
340 setattr(self
.m
.submodules
, self
.get_modname(opname
), pa
)
342 comb
+= pa
.opcode
.eq(optype
) # set opcode
343 if isinstance(op1
, SimdSignal
):
344 comb
+= pa
.a
.eq(op1
.sig
)
347 if isinstance(op2
, SimdSignal
):
348 comb
+= pa
.b
.eq(op2
.sig
)
353 def __eq__(self
, other
):
354 width
= len(self
.sig
)
355 return self
._compare
(width
, self
, other
, "eq", PartitionedEqGtGe
.EQ
)
357 def __ne__(self
, other
):
358 width
= len(self
.sig
)
359 eq
= self
._compare
(width
, self
, other
, "eq", PartitionedEqGtGe
.EQ
)
360 ne
= Signal(eq
.width
)
361 self
.m
.d
.comb
+= ne
.eq(~eq
)
364 def __lt__(self
, other
):
365 width
= len(self
.sig
)
366 # swap operands, use gt to do lt
367 return self
._compare
(width
, other
, self
, "gt", PartitionedEqGtGe
.GT
)
369 def __le__(self
, other
):
370 width
= len(self
.sig
)
371 # swap operands, use ge to do le
372 return self
._compare
(width
, other
, self
, "ge", PartitionedEqGtGe
.GE
)
374 def __gt__(self
, other
):
375 width
= len(self
.sig
)
376 return self
._compare
(width
, self
, other
, "gt", PartitionedEqGtGe
.GT
)
378 def __ge__(self
, other
):
379 width
= len(self
.sig
)
380 return self
._compare
(width
, self
, other
, "ge", PartitionedEqGtGe
.GE
)
382 # no override needed: Value.__abs__ is general enough it does the job
388 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=716
389 # def __getitem__(self, key):
391 def __new_sign(self
, signed
):
392 shape
= Shape(len(self
), signed
=signed
)
393 result
= SimdSignal
.like(self
, shape
=shape
)
394 self
.m
.d
.comb
+= result
.sig
.eq(self
.sig
)
397 # http://bugs.libre-riscv.org/show_bug.cgi?id=719
398 def as_unsigned(self
):
399 return self
.__new
_sign
(False)
401 return self
.__new
_sign
(True)
406 """Conversion to boolean.
411 ``1`` if any bits are set, ``0`` otherwise.
413 width
= len(self
.sig
)
414 pa
= PartitionedBool(width
, self
.partpoints
)
415 setattr(self
.m
.submodules
, self
.get_modname("bool"), pa
)
416 self
.m
.d
.comb
+= pa
.a
.eq(self
.sig
)
420 """Check if any bits are ``1``.
425 ``1`` if any bits are set, ``0`` otherwise.
427 return self
!= Const(0) # leverage the __ne__ operator here
428 return Operator("r|", [self
])
431 """Check if all bits are ``1``.
436 ``1`` if all bits are set, ``0`` otherwise.
438 # something wrong with PartitionedAll, but self == Const(-1)"
439 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=176#c17
440 #width = len(self.sig)
441 #pa = PartitionedAll(width, self.partpoints)
442 #setattr(self.m.submodules, self.get_modname("all"), pa)
443 #self.m.d.comb += pa.a.eq(self.sig)
445 return self
== Const(-1) # leverage the __eq__ operator here
448 """Compute pairwise exclusive-or of every bit.
453 ``1`` if an odd number of bits are set, ``0`` if an
454 even number of bits are set.
456 width
= len(self
.sig
)
457 pa
= PartitionedXOR(width
, self
.partpoints
)
458 setattr(self
.m
.submodules
, self
.get_modname("xor"), pa
)
459 self
.m
.d
.comb
+= pa
.a
.eq(self
.sig
)
462 # not needed: Value.implies does the job
463 # def implies(premise, conclusion):
465 # TODO. contains a Value.cast which means an override is needed (on both)
466 # def bit_select(self, offset, width):
467 # def word_select(self, offset, width):
469 # not needed: Value.matches, amazingly, should do the job
470 # def matches(self, *patterns):
472 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=713
474 return self
.sig
.shape()