33cc5feac86dda735d36623de2e815c45f5854b9
[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_shift.part_shift_dynamic import PartitionedDynamicShift
22 from ieee754.part_shift.part_shift_scalar import PartitionedScalarShift
23 from ieee754.part_mul_add.partpoints import make_partition
24 from operator import or_, xor, and_, not_
25
26 from nmigen import (Signal, Const)
27
28
29 def getsig(op1):
30 if isinstance(op1, PartitionedSignal):
31 op1 = op1.sig
32 return op1
33
34
35 def applyop(op1, op2, op):
36 return op(getsig(op1), getsig(op2))
37
38
39 class PartitionedSignal:
40 def __init__(self, mask, *args, **kwargs):
41 self.sig = Signal(*args, **kwargs)
42 width = self.sig.shape()[0] # get signal width
43 # create partition points
44 self.partpoints = make_partition(mask, width)
45 self.modnames = {}
46 for name in ['add', 'eq', 'gt', 'ge', 'ls']:
47 self.modnames[name] = 0
48
49 def set_module(self, m):
50 self.m = m
51
52 def get_modname(self, category):
53 self.modnames[category] += 1
54 return "%s_%d" % (category, self.modnames[category])
55
56 def eq(self, val):
57 return self.sig.eq(getsig(val))
58
59 # unary ops that do not require partitioning
60
61 def __invert__(self):
62 return ~self.sig
63
64 # unary ops that require partitioning
65
66 def __neg__(self):
67 z = Const(0, len(self.partpoints)+1)
68 result, _ = self.add_op(self, ~0, carry=z) # TODO, subop
69 return result
70
71 # binary ops that don't require partitioning
72
73 def __and__(self, other):
74 return applyop(self, other, and_)
75
76 def __rand__(self, other):
77 return applyop(other, self, and_)
78
79 def __or__(self, other):
80 return applyop(self, other, or_)
81
82 def __ror__(self, other):
83 return applyop(other, self, or_)
84
85 def __xor__(self, other):
86 return applyop(self, other, xor)
87
88 def __rxor__(self, other):
89 return applyop(other, self, xor)
90
91 # binary ops that need partitioning
92
93 # TODO: detect if the 2nd operand is a Const, a Signal or a
94 # PartitionedSignal. if it's a Const or a Signal, a global shift
95 # can occur. if it's a PartitionedSignal, that's much more interesting.
96 def ls_op(self, op1, op2, carry):
97 op1 = getsig(op1)
98 if isinstance(op2, Const) or isinstance(op2, Signal):
99 scalar = True
100 shape = op1.shape()
101 pa = PartitionedScalarShift(shape[0], self.partpoints)
102 else:
103 scalar = False
104 op2 = getsig(op2)
105 shape = op1.shape()
106 pa = PartitionedDynamicShift(shape[0], self.partpoints)
107 setattr(self.m.submodules, self.get_modname('ls'), pa)
108 comb = self.m.d.comb
109 if scalar:
110 comb += pa.data.eq(op1)
111 comb += pa.shifter.eq(op2)
112 else:
113 comb += pa.a.eq(op1)
114 comb += pa.b.eq(op2)
115 # XXX TODO: carry-in, carry-out
116 #comb += pa.carry_in.eq(carry)
117 return (pa.output, 0)
118
119 def __lshift__(self, other):
120 z = Const(0, len(self.partpoints)+1)
121 result, _ = self.ls_op(self, other, carry=z) # TODO, carry
122 return result
123
124 def __rlshift__(self, other):
125 raise NotImplementedError
126 return Operator("<<", [other, self])
127
128 def __rshift__(self, other):
129 raise NotImplementedError
130 return Operator(">>", [self, other])
131
132 def __rrshift__(self, other):
133 raise NotImplementedError
134 return Operator(">>", [other, self])
135
136 def add_op(self, op1, op2, carry):
137 op1 = getsig(op1)
138 op2 = getsig(op2)
139 shape = op1.shape()
140 pa = PartitionedAdder(shape[0], self.partpoints)
141 setattr(self.m.submodules, self.get_modname('add'), pa)
142 comb = self.m.d.comb
143 comb += pa.a.eq(op1)
144 comb += pa.b.eq(op2)
145 comb += pa.carry_in.eq(carry)
146 return (pa.output, pa.carry_out)
147
148 def sub_op(self, op1, op2, carry=~0):
149 op1 = getsig(op1)
150 op2 = getsig(op2)
151 shape = op1.shape()
152 pa = PartitionedAdder(shape[0], self.partpoints)
153 setattr(self.m.submodules, self.get_modname('add'), pa)
154 comb = self.m.d.comb
155 comb += pa.a.eq(op1)
156 comb += pa.b.eq(~op2)
157 comb += pa.carry_in.eq(carry)
158 return (pa.output, pa.carry_out)
159
160 def __add__(self, other):
161 result, _ = self.add_op(self, other, carry=0)
162 return result
163
164 def __radd__(self, other):
165 result, _ = self.add_op(other, self)
166 return result
167
168 def __sub__(self, other):
169 result, _ = self.sub_op(self, other)
170 return result
171
172 def __rsub__(self, other):
173 result, _ = self.sub_op(other, self)
174 return result
175
176 def __mul__(self, other):
177 return Operator("*", [self, other])
178
179 def __rmul__(self, other):
180 return Operator("*", [other, self])
181
182 def __check_divisor(self):
183 width, signed = self.shape()
184 if signed:
185 # Python's division semantics and Verilog's division semantics
186 # differ for negative divisors (Python uses div/mod, Verilog
187 # uses quo/rem); for now, avoid the issue
188 # completely by prohibiting such division operations.
189 raise NotImplementedError(
190 "Division by a signed value is not supported")
191
192 def __mod__(self, other):
193 raise NotImplementedError
194 other = Value.cast(other)
195 other.__check_divisor()
196 return Operator("%", [self, other])
197
198 def __rmod__(self, other):
199 raise NotImplementedError
200 self.__check_divisor()
201 return Operator("%", [other, self])
202
203 def __floordiv__(self, other):
204 raise NotImplementedError
205 other = Value.cast(other)
206 other.__check_divisor()
207 return Operator("//", [self, other])
208
209 def __rfloordiv__(self, other):
210 raise NotImplementedError
211 self.__check_divisor()
212 return Operator("//", [other, self])
213
214 # binary comparison ops that need partitioning
215
216 def _compare(self, width, op1, op2, opname, optype):
217 # print (opname, op1, op2)
218 pa = PartitionedEqGtGe(width, self.partpoints)
219 setattr(self.m.submodules, self.get_modname(opname), pa)
220 comb = self.m.d.comb
221 comb += pa.opcode.eq(optype) # set opcode
222 if isinstance(op1, PartitionedSignal):
223 comb += pa.a.eq(op1.sig)
224 else:
225 comb += pa.a.eq(op1)
226 if isinstance(op2, PartitionedSignal):
227 comb += pa.b.eq(op2.sig)
228 else:
229 comb += pa.b.eq(op2)
230 return pa.output
231
232 def __eq__(self, other):
233 width = self.sig.shape()[0]
234 return self._compare(width, self, other, "eq", PartitionedEqGtGe.EQ)
235
236 def __ne__(self, other):
237 width = self.sig.shape()[0]
238 eq = self._compare(width, self, other, "eq", PartitionedEqGtGe.EQ)
239 ne = Signal(eq.width)
240 self.m.d.comb += ne.eq(~eq)
241 return ne
242
243 def __gt__(self, other):
244 width = self.sig.shape()[0]
245 return self._compare(width, self, other, "gt", PartitionedEqGtGe.GT)
246
247 def __lt__(self, other):
248 width = self.sig.shape()[0]
249 return self._compare(width, other, self, "gt", PartitionedEqGtGe.GT)
250
251 def __ge__(self, other):
252 width = self.sig.shape()[0]
253 return self._compare(width, self, other, "ge", PartitionedEqGtGe.GE)
254
255 def __le__(self, other):
256 width = self.sig.shape()[0]
257 return self._compare(width, other, self, "ge", PartitionedEqGtGe.GE)
258
259 # useful operators
260
261 def bool(self):
262 """Conversion to boolean.
263
264 Returns
265 -------
266 Value, out
267 ``1`` if any bits are set, ``0`` otherwise.
268 """
269 raise NotImplementedError
270 return Operator("b", [self])
271
272 def any(self):
273 """Check if any bits are ``1``.
274
275 Returns
276 -------
277 Value, out
278 ``1`` if any bits are set, ``0`` otherwise.
279 """
280 raise NotImplementedError
281 return Operator("r|", [self])
282
283 def all(self):
284 """Check if all bits are ``1``.
285
286 Returns
287 -------
288 Value, out
289 ``1`` if all bits are set, ``0`` otherwise.
290 """
291 raise NotImplementedError
292 return Operator("r&", [self])
293
294 def xor(self):
295 """Compute pairwise exclusive-or of every bit.
296
297 Returns
298 -------
299 Value, out
300 ``1`` if an odd number of bits are set, ``0`` if an
301 even number of bits are set.
302 """
303 # XXXX TODO: return partition-mask-sized set of bits
304 raise NotImplementedError
305 return Operator("r^", [self])
306
307 def implies(premise, conclusion):
308 """Implication.
309
310 Returns
311 -------
312 Value, out
313 ``0`` if ``premise`` is true and ``conclusion`` is not,
314 ``1`` otherwise.
315 """
316 # amazingly, this should actually work.
317 return ~premise | conclusion