cpart_wid is just max(lane_shapes.values())
[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 def get_mask(self):
69 return list(self.psig.partpoints.values())
70 def get_switch(self):
71 return Cat(self.get_mask())
72 def get_cases(self):
73 return range(1<<len(self.get_mask()))
74 @property
75 def blanklanes(self):
76 return 0
77
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
84 # by layout()
85 class ElWidthPartType: # TODO decide name
86 def __init__(self, psig):
87 self.psig = psig
88 def get_mask(self):
89 ppoints, pbits = layout()
90 return ppoints.values() # i think
91 def get_switch(self):
92 return self.psig.elwidth
93 def get_cases(self):
94 ppoints, pbits = layout()
95 return pbits
96 @property
97 def blanklanes(self):
98 return 0 # TODO
99
100
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
112 else:
113 self.partpoints = make_partition2(mask, width)
114 self.ptype = PartType(self)
115
116 def set_module(self, m):
117 self.m = m
118
119 def get_modname(self, category):
120 modnames[category] += 1
121 return "%s_%d" % (category, modnames[category])
122
123 @staticmethod
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)
129 result.m = other.m
130 return result
131
132 def lower(self):
133 return self.sig
134
135 # nmigen-redirected constructs (Mux, Cat, Switch, Assign)
136
137 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=458
138 #def __Part__(self, offset, width, stride=1, *, src_loc_at=0):
139
140 def __Repl__(self, count, *, src_loc_at=0):
141 return PRepl(self.m, self, count, self.ptype)
142
143 def __Cat__(self, *args, src_loc_at=0):
144 args = [self] + list(args)
145 for sig in 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)
150
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)
157
158 def __Assign__(self, val, *, src_loc_at=0):
159 # print ("partsig ass", self, val)
160 return PAssign(self.m, self, val, self.ptype)
161
162 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=458
163 #def __Switch__(self, cases, *, src_loc=None, src_loc_at=0,
164 # case_src_locs={}):
165
166 # no override needed, Value.__bool__ sufficient
167 # def __bool__(self):
168
169 # unary ops that do not require partitioning
170
171 def __invert__(self):
172 result = SimdSignal.like(self)
173 self.m.d.comb += result.sig.eq(~self.sig)
174 return result
175
176 # unary ops that require partitioning
177
178 def __neg__(self):
179 z = Const(0, len(self.sig))
180 result, _ = self.sub_op(z, self)
181 return result
182
183 # binary ops that need partitioning
184
185 def add_op(self, op1, op2, carry):
186 op1 = getsig(op1)
187 op2 = getsig(op2)
188 pa = PartitionedAdder(len(op1), self.partpoints)
189 setattr(self.m.submodules, self.get_modname('add'), pa)
190 comb = self.m.d.comb
191 comb += pa.a.eq(op1)
192 comb += pa.b.eq(op2)
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
197
198 def sub_op(self, op1, op2, carry=~0):
199 op1 = getsig(op1)
200 op2 = getsig(op2)
201 pa = PartitionedAdder(len(op1), self.partpoints)
202 setattr(self.m.submodules, self.get_modname('add'), pa)
203 comb = self.m.d.comb
204 comb += pa.a.eq(op1)
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
210
211 def __add__(self, other):
212 result, _ = self.add_op(self, other, carry=0)
213 return result
214
215 def __radd__(self, other):
216 # https://bugs.libre-soc.org/show_bug.cgi?id=718
217 result, _ = self.add_op(other, self)
218 return result
219
220 def __sub__(self, other):
221 result, _ = self.sub_op(self, other)
222 return result
223
224 def __rsub__(self, other):
225 # https://bugs.libre-soc.org/show_bug.cgi?id=718
226 result, _ = self.sub_op(other, self)
227 return result
228
229 def __mul__(self, other):
230 raise NotImplementedError # too complicated at the moment
231 return Operator("*", [self, other])
232
233 def __rmul__(self, other):
234 raise NotImplementedError # too complicated at the moment
235 return Operator("*", [other, self])
236
237 # not needed: same as Value.__check_divisor
238 #def __check_divisor(self):
239
240 def __mod__(self, other):
241 raise NotImplementedError
242 other = Value.cast(other)
243 other.__check_divisor()
244 return Operator("%", [self, other])
245
246 def __rmod__(self, other):
247 raise NotImplementedError
248 self.__check_divisor()
249 return Operator("%", [other, self])
250
251 def __floordiv__(self, other):
252 raise NotImplementedError
253 other = Value.cast(other)
254 other.__check_divisor()
255 return Operator("//", [self, other])
256
257 def __rfloordiv__(self, other):
258 raise NotImplementedError
259 self.__check_divisor()
260 return Operator("//", [other, self])
261
262 # not needed: same as Value.__check_shamt
263 #def __check_shamt(self):
264
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):
269 op1 = getsig(op1)
270 if isinstance(op2, Const) or isinstance(op2, Signal):
271 scalar = True
272 pa = PartitionedScalarShift(len(op1), self.partpoints)
273 else:
274 scalar = False
275 op2 = getsig(op2)
276 pa = PartitionedDynamicShift(len(op1), self.partpoints)
277 # else:
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)
282 comb = self.m.d.comb
283 if scalar:
284 comb += pa.data.eq(op1)
285 comb += pa.shifter.eq(op2)
286 comb += pa.shift_right.eq(shr_flag)
287 else:
288 comb += pa.a.eq(op1)
289 comb += pa.b.eq(op2)
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)
294
295 def __lshift__(self, other):
296 z = Const(0, len(self.partpoints)+1)
297 result, _ = self.ls_op(self, other, carry=z) # TODO, carry
298 return result
299
300 def __rlshift__(self, other):
301 # https://bugs.libre-soc.org/show_bug.cgi?id=718
302 raise NotImplementedError
303 return Operator("<<", [other, self])
304
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
308 return result
309
310 def __rrshift__(self, other):
311 # https://bugs.libre-soc.org/show_bug.cgi?id=718
312 raise NotImplementedError
313 return Operator(">>", [other, self])
314
315 # binary ops that don't require partitioning
316
317 def __and__(self, other):
318 return applyop(self, other, and_)
319
320 def __rand__(self, other):
321 return applyop(other, self, and_)
322
323 def __or__(self, other):
324 return applyop(self, other, or_)
325
326 def __ror__(self, other):
327 return applyop(other, self, or_)
328
329 def __xor__(self, other):
330 return applyop(self, other, xor)
331
332 def __rxor__(self, other):
333 return applyop(other, self, xor)
334
335 # binary comparison ops that need partitioning
336
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)
341 comb = self.m.d.comb
342 comb += pa.opcode.eq(optype) # set opcode
343 if isinstance(op1, SimdSignal):
344 comb += pa.a.eq(op1.sig)
345 else:
346 comb += pa.a.eq(op1)
347 if isinstance(op2, SimdSignal):
348 comb += pa.b.eq(op2.sig)
349 else:
350 comb += pa.b.eq(op2)
351 return pa.output
352
353 def __eq__(self, other):
354 width = len(self.sig)
355 return self._compare(width, self, other, "eq", PartitionedEqGtGe.EQ)
356
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)
362 return ne
363
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)
368
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)
373
374 def __gt__(self, other):
375 width = len(self.sig)
376 return self._compare(width, self, other, "gt", PartitionedEqGtGe.GT)
377
378 def __ge__(self, other):
379 width = len(self.sig)
380 return self._compare(width, self, other, "ge", PartitionedEqGtGe.GE)
381
382 # no override needed: Value.__abs__ is general enough it does the job
383 # def __abs__(self):
384
385 def __len__(self):
386 return len(self.sig)
387
388 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=716
389 # def __getitem__(self, key):
390
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)
395 return result
396
397 # http://bugs.libre-riscv.org/show_bug.cgi?id=719
398 def as_unsigned(self):
399 return self.__new_sign(False)
400 def as_signed(self):
401 return self.__new_sign(True)
402
403 # useful operators
404
405 def bool(self):
406 """Conversion to boolean.
407
408 Returns
409 -------
410 Value, out
411 ``1`` if any bits are set, ``0`` otherwise.
412 """
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)
417 return pa.output
418
419 def any(self):
420 """Check if any bits are ``1``.
421
422 Returns
423 -------
424 Value, out
425 ``1`` if any bits are set, ``0`` otherwise.
426 """
427 return self != Const(0) # leverage the __ne__ operator here
428 return Operator("r|", [self])
429
430 def all(self):
431 """Check if all bits are ``1``.
432
433 Returns
434 -------
435 Value, out
436 ``1`` if all bits are set, ``0`` otherwise.
437 """
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)
444 #return pa.output
445 return self == Const(-1) # leverage the __eq__ operator here
446
447 def xor(self):
448 """Compute pairwise exclusive-or of every bit.
449
450 Returns
451 -------
452 Value, out
453 ``1`` if an odd number of bits are set, ``0`` if an
454 even number of bits are set.
455 """
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)
460 return pa.output
461
462 # not needed: Value.implies does the job
463 # def implies(premise, conclusion):
464
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):
468
469 # not needed: Value.matches, amazingly, should do the job
470 # def matches(self, *patterns):
471
472 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=713
473 def shape(self):
474 return self.sig.shape()