add WIP code for handling Slice and Cat in a unified way, supporting assignment
[ieee754fpu.git] / src / ieee754 / part / partsig.py
1 # SPDX-License-Identifier: LGPL-2.1-or-later
2 # See Notices.txt for copyright information
3
4 """
5 Copyright (C) 2020 Luke Kenneth Casson Leighton <lkcl@lkcl.net>
6
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*.
10
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.
15
16 * http://bugs.libre-riscv.org/show_bug.cgi?id=132
17 """
18
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_
32
33 from nmigen import (Signal, Const, Cat)
34 from nmigen.hdl.ast import UserValue, Shape
35
36
37 def getsig(op1):
38 if isinstance(op1, SimdSignal):
39 op1 = op1.sig
40 return op1
41
42
43 def applyop(op1, op2, op):
44 if isinstance(op1, SimdSignal):
45 result = SimdSignal.like(op1)
46 else:
47 result = SimdSignal.like(op2)
48 result.m.d.comb += result.sig.eq(op(getsig(op1), getsig(op2)))
49 return result
50
51
52 global modnames
53 modnames = {}
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']:
57 modnames[name] = 0
58
59
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):
67 self.psig = psig
68
69 def get_mask(self):
70 return list(self.psig.partpoints.values())
71
72 def get_switch(self):
73 return Cat(self.get_mask())
74
75 def get_cases(self):
76 return range(1 << len(self.get_mask()))
77
78 @property
79 def blanklanes(self):
80 return 0
81
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
88 # by layout()
89
90
91 class ElWidthPartType: # TODO decide name
92 def __init__(self, psig):
93 self.psig = psig
94
95 def get_mask(self):
96 ppoints, pbits = layout()
97 return ppoints.values() # i think
98
99 def get_switch(self):
100 return self.psig.elwidth
101
102 def get_cases(self):
103 ppoints, pbits = layout()
104 return pbits
105
106 @property
107 def blanklanes(self):
108 return 0 # TODO
109
110
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
122 else:
123 self.partpoints = make_partition2(mask, width)
124 self.ptype = PartType(self)
125
126 def set_module(self, m):
127 self.m = m
128
129 def get_modname(self, category):
130 modnames[category] += 1
131 return "%s_%d" % (category, modnames[category])
132
133 @staticmethod
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)
139 result.m = other.m
140 return result
141
142 def lower(self):
143 return self.sig
144
145 # nmigen-redirected constructs (Mux, Cat, Switch, Assign)
146
147 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=458
148 # def __Part__(self, offset, width, stride=1, *, src_loc_at=0):
149
150 def __Repl__(self, count, *, src_loc_at=0):
151 return PRepl(self.m, self, count, self.ptype)
152
153 def __Cat__(self, *args, src_loc_at=0):
154 # TODO: need SwizzledSimdValue-aware Cat
155 args = [self] + list(args)
156 for sig in args:
157 assert isinstance(sig, SimdSignal), \
158 "All SimdSignal.__Cat__ arguments must be " \
159 "a SimdSignal. %s is not." % repr(sig)
160 return PCat(self.m, args, self.ptype)
161
162 def __Mux__(self, val1, val2):
163 # print ("partsig mux", self, val1, val2)
164 assert len(val1) == len(val2), \
165 "SimdSignal width sources must be the same " \
166 "val1 == %d, val2 == %d" % (len(val1), len(val2))
167 return PMux(self.m, self.partpoints, self, val1, val2, self.ptype)
168
169 def __Assign__(self, val, *, src_loc_at=0):
170 # print ("partsig ass", self, val)
171 return PAssign(self.m, self, val, self.ptype)
172
173 def __Slice__(self, start, stop, *, src_loc_at=0):
174 # TODO: add __Slice__ redirection to nmigen
175 raise NotImplementedError("TODO: need SwizzledSimdValue-aware Slice")
176
177 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=458
178 # def __Switch__(self, cases, *, src_loc=None, src_loc_at=0,
179 # case_src_locs={}):
180
181 # no override needed, Value.__bool__ sufficient
182 # def __bool__(self):
183
184 # unary ops that do not require partitioning
185
186 def __invert__(self):
187 result = SimdSignal.like(self)
188 self.m.d.comb += result.sig.eq(~self.sig)
189 return result
190
191 # unary ops that require partitioning
192
193 def __neg__(self):
194 z = Const(0, len(self.sig))
195 result, _ = self.sub_op(z, self)
196 return result
197
198 # binary ops that need partitioning
199
200 def add_op(self, op1, op2, carry):
201 op1 = getsig(op1)
202 op2 = getsig(op2)
203 pa = PartitionedAdder(len(op1), self.partpoints)
204 setattr(self.m.submodules, self.get_modname('add'), pa)
205 comb = self.m.d.comb
206 comb += pa.a.eq(op1)
207 comb += pa.b.eq(op2)
208 comb += pa.carry_in.eq(carry)
209 result = SimdSignal.like(self)
210 comb += result.sig.eq(pa.output)
211 return result, pa.carry_out
212
213 def sub_op(self, op1, op2, carry=~0):
214 op1 = getsig(op1)
215 op2 = getsig(op2)
216 pa = PartitionedAdder(len(op1), self.partpoints)
217 setattr(self.m.submodules, self.get_modname('add'), pa)
218 comb = self.m.d.comb
219 comb += pa.a.eq(op1)
220 comb += pa.b.eq(~op2)
221 comb += pa.carry_in.eq(carry)
222 result = SimdSignal.like(self)
223 comb += result.sig.eq(pa.output)
224 return result, pa.carry_out
225
226 def __add__(self, other):
227 result, _ = self.add_op(self, other, carry=0)
228 return result
229
230 def __radd__(self, other):
231 # https://bugs.libre-soc.org/show_bug.cgi?id=718
232 result, _ = self.add_op(other, self)
233 return result
234
235 def __sub__(self, other):
236 result, _ = self.sub_op(self, other)
237 return result
238
239 def __rsub__(self, other):
240 # https://bugs.libre-soc.org/show_bug.cgi?id=718
241 result, _ = self.sub_op(other, self)
242 return result
243
244 def __mul__(self, other):
245 raise NotImplementedError # too complicated at the moment
246 return Operator("*", [self, other])
247
248 def __rmul__(self, other):
249 raise NotImplementedError # too complicated at the moment
250 return Operator("*", [other, self])
251
252 # not needed: same as Value.__check_divisor
253 # def __check_divisor(self):
254
255 def __mod__(self, other):
256 raise NotImplementedError
257 other = Value.cast(other)
258 other.__check_divisor()
259 return Operator("%", [self, other])
260
261 def __rmod__(self, other):
262 raise NotImplementedError
263 self.__check_divisor()
264 return Operator("%", [other, self])
265
266 def __floordiv__(self, other):
267 raise NotImplementedError
268 other = Value.cast(other)
269 other.__check_divisor()
270 return Operator("//", [self, other])
271
272 def __rfloordiv__(self, other):
273 raise NotImplementedError
274 self.__check_divisor()
275 return Operator("//", [other, self])
276
277 # not needed: same as Value.__check_shamt
278 # def __check_shamt(self):
279
280 # TODO: detect if the 2nd operand is a Const, a Signal or a
281 # SimdSignal. if it's a Const or a Signal, a global shift
282 # can occur. if it's a SimdSignal, that's much more interesting.
283 def ls_op(self, op1, op2, carry, shr_flag=0):
284 op1 = getsig(op1)
285 if isinstance(op2, Const) or isinstance(op2, Signal):
286 scalar = True
287 pa = PartitionedScalarShift(len(op1), self.partpoints)
288 else:
289 scalar = False
290 op2 = getsig(op2)
291 pa = PartitionedDynamicShift(len(op1), self.partpoints)
292 # else:
293 # TODO: case where the *shifter* is a SimdSignal but
294 # the thing *being* Shifted is a scalar (Signal, expression)
295 # https://bugs.libre-soc.org/show_bug.cgi?id=718
296 setattr(self.m.submodules, self.get_modname('ls'), pa)
297 comb = self.m.d.comb
298 if scalar:
299 comb += pa.data.eq(op1)
300 comb += pa.shifter.eq(op2)
301 comb += pa.shift_right.eq(shr_flag)
302 else:
303 comb += pa.a.eq(op1)
304 comb += pa.b.eq(op2)
305 comb += pa.shift_right.eq(shr_flag)
306 # XXX TODO: carry-in, carry-out (for arithmetic shift)
307 #comb += pa.carry_in.eq(carry)
308 return (pa.output, 0)
309
310 def __lshift__(self, other):
311 z = Const(0, len(self.partpoints)+1)
312 result, _ = self.ls_op(self, other, carry=z) # TODO, carry
313 return result
314
315 def __rlshift__(self, other):
316 # https://bugs.libre-soc.org/show_bug.cgi?id=718
317 raise NotImplementedError
318 return Operator("<<", [other, self])
319
320 def __rshift__(self, other):
321 z = Const(0, len(self.partpoints)+1)
322 result, _ = self.ls_op(self, other, carry=z, shr_flag=1) # TODO, carry
323 return result
324
325 def __rrshift__(self, other):
326 # https://bugs.libre-soc.org/show_bug.cgi?id=718
327 raise NotImplementedError
328 return Operator(">>", [other, self])
329
330 # binary ops that don't require partitioning
331
332 def __and__(self, other):
333 return applyop(self, other, and_)
334
335 def __rand__(self, other):
336 return applyop(other, self, and_)
337
338 def __or__(self, other):
339 return applyop(self, other, or_)
340
341 def __ror__(self, other):
342 return applyop(other, self, or_)
343
344 def __xor__(self, other):
345 return applyop(self, other, xor)
346
347 def __rxor__(self, other):
348 return applyop(other, self, xor)
349
350 # binary comparison ops that need partitioning
351
352 def _compare(self, width, op1, op2, opname, optype):
353 # print (opname, op1, op2)
354 pa = PartitionedEqGtGe(width, self.partpoints)
355 setattr(self.m.submodules, self.get_modname(opname), pa)
356 comb = self.m.d.comb
357 comb += pa.opcode.eq(optype) # set opcode
358 if isinstance(op1, SimdSignal):
359 comb += pa.a.eq(op1.sig)
360 else:
361 comb += pa.a.eq(op1)
362 if isinstance(op2, SimdSignal):
363 comb += pa.b.eq(op2.sig)
364 else:
365 comb += pa.b.eq(op2)
366 return pa.output
367
368 def __eq__(self, other):
369 width = len(self.sig)
370 return self._compare(width, self, other, "eq", PartitionedEqGtGe.EQ)
371
372 def __ne__(self, other):
373 width = len(self.sig)
374 eq = self._compare(width, self, other, "eq", PartitionedEqGtGe.EQ)
375 ne = Signal(eq.width)
376 self.m.d.comb += ne.eq(~eq)
377 return ne
378
379 def __lt__(self, other):
380 width = len(self.sig)
381 # swap operands, use gt to do lt
382 return self._compare(width, other, self, "gt", PartitionedEqGtGe.GT)
383
384 def __le__(self, other):
385 width = len(self.sig)
386 # swap operands, use ge to do le
387 return self._compare(width, other, self, "ge", PartitionedEqGtGe.GE)
388
389 def __gt__(self, other):
390 width = len(self.sig)
391 return self._compare(width, self, other, "gt", PartitionedEqGtGe.GT)
392
393 def __ge__(self, other):
394 width = len(self.sig)
395 return self._compare(width, self, other, "ge", PartitionedEqGtGe.GE)
396
397 # no override needed: Value.__abs__ is general enough it does the job
398 # def __abs__(self):
399
400 def __len__(self):
401 return len(self.sig)
402
403 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=716
404 # def __getitem__(self, key):
405
406 def __new_sign(self, signed):
407 shape = Shape(len(self), signed=signed)
408 result = SimdSignal.like(self, shape=shape)
409 self.m.d.comb += result.sig.eq(self.sig)
410 return result
411
412 # http://bugs.libre-riscv.org/show_bug.cgi?id=719
413 def as_unsigned(self):
414 return self.__new_sign(False)
415
416 def as_signed(self):
417 return self.__new_sign(True)
418
419 # useful operators
420
421 def bool(self):
422 """Conversion to boolean.
423
424 Returns
425 -------
426 Value, out
427 ``1`` if any bits are set, ``0`` otherwise.
428 """
429 width = len(self.sig)
430 pa = PartitionedBool(width, self.partpoints)
431 setattr(self.m.submodules, self.get_modname("bool"), pa)
432 self.m.d.comb += pa.a.eq(self.sig)
433 return pa.output
434
435 def any(self):
436 """Check if any bits are ``1``.
437
438 Returns
439 -------
440 Value, out
441 ``1`` if any bits are set, ``0`` otherwise.
442 """
443 return self != Const(0) # leverage the __ne__ operator here
444 return Operator("r|", [self])
445
446 def all(self):
447 """Check if all bits are ``1``.
448
449 Returns
450 -------
451 Value, out
452 ``1`` if all bits are set, ``0`` otherwise.
453 """
454 # something wrong with PartitionedAll, but self == Const(-1)"
455 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=176#c17
456 #width = len(self.sig)
457 #pa = PartitionedAll(width, self.partpoints)
458 #setattr(self.m.submodules, self.get_modname("all"), pa)
459 #self.m.d.comb += pa.a.eq(self.sig)
460 # return pa.output
461 return self == Const(-1) # leverage the __eq__ operator here
462
463 def xor(self):
464 """Compute pairwise exclusive-or of every bit.
465
466 Returns
467 -------
468 Value, out
469 ``1`` if an odd number of bits are set, ``0`` if an
470 even number of bits are set.
471 """
472 width = len(self.sig)
473 pa = PartitionedXOR(width, self.partpoints)
474 setattr(self.m.submodules, self.get_modname("xor"), pa)
475 self.m.d.comb += pa.a.eq(self.sig)
476 return pa.output
477
478 # not needed: Value.implies does the job
479 # def implies(premise, conclusion):
480
481 # TODO. contains a Value.cast which means an override is needed (on both)
482 # def bit_select(self, offset, width):
483 # def word_select(self, offset, width):
484
485 # not needed: Value.matches, amazingly, should do the job
486 # def matches(self, *patterns):
487
488 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=713
489 def shape(self):
490 return self.sig.shape()