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