disable mul and rmul in PartitionedSignal for now
[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 PartitionedSignal 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 operator import or_, xor, and_, not_
31
32 from nmigen import (Signal, Const)
33 from nmigen.hdl.ast import UserValue
34
35
36 def getsig(op1):
37 if isinstance(op1, PartitionedSignal):
38 op1 = op1.sig
39 return op1
40
41
42 def applyop(op1, op2, op):
43 if isinstance(op1, PartitionedSignal):
44 result = PartitionedSignal.like(op1)
45 else:
46 result = PartitionedSignal.like(op2)
47 result.m.d.comb += result.sig.eq(op(getsig(op1), getsig(op2)))
48 return result
49
50 global modnames
51 modnames = {}
52 # for sub-modules to be created on-demand. Mux is done slightly
53 # differently (has its own global)
54 for name in ['add', 'eq', 'gt', 'ge', 'ls', 'xor', 'bool', 'all']:
55 modnames[name] = 0
56
57
58 class PartitionedSignal(UserValue):
59 def __init__(self, mask, *args, src_loc_at=0, **kwargs):
60 super().__init__(src_loc_at=src_loc_at)
61 self.sig = Signal(*args, **kwargs)
62 width = len(self.sig) # get signal width
63 # create partition points
64 if isinstance(mask, PartitionPoints):
65 self.partpoints = mask
66 else:
67 self.partpoints = make_partition2(mask, width)
68
69
70 def set_module(self, m):
71 self.m = m
72
73 def get_modname(self, category):
74 modnames[category] += 1
75 return "%s_%d" % (category, modnames[category])
76
77 @staticmethod
78 def like(other, *args, **kwargs):
79 """Builds a new PartitionedSignal with the same PartitionPoints and
80 Signal properties as the other"""
81 result = PartitionedSignal(PartitionPoints(other.partpoints))
82 result.sig = Signal.like(other.sig, *args, **kwargs)
83 result.m = other.m
84 return result
85
86 def __len__(self):
87 return len(self.sig)
88 def shape(self):
89 return self.sig.shape()
90 def lower(self):
91 return self.sig
92 # now using __Assign__
93 #def eq(self, val):
94 # return self.sig.eq(getsig(val))
95
96 # nmigen-redirected constructs (Mux, Cat, Switch, Assign)
97
98 def __Mux__(self, val1, val2):
99 # print ("partsig mux", self, val1, val2)
100 assert len(val1) == len(val2), \
101 "PartitionedSignal width sources must be the same " \
102 "val1 == %d, val2 == %d" % (len(val1), len(val2))
103 return PMux(self.m, self.partpoints, self, val1, val2)
104
105 def __Assign__(self, val, *, src_loc_at=0):
106 # print ("partsig ass", self, val)
107 return PAssign(self.m, self, val, self.partpoints)
108
109 def __Cat__(self, *args, src_loc_at=0):
110 args = [self] + list(args)
111 for sig in args:
112 assert isinstance(sig, PartitionedSignal), \
113 "All PartitionedSignal.__Cat__ arguments must be " \
114 "a PartitionedSignal. %s is not." % repr(sig)
115 return PCat(self.m, args, self.partpoints)
116
117 # unary ops that do not require partitioning
118
119 def __invert__(self):
120 result = PartitionedSignal.like(self)
121 self.m.d.comb += result.sig.eq(~self.sig)
122 return result
123
124 # unary ops that require partitioning
125
126 def __neg__(self):
127 z = Const(0, len(self.sig))
128 result, _ = self.sub_op(z, self)
129 return result
130
131 # binary ops that don't require partitioning
132
133 def __and__(self, other):
134 return applyop(self, other, and_)
135
136 def __rand__(self, other):
137 return applyop(other, self, and_)
138
139 def __or__(self, other):
140 return applyop(self, other, or_)
141
142 def __ror__(self, other):
143 return applyop(other, self, or_)
144
145 def __xor__(self, other):
146 return applyop(self, other, xor)
147
148 def __rxor__(self, other):
149 return applyop(other, self, xor)
150
151 # binary ops that need partitioning
152
153 # TODO: detect if the 2nd operand is a Const, a Signal or a
154 # PartitionedSignal. if it's a Const or a Signal, a global shift
155 # can occur. if it's a PartitionedSignal, that's much more interesting.
156 def ls_op(self, op1, op2, carry, shr_flag=0):
157 op1 = getsig(op1)
158 if isinstance(op2, Const) or isinstance(op2, Signal):
159 scalar = True
160 pa = PartitionedScalarShift(len(op1), self.partpoints)
161 else:
162 scalar = False
163 op2 = getsig(op2)
164 pa = PartitionedDynamicShift(len(op1), self.partpoints)
165 # else:
166 # TODO: case where the *shifter* is a PartitionedSignal but
167 # the thing *being* Shifted is a scalar (Signal, expression)
168 # https://bugs.libre-soc.org/show_bug.cgi?id=718
169 setattr(self.m.submodules, self.get_modname('ls'), pa)
170 comb = self.m.d.comb
171 if scalar:
172 comb += pa.data.eq(op1)
173 comb += pa.shifter.eq(op2)
174 comb += pa.shift_right.eq(shr_flag)
175 else:
176 comb += pa.a.eq(op1)
177 comb += pa.b.eq(op2)
178 comb += pa.shift_right.eq(shr_flag)
179 # XXX TODO: carry-in, carry-out (for arithmetic shift)
180 #comb += pa.carry_in.eq(carry)
181 return (pa.output, 0)
182
183 def __lshift__(self, other):
184 z = Const(0, len(self.partpoints)+1)
185 result, _ = self.ls_op(self, other, carry=z) # TODO, carry
186 return result
187
188 def __rlshift__(self, other):
189 # https://bugs.libre-soc.org/show_bug.cgi?id=718
190 raise NotImplementedError
191 return Operator("<<", [other, self])
192
193 def __rshift__(self, other):
194 z = Const(0, len(self.partpoints)+1)
195 result, _ = self.ls_op(self, other, carry=z, shr_flag=1) # TODO, carry
196 return result
197
198 def __rrshift__(self, other):
199 # https://bugs.libre-soc.org/show_bug.cgi?id=718
200 raise NotImplementedError
201 return Operator(">>", [other, self])
202
203 def add_op(self, op1, op2, carry):
204 op1 = getsig(op1)
205 op2 = getsig(op2)
206 pa = PartitionedAdder(len(op1), self.partpoints)
207 setattr(self.m.submodules, self.get_modname('add'), pa)
208 comb = self.m.d.comb
209 comb += pa.a.eq(op1)
210 comb += pa.b.eq(op2)
211 comb += pa.carry_in.eq(carry)
212 result = PartitionedSignal.like(self)
213 comb += result.sig.eq(pa.output)
214 return result, pa.carry_out
215
216 def sub_op(self, op1, op2, carry=~0):
217 op1 = getsig(op1)
218 op2 = getsig(op2)
219 pa = PartitionedAdder(len(op1), self.partpoints)
220 setattr(self.m.submodules, self.get_modname('add'), pa)
221 comb = self.m.d.comb
222 comb += pa.a.eq(op1)
223 comb += pa.b.eq(~op2)
224 comb += pa.carry_in.eq(carry)
225 result = PartitionedSignal.like(self)
226 comb += result.sig.eq(pa.output)
227 return result, pa.carry_out
228
229 def __add__(self, other):
230 result, _ = self.add_op(self, other, carry=0)
231 return result
232
233 def __radd__(self, other):
234 # https://bugs.libre-soc.org/show_bug.cgi?id=718
235 result, _ = self.add_op(other, self)
236 return result
237
238 def __sub__(self, other):
239 result, _ = self.sub_op(self, other)
240 return result
241
242 def __rsub__(self, other):
243 # https://bugs.libre-soc.org/show_bug.cgi?id=718
244 result, _ = self.sub_op(other, self)
245 return result
246
247 def __mul__(self, other):
248 raise NotImplementedError # too complicated at the moment
249 return Operator("*", [self, other])
250
251 def __rmul__(self, other):
252 raise NotImplementedError # too complicated at the moment
253 return Operator("*", [other, self])
254
255 def __check_divisor(self):
256 width, signed = self.shape()
257 if signed:
258 # Python's division semantics and Verilog's division semantics
259 # differ for negative divisors (Python uses div/mod, Verilog
260 # uses quo/rem); for now, avoid the issue
261 # completely by prohibiting such division operations.
262 raise NotImplementedError(
263 "Division by a signed value is not supported")
264
265 def __mod__(self, other):
266 raise NotImplementedError
267 other = Value.cast(other)
268 other.__check_divisor()
269 return Operator("%", [self, other])
270
271 def __rmod__(self, other):
272 raise NotImplementedError
273 self.__check_divisor()
274 return Operator("%", [other, self])
275
276 def __floordiv__(self, other):
277 raise NotImplementedError
278 other = Value.cast(other)
279 other.__check_divisor()
280 return Operator("//", [self, other])
281
282 def __rfloordiv__(self, other):
283 raise NotImplementedError
284 self.__check_divisor()
285 return Operator("//", [other, self])
286
287 # binary comparison ops that need partitioning
288
289 def _compare(self, width, op1, op2, opname, optype):
290 # print (opname, op1, op2)
291 pa = PartitionedEqGtGe(width, self.partpoints)
292 setattr(self.m.submodules, self.get_modname(opname), pa)
293 comb = self.m.d.comb
294 comb += pa.opcode.eq(optype) # set opcode
295 if isinstance(op1, PartitionedSignal):
296 comb += pa.a.eq(op1.sig)
297 else:
298 comb += pa.a.eq(op1)
299 if isinstance(op2, PartitionedSignal):
300 comb += pa.b.eq(op2.sig)
301 else:
302 comb += pa.b.eq(op2)
303 return pa.output
304
305 def __eq__(self, other):
306 width = len(self.sig)
307 return self._compare(width, self, other, "eq", PartitionedEqGtGe.EQ)
308
309 def __ne__(self, other):
310 width = len(self.sig)
311 eq = self._compare(width, self, other, "eq", PartitionedEqGtGe.EQ)
312 ne = Signal(eq.width)
313 self.m.d.comb += ne.eq(~eq)
314 return ne
315
316 def __gt__(self, other):
317 width = len(self.sig)
318 return self._compare(width, self, other, "gt", PartitionedEqGtGe.GT)
319
320 def __lt__(self, other):
321 width = len(self.sig)
322 # swap operands, use gt to do lt
323 return self._compare(width, other, self, "gt", PartitionedEqGtGe.GT)
324
325 def __ge__(self, other):
326 width = len(self.sig)
327 return self._compare(width, self, other, "ge", PartitionedEqGtGe.GE)
328
329 def __le__(self, other):
330 width = len(self.sig)
331 # swap operands, use ge to do le
332 return self._compare(width, other, self, "ge", PartitionedEqGtGe.GE)
333
334 # useful operators
335
336 def bool(self):
337 """Conversion to boolean.
338
339 Returns
340 -------
341 Value, out
342 ``1`` if any bits are set, ``0`` otherwise.
343 """
344 width = len(self.sig)
345 pa = PartitionedBool(width, self.partpoints)
346 setattr(self.m.submodules, self.get_modname("bool"), pa)
347 self.m.d.comb += pa.a.eq(self.sig)
348 return pa.output
349
350 def any(self):
351 """Check if any bits are ``1``.
352
353 Returns
354 -------
355 Value, out
356 ``1`` if any bits are set, ``0`` otherwise.
357 """
358 return self != Const(0) # leverage the __ne__ operator here
359 return Operator("r|", [self])
360
361 def all(self):
362 """Check if all bits are ``1``.
363
364 Returns
365 -------
366 Value, out
367 ``1`` if all bits are set, ``0`` otherwise.
368 """
369 # something wrong with PartitionedAll, but self == Const(-1)"
370 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=176#c17
371 #width = len(self.sig)
372 #pa = PartitionedAll(width, self.partpoints)
373 #setattr(self.m.submodules, self.get_modname("all"), pa)
374 #self.m.d.comb += pa.a.eq(self.sig)
375 #return pa.output
376 return self == Const(-1) # leverage the __eq__ operator here
377
378 def xor(self):
379 """Compute pairwise exclusive-or of every bit.
380
381 Returns
382 -------
383 Value, out
384 ``1`` if an odd number of bits are set, ``0`` if an
385 even number of bits are set.
386 """
387 width = len(self.sig)
388 pa = PartitionedXOR(width, self.partpoints)
389 setattr(self.m.submodules, self.get_modname("xor"), pa)
390 self.m.d.comb += pa.a.eq(self.sig)
391 return pa.output
392
393 def implies(premise, conclusion):
394 """Implication.
395
396 Returns
397 -------
398 Value, out
399 ``0`` if ``premise`` is true and ``conclusion`` is not,
400 ``1`` otherwise.
401 """
402 # amazingly, this should actually work.
403 return ~premise | conclusion