improve code-comments some more
[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 global modnames
52 modnames = {}
53 # for sub-modules to be created on-demand. Mux is done slightly
54 # differently (has its own global)
55 for name in ['add', 'eq', 'gt', 'ge', 'ls', 'xor', 'bool', 'all']:
56 modnames[name] = 0
57
58
59 # Prototype https://bugs.libre-soc.org/show_bug.cgi?id=713#c53
60 # this provides a "compatibility" layer with existing SimdSignal
61 # behaviour. the idea is that this interface defines which "combinations"
62 # of partition selections are relevant, and as an added bonus it says
63 # which partition lanes are completely irrelevant (padding, blank).
64 class PartType: # TODO decide name
65 def __init__(self, psig):
66 self.psig = psig
67 def get_mask(self):
68 return list(self.psig.partpoints.values())
69 def get_switch(self):
70 return Cat(self.get_mask())
71 def get_cases(self):
72 return range(1<<len(self.get_mask()))
73 @property
74 def blanklanes(self):
75 return 0
76
77 # this one would be an elwidth version
78 # see https://bugs.libre-soc.org/show_bug.cgi?id=713#c34
79 # it requires an "adapter" which is the layout() function
80 # where the PartitionPoints was *created* by the layout()
81 # function and this class then "understands" the relationship
82 # between elwidth and the PartitionPoints that were created
83 # by layout()
84 class ElWidthPartType: # TODO decide name
85 def __init__(self, psig):
86 self.psig = psig
87 def get_mask(self):
88 ppoints, pbits = layout()
89 return ppoints.values() # i think
90 def get_switch(self):
91 return self.psig.elwidth
92 def get_cases(self):
93 ppoints, pbits = layout()
94 return pbits
95 @property
96 def blanklanes(self):
97 return 0 # TODO
98
99
100 class SimdSignal(UserValue):
101 # XXX ################################################### XXX
102 # XXX Keep these functions in the same order as ast.Value XXX
103 # XXX ################################################### XXX
104 def __init__(self, mask, *args, src_loc_at=0, **kwargs):
105 super().__init__(src_loc_at=src_loc_at)
106 self.sig = Signal(*args, **kwargs)
107 width = len(self.sig) # get signal width
108 # create partition points
109 if isinstance(mask, PartitionPoints):
110 self.partpoints = mask
111 else:
112 self.partpoints = make_partition2(mask, width)
113 self.ptype = PartType(self)
114
115 def set_module(self, m):
116 self.m = m
117
118 def get_modname(self, category):
119 modnames[category] += 1
120 return "%s_%d" % (category, modnames[category])
121
122 @staticmethod
123 def like(other, *args, **kwargs):
124 """Builds a new SimdSignal with the same PartitionPoints and
125 Signal properties as the other"""
126 result = SimdSignal(PartitionPoints(other.partpoints))
127 result.sig = Signal.like(other.sig, *args, **kwargs)
128 result.m = other.m
129 return result
130
131 def lower(self):
132 return self.sig
133
134 # nmigen-redirected constructs (Mux, Cat, Switch, Assign)
135
136 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=458
137 #def __Part__(self, offset, width, stride=1, *, src_loc_at=0):
138
139 def __Repl__(self, count, *, src_loc_at=0):
140 return PRepl(self.m, self, count, self.ptype)
141
142 def __Cat__(self, *args, src_loc_at=0):
143 args = [self] + list(args)
144 for sig in args:
145 assert isinstance(sig, SimdSignal), \
146 "All SimdSignal.__Cat__ arguments must be " \
147 "a SimdSignal. %s is not." % repr(sig)
148 return PCat(self.m, args, self.ptype)
149
150 def __Mux__(self, val1, val2):
151 # print ("partsig mux", self, val1, val2)
152 assert len(val1) == len(val2), \
153 "SimdSignal width sources must be the same " \
154 "val1 == %d, val2 == %d" % (len(val1), len(val2))
155 return PMux(self.m, self.partpoints, self, val1, val2, self.ptype)
156
157 def __Assign__(self, val, *, src_loc_at=0):
158 # print ("partsig ass", self, val)
159 return PAssign(self.m, self, val, self.ptype)
160
161 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=458
162 #def __Switch__(self, cases, *, src_loc=None, src_loc_at=0,
163 # case_src_locs={}):
164
165 # no override needed, Value.__bool__ sufficient
166 # def __bool__(self):
167
168 # unary ops that do not require partitioning
169
170 def __invert__(self):
171 result = SimdSignal.like(self)
172 self.m.d.comb += result.sig.eq(~self.sig)
173 return result
174
175 # unary ops that require partitioning
176
177 def __neg__(self):
178 z = Const(0, len(self.sig))
179 result, _ = self.sub_op(z, self)
180 return result
181
182 # binary ops that need partitioning
183
184 def add_op(self, op1, op2, carry):
185 op1 = getsig(op1)
186 op2 = getsig(op2)
187 pa = PartitionedAdder(len(op1), self.partpoints)
188 setattr(self.m.submodules, self.get_modname('add'), pa)
189 comb = self.m.d.comb
190 comb += pa.a.eq(op1)
191 comb += pa.b.eq(op2)
192 comb += pa.carry_in.eq(carry)
193 result = SimdSignal.like(self)
194 comb += result.sig.eq(pa.output)
195 return result, pa.carry_out
196
197 def sub_op(self, op1, op2, carry=~0):
198 op1 = getsig(op1)
199 op2 = getsig(op2)
200 pa = PartitionedAdder(len(op1), self.partpoints)
201 setattr(self.m.submodules, self.get_modname('add'), pa)
202 comb = self.m.d.comb
203 comb += pa.a.eq(op1)
204 comb += pa.b.eq(~op2)
205 comb += pa.carry_in.eq(carry)
206 result = SimdSignal.like(self)
207 comb += result.sig.eq(pa.output)
208 return result, pa.carry_out
209
210 def __add__(self, other):
211 result, _ = self.add_op(self, other, carry=0)
212 return result
213
214 def __radd__(self, other):
215 # https://bugs.libre-soc.org/show_bug.cgi?id=718
216 result, _ = self.add_op(other, self)
217 return result
218
219 def __sub__(self, other):
220 result, _ = self.sub_op(self, other)
221 return result
222
223 def __rsub__(self, other):
224 # https://bugs.libre-soc.org/show_bug.cgi?id=718
225 result, _ = self.sub_op(other, self)
226 return result
227
228 def __mul__(self, other):
229 raise NotImplementedError # too complicated at the moment
230 return Operator("*", [self, other])
231
232 def __rmul__(self, other):
233 raise NotImplementedError # too complicated at the moment
234 return Operator("*", [other, self])
235
236 # not needed: same as Value.__check_divisor
237 #def __check_divisor(self):
238
239 def __mod__(self, other):
240 raise NotImplementedError
241 other = Value.cast(other)
242 other.__check_divisor()
243 return Operator("%", [self, other])
244
245 def __rmod__(self, other):
246 raise NotImplementedError
247 self.__check_divisor()
248 return Operator("%", [other, self])
249
250 def __floordiv__(self, other):
251 raise NotImplementedError
252 other = Value.cast(other)
253 other.__check_divisor()
254 return Operator("//", [self, other])
255
256 def __rfloordiv__(self, other):
257 raise NotImplementedError
258 self.__check_divisor()
259 return Operator("//", [other, self])
260
261 # not needed: same as Value.__check_shamt
262 #def __check_shamt(self):
263
264 # TODO: detect if the 2nd operand is a Const, a Signal or a
265 # SimdSignal. if it's a Const or a Signal, a global shift
266 # can occur. if it's a SimdSignal, that's much more interesting.
267 def ls_op(self, op1, op2, carry, shr_flag=0):
268 op1 = getsig(op1)
269 if isinstance(op2, Const) or isinstance(op2, Signal):
270 scalar = True
271 pa = PartitionedScalarShift(len(op1), self.partpoints)
272 else:
273 scalar = False
274 op2 = getsig(op2)
275 pa = PartitionedDynamicShift(len(op1), self.partpoints)
276 # else:
277 # TODO: case where the *shifter* is a SimdSignal but
278 # the thing *being* Shifted is a scalar (Signal, expression)
279 # https://bugs.libre-soc.org/show_bug.cgi?id=718
280 setattr(self.m.submodules, self.get_modname('ls'), pa)
281 comb = self.m.d.comb
282 if scalar:
283 comb += pa.data.eq(op1)
284 comb += pa.shifter.eq(op2)
285 comb += pa.shift_right.eq(shr_flag)
286 else:
287 comb += pa.a.eq(op1)
288 comb += pa.b.eq(op2)
289 comb += pa.shift_right.eq(shr_flag)
290 # XXX TODO: carry-in, carry-out (for arithmetic shift)
291 #comb += pa.carry_in.eq(carry)
292 return (pa.output, 0)
293
294 def __lshift__(self, other):
295 z = Const(0, len(self.partpoints)+1)
296 result, _ = self.ls_op(self, other, carry=z) # TODO, carry
297 return result
298
299 def __rlshift__(self, other):
300 # https://bugs.libre-soc.org/show_bug.cgi?id=718
301 raise NotImplementedError
302 return Operator("<<", [other, self])
303
304 def __rshift__(self, other):
305 z = Const(0, len(self.partpoints)+1)
306 result, _ = self.ls_op(self, other, carry=z, shr_flag=1) # TODO, carry
307 return result
308
309 def __rrshift__(self, other):
310 # https://bugs.libre-soc.org/show_bug.cgi?id=718
311 raise NotImplementedError
312 return Operator(">>", [other, self])
313
314 # binary ops that don't require partitioning
315
316 def __and__(self, other):
317 return applyop(self, other, and_)
318
319 def __rand__(self, other):
320 return applyop(other, self, and_)
321
322 def __or__(self, other):
323 return applyop(self, other, or_)
324
325 def __ror__(self, other):
326 return applyop(other, self, or_)
327
328 def __xor__(self, other):
329 return applyop(self, other, xor)
330
331 def __rxor__(self, other):
332 return applyop(other, self, xor)
333
334 # binary comparison ops that need partitioning
335
336 def _compare(self, width, op1, op2, opname, optype):
337 # print (opname, op1, op2)
338 pa = PartitionedEqGtGe(width, self.partpoints)
339 setattr(self.m.submodules, self.get_modname(opname), pa)
340 comb = self.m.d.comb
341 comb += pa.opcode.eq(optype) # set opcode
342 if isinstance(op1, SimdSignal):
343 comb += pa.a.eq(op1.sig)
344 else:
345 comb += pa.a.eq(op1)
346 if isinstance(op2, SimdSignal):
347 comb += pa.b.eq(op2.sig)
348 else:
349 comb += pa.b.eq(op2)
350 return pa.output
351
352 def __eq__(self, other):
353 width = len(self.sig)
354 return self._compare(width, self, other, "eq", PartitionedEqGtGe.EQ)
355
356 def __ne__(self, other):
357 width = len(self.sig)
358 eq = self._compare(width, self, other, "eq", PartitionedEqGtGe.EQ)
359 ne = Signal(eq.width)
360 self.m.d.comb += ne.eq(~eq)
361 return ne
362
363 def __lt__(self, other):
364 width = len(self.sig)
365 # swap operands, use gt to do lt
366 return self._compare(width, other, self, "gt", PartitionedEqGtGe.GT)
367
368 def __le__(self, other):
369 width = len(self.sig)
370 # swap operands, use ge to do le
371 return self._compare(width, other, self, "ge", PartitionedEqGtGe.GE)
372
373 def __gt__(self, other):
374 width = len(self.sig)
375 return self._compare(width, self, other, "gt", PartitionedEqGtGe.GT)
376
377 def __ge__(self, other):
378 width = len(self.sig)
379 return self._compare(width, self, other, "ge", PartitionedEqGtGe.GE)
380
381 # no override needed: Value.__abs__ is general enough it does the job
382 # def __abs__(self):
383
384 def __len__(self):
385 return len(self.sig)
386
387 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=716
388 # def __getitem__(self, key):
389
390 def __new_sign(self, signed):
391 shape = Shape(len(self), signed=signed)
392 result = SimdSignal.like(self, shape=shape)
393 self.m.d.comb += result.sig.eq(self.sig)
394 return result
395
396 # http://bugs.libre-riscv.org/show_bug.cgi?id=719
397 def as_unsigned(self):
398 return self.__new_sign(False)
399 def as_signed(self):
400 return self.__new_sign(True)
401
402 # useful operators
403
404 def bool(self):
405 """Conversion to boolean.
406
407 Returns
408 -------
409 Value, out
410 ``1`` if any bits are set, ``0`` otherwise.
411 """
412 width = len(self.sig)
413 pa = PartitionedBool(width, self.partpoints)
414 setattr(self.m.submodules, self.get_modname("bool"), pa)
415 self.m.d.comb += pa.a.eq(self.sig)
416 return pa.output
417
418 def any(self):
419 """Check if any bits are ``1``.
420
421 Returns
422 -------
423 Value, out
424 ``1`` if any bits are set, ``0`` otherwise.
425 """
426 return self != Const(0) # leverage the __ne__ operator here
427 return Operator("r|", [self])
428
429 def all(self):
430 """Check if all bits are ``1``.
431
432 Returns
433 -------
434 Value, out
435 ``1`` if all bits are set, ``0`` otherwise.
436 """
437 # something wrong with PartitionedAll, but self == Const(-1)"
438 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=176#c17
439 #width = len(self.sig)
440 #pa = PartitionedAll(width, self.partpoints)
441 #setattr(self.m.submodules, self.get_modname("all"), pa)
442 #self.m.d.comb += pa.a.eq(self.sig)
443 #return pa.output
444 return self == Const(-1) # leverage the __eq__ operator here
445
446 def xor(self):
447 """Compute pairwise exclusive-or of every bit.
448
449 Returns
450 -------
451 Value, out
452 ``1`` if an odd number of bits are set, ``0`` if an
453 even number of bits are set.
454 """
455 width = len(self.sig)
456 pa = PartitionedXOR(width, self.partpoints)
457 setattr(self.m.submodules, self.get_modname("xor"), pa)
458 self.m.d.comb += pa.a.eq(self.sig)
459 return pa.output
460
461 # not needed: Value.implies does the job
462 # def implies(premise, conclusion):
463
464 # TODO. contains a Value.cast which means an override is needed (on both)
465 # def bit_select(self, offset, width):
466 # def word_select(self, offset, width):
467
468 # not needed: Value.matches, amazingly, should do the job
469 # def matches(self, *patterns):
470
471 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=713
472 def shape(self):
473 return self.sig.shape()