zero carry-in on __neg__
[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, self.sig.shape())
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 result, _ = self.ls_op(self, other, carry=0)
121 return result
122
123 def __rlshift__(self, other):
124 raise NotImplementedError
125 return Operator("<<", [other, self])
126
127 def __rshift__(self, other):
128 raise NotImplementedError
129 return Operator(">>", [self, other])
130
131 def __rrshift__(self, other):
132 raise NotImplementedError
133 return Operator(">>", [other, self])
134
135 def add_op(self, op1, op2, carry):
136 op1 = getsig(op1)
137 op2 = getsig(op2)
138 shape = op1.shape()
139 pa = PartitionedAdder(shape[0], self.partpoints)
140 setattr(self.m.submodules, self.get_modname('add'), pa)
141 comb = self.m.d.comb
142 comb += pa.a.eq(op1)
143 comb += pa.b.eq(op2)
144 comb += pa.carry_in.eq(carry)
145 return (pa.output, pa.carry_out)
146
147 def sub_op(self, op1, op2, carry=~0):
148 op1 = getsig(op1)
149 op2 = getsig(op2)
150 shape = op1.shape()
151 pa = PartitionedAdder(shape[0], self.partpoints)
152 setattr(self.m.submodules, self.get_modname('add'), pa)
153 comb = self.m.d.comb
154 comb += pa.a.eq(op1)
155 comb += pa.b.eq(~op2)
156 comb += pa.carry_in.eq(carry)
157 return (pa.output, pa.carry_out)
158
159 def __add__(self, other):
160 result, _ = self.add_op(self, other, carry=0)
161 return result
162
163 def __radd__(self, other):
164 result, _ = self.add_op(other, self)
165 return result
166
167 def __sub__(self, other):
168 result, _ = self.sub_op(self, other)
169 return result
170
171 def __rsub__(self, other):
172 result, _ = self.sub_op(other, self)
173 return result
174
175 def __mul__(self, other):
176 return Operator("*", [self, other])
177
178 def __rmul__(self, other):
179 return Operator("*", [other, self])
180
181 def __check_divisor(self):
182 width, signed = self.shape()
183 if signed:
184 # Python's division semantics and Verilog's division semantics
185 # differ for negative divisors (Python uses div/mod, Verilog
186 # uses quo/rem); for now, avoid the issue
187 # completely by prohibiting such division operations.
188 raise NotImplementedError(
189 "Division by a signed value is not supported")
190
191 def __mod__(self, other):
192 raise NotImplementedError
193 other = Value.cast(other)
194 other.__check_divisor()
195 return Operator("%", [self, other])
196
197 def __rmod__(self, other):
198 raise NotImplementedError
199 self.__check_divisor()
200 return Operator("%", [other, self])
201
202 def __floordiv__(self, other):
203 raise NotImplementedError
204 other = Value.cast(other)
205 other.__check_divisor()
206 return Operator("//", [self, other])
207
208 def __rfloordiv__(self, other):
209 raise NotImplementedError
210 self.__check_divisor()
211 return Operator("//", [other, self])
212
213 # binary comparison ops that need partitioning
214
215 def _compare(self, width, op1, op2, opname, optype):
216 # print (opname, op1, op2)
217 pa = PartitionedEqGtGe(width, self.partpoints)
218 setattr(self.m.submodules, self.get_modname(opname), pa)
219 comb = self.m.d.comb
220 comb += pa.opcode.eq(optype) # set opcode
221 if isinstance(op1, PartitionedSignal):
222 comb += pa.a.eq(op1.sig)
223 else:
224 comb += pa.a.eq(op1)
225 if isinstance(op2, PartitionedSignal):
226 comb += pa.b.eq(op2.sig)
227 else:
228 comb += pa.b.eq(op2)
229 return pa.output
230
231 def __eq__(self, other):
232 width = self.sig.shape()[0]
233 return self._compare(width, self, other, "eq", PartitionedEqGtGe.EQ)
234
235 def __ne__(self, other):
236 width = self.sig.shape()[0]
237 eq = self._compare(width, self, other, "eq", PartitionedEqGtGe.EQ)
238 ne = Signal(eq.width)
239 self.m.d.comb += ne.eq(~eq)
240 return ne
241
242 def __gt__(self, other):
243 width = self.sig.shape()[0]
244 return self._compare(width, self, other, "gt", PartitionedEqGtGe.GT)
245
246 def __lt__(self, other):
247 width = self.sig.shape()[0]
248 return self._compare(width, other, self, "gt", PartitionedEqGtGe.GT)
249
250 def __ge__(self, other):
251 width = self.sig.shape()[0]
252 return self._compare(width, self, other, "ge", PartitionedEqGtGe.GE)
253
254 def __le__(self, other):
255 width = self.sig.shape()[0]
256 return self._compare(width, other, self, "ge", PartitionedEqGtGe.GE)
257
258 # useful operators
259
260 def bool(self):
261 """Conversion to boolean.
262
263 Returns
264 -------
265 Value, out
266 ``1`` if any bits are set, ``0`` otherwise.
267 """
268 raise NotImplementedError
269 return Operator("b", [self])
270
271 def any(self):
272 """Check if any bits are ``1``.
273
274 Returns
275 -------
276 Value, out
277 ``1`` if any bits are set, ``0`` otherwise.
278 """
279 raise NotImplementedError
280 return Operator("r|", [self])
281
282 def all(self):
283 """Check if all bits are ``1``.
284
285 Returns
286 -------
287 Value, out
288 ``1`` if all bits are set, ``0`` otherwise.
289 """
290 raise NotImplementedError
291 return Operator("r&", [self])
292
293 def xor(self):
294 """Compute pairwise exclusive-or of every bit.
295
296 Returns
297 -------
298 Value, out
299 ``1`` if an odd number of bits are set, ``0`` if an
300 even number of bits are set.
301 """
302 # XXXX TODO: return partition-mask-sized set of bits
303 raise NotImplementedError
304 return Operator("r^", [self])
305
306 def implies(premise, conclusion):
307 """Implication.
308
309 Returns
310 -------
311 Value, out
312 ``0`` if ``premise`` is true and ``conclusion`` is not,
313 ``1`` otherwise.
314 """
315 # amazingly, this should actually work.
316 return ~premise | conclusion