2c5153ed5d33f71fb516b14be4fc872dab555f79
[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 ieee754.part.simd_scope import SimdScope
32 from ieee754.part.layout_experiment import layout
33 from operator import or_, xor, and_, not_
34
35 from nmigen import (Signal, Const, Cat)
36 from nmigen.hdl.ast import UserValue, Shape
37
38
39 def getsig(op1):
40 if isinstance(op1, SimdSignal):
41 op1 = op1.sig
42 return op1
43
44
45 def applyop(op1, op2, op):
46 if isinstance(op1, SimdSignal):
47 result = SimdSignal.like(op1)
48 else:
49 result = SimdSignal.like(op2)
50 result.m.d.comb += result.sig.eq(op(getsig(op1), getsig(op2)))
51 return result
52
53
54 global modnames
55 modnames = {}
56 # for sub-modules to be created on-demand. Mux is done slightly
57 # differently (has its own global)
58 for name in ['add', 'eq', 'gt', 'ge', 'ls', 'xor', 'bool', 'all']:
59 modnames[name] = 0
60
61
62 def get_runlengths(pbit, size):
63 res = []
64 count = 1
65 # identify where the 1s are, which indicates "start of a new partition"
66 # we want a list of the lengths of all partitions
67 for i in range(size):
68 if pbit & (1 << i): # it's a 1: ends old partition, starts new
69 res.append(count) # add partition
70 count = 1 # start again
71 else:
72 count += 1
73 # end reached, add whatever is left. could have done this by creating
74 # "fake" extra bit on the partitions, but hey
75 res.append(count)
76
77 return res
78
79
80 # Prototype https://bugs.libre-soc.org/show_bug.cgi?id=713#c53
81 # this provides a "compatibility" layer with existing SimdSignal
82 # behaviour. the idea is that this interface defines which "combinations"
83 # of partition selections are relevant, and as an added bonus it says
84 # which partition lanes are completely irrelevant (padding, blank).
85 class PartType: # TODO decide name
86 def __init__(self, psig):
87 self.psig = psig
88
89 def get_mask(self):
90 return list(self.psig.partpoints.values())
91
92 def get_switch(self):
93 return Cat(self.get_mask())
94
95 def get_cases(self):
96 return range(1 << len(self.get_mask()))
97
98 def get_num_elements(self, pbit):
99 keys = list(self.psig.partpoints.keys())
100 return len(get_runlengths(pbit, len(keys)))
101
102 def get_el_range(self, pbit, el_num):
103 """based on the element number and the current elwid/pbit (case)
104 return the range start/end of the element within its underlying signal
105 this function is not at all designed to be efficient.
106 """
107 keys = list(self.psig.partpoints.keys())
108 runs = get_runlengths(pbit, len(keys))
109 keys = [0] + keys + [len(self.psig.sig)]
110 y = 0
111 for i in range(el_num):
112 numparts = runs[i]
113 y += numparts
114 numparts = runs[el_num]
115 return range(keys[y], keys[y+numparts])
116
117 @property
118 def blanklanes(self):
119 return 0
120
121
122 # this one would be an elwidth version
123 # see https://bugs.libre-soc.org/show_bug.cgi?id=713#c34
124 # it requires an "adapter" which is the layout() function
125 # where the PartitionPoints was *created* by the layout()
126 # function and this class then "understands" the relationship
127 # between elwidth and the PartitionPoints that were created
128 # by layout()
129 class ElwidPartType: # TODO decide name
130 def __init__(self, psig):
131 self.psig = psig
132
133 def get_mask(self):
134 return list(self.psig._shape.partpoints.values()) # i think
135
136 def get_switch(self):
137 return self.psig.scope.elwid # switch on elwid: match get_cases()
138
139 def get_cases(self):
140 return self.psig._shape.bitp.keys() # all possible values of elwid
141
142 @property
143 def blanklanes(self):
144 return self.psig.shape.blankmask
145
146
147 # declares priority of the SimdShape
148 PRIORITY_FIXED = 0b01
149 PRIORITY_ELWID = 0b10
150 PRIORITY_BOTH = 0b11
151
152 class SimdShape(Shape):
153 """a SIMD variant of Shape. supports:
154 * fixed overall width with variable (maxed-out) element lengths
155 * fixed element widths with overall size auto-determined
156 * both fixed overall width and fixed element widths
157
158 Documentation / Analysis:
159 https://libre-soc.org/3d_gpu/architecture/dynamic_simd/shape/
160
161 naming is preserved to be compatible with Shape(): the (calculated *or*
162 given) fixed_width is *explicitly* passed through as Shape.width
163 in order to ensure downcasting works as expected.
164
165 the width parameter is exactly what would be expected if this was
166 a Scalar Shape: it can however be given a dictionary of alternative
167 widths on a per-elwid basis.
168
169 a mode flag records what behaviour is required for arithmetic operators.
170 see wiki documentation: it's... complicated.
171 """
172
173 def __init__(self, scope, width=None, # this is actually widths_at_elwid
174 signed=False,
175 fixed_width=None): # fixed overall width
176 # record the mode and scope
177 self.scope = scope
178 self.fixed_width = fixed_width
179 self.widths_at_elwid = width
180 self.mode_flag = 0
181 # when both of these are set it creates mode_flag=PRIORITY_BOTH
182 # otherwise creates a priority of either FIXED width or ELWIDs
183 if self.fixed_width is not None:
184 self.mode_flag |= PRIORITY_FIXED
185 if self.widths_at_elwid is not None:
186 self.mode_flag |= PRIORITY_ELWID
187
188 print("SimdShape width", width, "fixed_width", fixed_width)
189 # this check is done inside layout but do it again here anyway
190 assert self.fixed_width != None or self.widths_at_elwid != None, \
191 "both width (widths_at_elwid) and fixed_width cannot be None"
192
193 if scope is not None:
194 (pp, bitp, lpoints, bmask, width, lane_shapes, part_wid) = \
195 layout(scope.elwid,
196 scope.vec_el_counts,
197 self.widths_at_elwid,
198 self.fixed_width)
199 self.partpoints = pp
200 self.bitp = bitp # binary values for partpoints at each elwidth
201 self.lpoints = lpoints # layout ranges
202 self.blankmask = bmask # blanking mask (partitions always padding)
203 self.partwid = part_wid # smallest alignment start point for elements
204 self.lane_shapes = lane_shapes
205
206 # pass through the calculated width to Shape() so that when/if
207 # objects using this Shape are downcast, they know exactly how to
208 # get *all* bits and need know absolutely nothing about SIMD at all
209 Shape.__init__(self, width, signed)
210
211 @staticmethod
212 def like(cls, shape, *, scope=None):
213 if scope is None:
214 scope = shape.scope
215 return SimdShape(scope, shape.widths_at_elwid, shape.signed,
216 scope.fixed_width)
217
218 def __mul__(self, other):
219 if isinstance(other, int):
220 # for integer multiply, by a nice coincidence it does not
221 # matter if the LHS is PRIORITY_FIXED or PRIORITY_ELWID.
222 # however the priority has to be preserved.
223 fixed_width = None
224 lane_shapes = None
225
226 # first, check if fixed_width is needed (if originally,
227 # self was constructed with a fixed_width=None we must
228 # *return* another SimdShape with a fixed_width=None)
229 if self.mode_flag & PRIORITY_FIXED:
230 fixed_width = self.width * other
231
232 # likewise for lane elwidths: if, originally, self was constructed
233 # with [widths_at_elwidth==lane_shapes==]width not None,
234 # the return result also has to set up explicit lane_shapes
235 if self.mode_flag & PRIORITY_ELWID:
236 lane_shapes = {k: v * other for k, v in self.lane_shapes}
237
238 # wheww, got everything.
239 return SimdShape(self.scope, # same scope
240 width=lane_shapes, # widths_at_elwid
241 signed=self.signed, # same sign? hmmm XXX
242 fixed_width=fixed_width) # overall width
243 else:
244 raise NotImplementedError(
245 f"Multiplying a SimdShape by {type(other)} isn't implemented")
246
247 # TODO (and go over examples, sigh). this is deliberately *after*
248 # the raise NotImplementedError because it needs review.
249
250 # also probably TODO: potentially the other argument could be
251 # a Shape() not a SimdShape(). sigh.
252
253 # for SimdShape-to-SimdShape multiply, the rules are slightly
254 # different: both sides have to be PRIORITY_FIXED for a
255 # PRIORITY_FIXED result to be returned. if either (or both)
256 # of the LHS and RHS were given elwidths (lane_shapes != None)
257 # then tough luck: the return result is still PRIORITY_ELWID.
258 # TODO: review that. it *might* be the case (again, due to
259 # a coincidence of multiply, that when PRIORITY_BOTH is set
260 # it is possible to return a PRIORITY_BOTH result. but..
261 # it is unlikely)
262
263 fixed_width = None
264 lane_shapes = None
265
266 # first, check if this is fixed_width mode. this is *only*
267 # possible if *both* LHS *and* RHS are PRIORITY_FIXED.
268 if (self.mode_flag == PRIORITY_FIXED and
269 other.mode_flag == PRIORITY_FIXED):
270 fixed_width = self.width * other.width
271 else:
272 # (XXX assume other is SimdShape) - when PRIORITY_ELWID
273 # the result *has* to be a PRIORITY_ELWID (FIXED is *IGNORED*)
274 # use *either* the computed *or* the given lane_shapes
275 lane_shapes = {k: v * other.lane_shapes[k] \
276 for k, v in self.lane_shapes}
277
278 # wheww, got everything.
279 return SimdShape(self.scope, # same scope
280 width=lane_shapes, # widths_at_elwid
281 signed=self.signed, # same sign? hmmm XXX
282 fixed_width=fixed_width) # overall width
283
284
285 def __rmul__(self, other):
286 return self.__mul__(other)
287
288 def __add__(self, other):
289 if isinstance(other, int):
290 lane_shapes = {k: v + other for k, v in self.lane_shapes}
291 return SimdShape(self.scope, lane_shapes, signed=self.signed)
292 elif isinstance(other, SimdShape):
293 # XXX MO, must be equivalent, not the same object.
294 # requires an eq override just like in Shape.
295 assert other.scope is self.scope, "scope mismatch"
296 o = other.lane_shapes
297 lane_shapes = {k: v + o[k] for k, v in self.lane_shapes}
298 # XXX not correct, we need a width-hint, not an overwrite
299 # lane_shapes argument...
300 return SimdShape(self.scope, lane_shapes, signed=self.signed,
301 fixed_width=self.width + other.width)
302 else:
303 raise NotImplementedError(
304 f"Adding a SimdShape to {type(other)} isn't implemented")
305
306 def __radd__(self, other):
307 return self.__add__(other)
308
309
310 class SimdSignal(UserValue):
311 # XXX ################################################### XXX
312 # XXX Keep these functions in the same order as ast.Value XXX
313 # XXX ################################################### XXX
314 def __init__(self, mask, shape=None, *args,
315 src_loc_at=0, fixed_width=None, **kwargs):
316 super().__init__(src_loc_at=src_loc_at)
317 print("SimdSignal shape", shape)
318 # create partition points
319 if isinstance(mask, SimdScope): # mask parameter is a SimdScope
320 self.scope = mask
321 self.ptype = ElwidPartType(self)
322 # SimdShapes can be created with an empty scope. check that now
323 if isinstance(shape, SimdScope):
324 if shape.scope is None:
325 shape = SimdScope.like(shape, scope=self.scope)
326 else:
327 # adapt shape to a SimdShape
328 shape = SimdShape(self.scope, shape, fixed_width=fixed_width)
329 self._shape = shape
330 self.sig = Signal(shape, *args, **kwargs)
331 # get partpoints from SimdShape
332 self.partpoints = shape.partpoints
333 else:
334 self.sig = Signal(shape, *args, **kwargs)
335 width = len(self.sig) # get signal width
336 if isinstance(mask, PartitionPoints):
337 self.partpoints = mask
338 else:
339 self.partpoints = make_partition2(mask, width)
340 self.ptype = PartType(self)
341
342 def set_module(self, m):
343 self.m = m
344
345 def get_modname(self, category):
346 modnames[category] += 1
347 return "%s_%d" % (category, modnames[category])
348
349 @staticmethod
350 def like(other, *args, **kwargs):
351 """Builds a new SimdSignal with the same PartitionPoints and
352 Signal properties as the other"""
353 result = SimdSignal(PartitionPoints(other.partpoints))
354 result.sig = Signal.like(other.sig, *args, **kwargs)
355 result.m = other.m
356 return result
357
358 def lower(self):
359 return self.sig
360
361 # nmigen-redirected constructs (Mux, Cat, Switch, Assign)
362
363 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=716
364 # def __Part__(self, offset, width, stride=1, *, src_loc_at=0):
365 raise NotImplementedError("TODO: implement as "
366 "(self>>(offset*stride)[:width]")
367 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=716
368
369 def __Slice__(self, start, stop, *, src_loc_at=0):
370 # NO. Swizzled shall NOT be deployed, it violates
371 # Project Development Practices
372 raise NotImplementedError("TODO: need PartitionedSlice")
373
374 def __Repl__(self, count, *, src_loc_at=0):
375 return PRepl(self.m, self, count, self.ptype)
376
377 def __Cat__(self, *args, src_loc_at=0):
378 print("partsig cat", self, args)
379 # TODO: need SwizzledSimdValue-aware Cat
380 args = [self] + list(args)
381 for sig in args:
382 assert isinstance(sig, SimdSignal), \
383 "All SimdSignal.__Cat__ arguments must be " \
384 "a SimdSignal. %s is not." % repr(sig)
385 return PCat(self.m, args, self.ptype)
386
387 def __Mux__(self, val1, val2):
388 # print ("partsig mux", self, val1, val2)
389 assert len(val1) == len(val2), \
390 "SimdSignal width sources must be the same " \
391 "val1 == %d, val2 == %d" % (len(val1), len(val2))
392 return PMux(self.m, self.partpoints, self, val1, val2, self.ptype)
393
394 def __Assign__(self, val, *, src_loc_at=0):
395 print("partsig assign", self, val)
396 # this is a truly awful hack, outlined here:
397 # https://bugs.libre-soc.org/show_bug.cgi?id=731#c13
398 # during the period between constructing Simd-aware sub-modules
399 # and the elaborate() being called on them there is a window of
400 # opportunity to indicate which of those submodules is LHS and
401 # which is RHS. manic laughter is permitted. *gibber*.
402 if hasattr(self, "_hack_submodule"):
403 self._hack_submodule.set_lhs_mode(True)
404 if hasattr(val, "_hack_submodule"):
405 val._hack_submodule.set_lhs_mode(False)
406 return PAssign(self.m, self, val, self.ptype)
407
408 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=458
409 # def __Switch__(self, cases, *, src_loc=None, src_loc_at=0,
410 # case_src_locs={}):
411
412 # no override needed, Value.__bool__ sufficient
413 # def __bool__(self):
414
415 # unary ops that do not require partitioning
416
417 def __invert__(self):
418 result = SimdSignal.like(self)
419 self.m.d.comb += result.sig.eq(~self.sig)
420 return result
421
422 # unary ops that require partitioning
423
424 def __neg__(self):
425 z = Const(0, len(self.sig))
426 result, _ = self.sub_op(z, self)
427 return result
428
429 # binary ops that need partitioning
430
431 def add_op(self, op1, op2, carry):
432 op1 = getsig(op1)
433 op2 = getsig(op2)
434 pa = PartitionedAdder(len(op1), self.partpoints)
435 setattr(self.m.submodules, self.get_modname('add'), pa)
436 comb = self.m.d.comb
437 comb += pa.a.eq(op1)
438 comb += pa.b.eq(op2)
439 comb += pa.carry_in.eq(carry)
440 result = SimdSignal.like(self)
441 comb += result.sig.eq(pa.output)
442 return result, pa.carry_out
443
444 def sub_op(self, op1, op2, carry=~0):
445 op1 = getsig(op1)
446 op2 = getsig(op2)
447 pa = PartitionedAdder(len(op1), self.partpoints)
448 setattr(self.m.submodules, self.get_modname('add'), pa)
449 comb = self.m.d.comb
450 comb += pa.a.eq(op1)
451 comb += pa.b.eq(~op2)
452 comb += pa.carry_in.eq(carry)
453 result = SimdSignal.like(self)
454 comb += result.sig.eq(pa.output)
455 return result, pa.carry_out
456
457 def __add__(self, other):
458 result, _ = self.add_op(self, other, carry=0)
459 return result
460
461 def __radd__(self, other):
462 # https://bugs.libre-soc.org/show_bug.cgi?id=718
463 result, _ = self.add_op(other, self)
464 return result
465
466 def __sub__(self, other):
467 result, _ = self.sub_op(self, other)
468 return result
469
470 def __rsub__(self, other):
471 # https://bugs.libre-soc.org/show_bug.cgi?id=718
472 result, _ = self.sub_op(other, self)
473 return result
474
475 def __mul__(self, other):
476 raise NotImplementedError # too complicated at the moment
477 return Operator("*", [self, other])
478
479 def __rmul__(self, other):
480 raise NotImplementedError # too complicated at the moment
481 return Operator("*", [other, self])
482
483 # not needed: same as Value.__check_divisor
484 # def __check_divisor(self):
485
486 def __mod__(self, other):
487 raise NotImplementedError
488 other = Value.cast(other)
489 other.__check_divisor()
490 return Operator("%", [self, other])
491
492 def __rmod__(self, other):
493 raise NotImplementedError
494 self.__check_divisor()
495 return Operator("%", [other, self])
496
497 def __floordiv__(self, other):
498 raise NotImplementedError
499 other = Value.cast(other)
500 other.__check_divisor()
501 return Operator("//", [self, other])
502
503 def __rfloordiv__(self, other):
504 raise NotImplementedError
505 self.__check_divisor()
506 return Operator("//", [other, self])
507
508 # not needed: same as Value.__check_shamt
509 # def __check_shamt(self):
510
511 # TODO: detect if the 2nd operand is a Const, a Signal or a
512 # SimdSignal. if it's a Const or a Signal, a global shift
513 # can occur. if it's a SimdSignal, that's much more interesting.
514 def ls_op(self, op1, op2, carry, shr_flag=0):
515 op1 = getsig(op1)
516 if isinstance(op2, Const) or isinstance(op2, Signal):
517 scalar = True
518 pa = PartitionedScalarShift(len(op1), self.partpoints)
519 else:
520 scalar = False
521 op2 = getsig(op2)
522 pa = PartitionedDynamicShift(len(op1), self.partpoints)
523 # else:
524 # TODO: case where the *shifter* is a SimdSignal but
525 # the thing *being* Shifted is a scalar (Signal, expression)
526 # https://bugs.libre-soc.org/show_bug.cgi?id=718
527 setattr(self.m.submodules, self.get_modname('ls'), pa)
528 comb = self.m.d.comb
529 if scalar:
530 comb += pa.data.eq(op1)
531 comb += pa.shifter.eq(op2)
532 comb += pa.shift_right.eq(shr_flag)
533 else:
534 comb += pa.a.eq(op1)
535 comb += pa.b.eq(op2)
536 comb += pa.shift_right.eq(shr_flag)
537 # XXX TODO: carry-in, carry-out (for arithmetic shift)
538 #comb += pa.carry_in.eq(carry)
539 return (pa.output, 0)
540
541 def __lshift__(self, other):
542 z = Const(0, len(self.partpoints)+1)
543 result, _ = self.ls_op(self, other, carry=z) # TODO, carry
544 return result
545
546 def __rlshift__(self, other):
547 # https://bugs.libre-soc.org/show_bug.cgi?id=718
548 raise NotImplementedError
549 return Operator("<<", [other, self])
550
551 def __rshift__(self, other):
552 z = Const(0, len(self.partpoints)+1)
553 result, _ = self.ls_op(self, other, carry=z, shr_flag=1) # TODO, carry
554 return result
555
556 def __rrshift__(self, other):
557 # https://bugs.libre-soc.org/show_bug.cgi?id=718
558 raise NotImplementedError
559 return Operator(">>", [other, self])
560
561 # binary ops that don't require partitioning
562
563 def __and__(self, other):
564 return applyop(self, other, and_)
565
566 def __rand__(self, other):
567 return applyop(other, self, and_)
568
569 def __or__(self, other):
570 return applyop(self, other, or_)
571
572 def __ror__(self, other):
573 return applyop(other, self, or_)
574
575 def __xor__(self, other):
576 return applyop(self, other, xor)
577
578 def __rxor__(self, other):
579 return applyop(other, self, xor)
580
581 # binary comparison ops that need partitioning
582
583 def _compare(self, width, op1, op2, opname, optype):
584 # print (opname, op1, op2)
585 pa = PartitionedEqGtGe(width, self.partpoints)
586 setattr(self.m.submodules, self.get_modname(opname), pa)
587 comb = self.m.d.comb
588 comb += pa.opcode.eq(optype) # set opcode
589 if isinstance(op1, SimdSignal):
590 comb += pa.a.eq(op1.sig)
591 else:
592 comb += pa.a.eq(op1)
593 if isinstance(op2, SimdSignal):
594 comb += pa.b.eq(op2.sig)
595 else:
596 comb += pa.b.eq(op2)
597 return pa.output
598
599 def __eq__(self, other):
600 width = len(self.sig)
601 return self._compare(width, self, other, "eq", PartitionedEqGtGe.EQ)
602
603 def __ne__(self, other):
604 width = len(self.sig)
605 eq = self._compare(width, self, other, "eq", PartitionedEqGtGe.EQ)
606 ne = Signal(eq.width)
607 self.m.d.comb += ne.eq(~eq)
608 return ne
609
610 def __lt__(self, other):
611 width = len(self.sig)
612 # swap operands, use gt to do lt
613 return self._compare(width, other, self, "gt", PartitionedEqGtGe.GT)
614
615 def __le__(self, other):
616 width = len(self.sig)
617 # swap operands, use ge to do le
618 return self._compare(width, other, self, "ge", PartitionedEqGtGe.GE)
619
620 def __gt__(self, other):
621 width = len(self.sig)
622 return self._compare(width, self, other, "gt", PartitionedEqGtGe.GT)
623
624 def __ge__(self, other):
625 width = len(self.sig)
626 return self._compare(width, self, other, "ge", PartitionedEqGtGe.GE)
627
628 # no override needed: Value.__abs__ is general enough it does the job
629 # def __abs__(self):
630
631 def __len__(self):
632 return len(self.sig)
633
634 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=716
635 # def __getitem__(self, key):
636
637 def __new_sign(self, signed):
638 # XXX NO - SimdShape not Shape
639 print("XXX requires SimdShape not Shape")
640 shape = Shape(len(self), signed=signed)
641 result = SimdSignal.like(self, shape=shape)
642 self.m.d.comb += result.sig.eq(self.sig)
643 return result
644
645 # http://bugs.libre-riscv.org/show_bug.cgi?id=719
646 def as_unsigned(self):
647 return self.__new_sign(False)
648
649 def as_signed(self):
650 return self.__new_sign(True)
651
652 # useful operators
653
654 def bool(self):
655 """Conversion to boolean.
656
657 Returns
658 -------
659 Value, out
660 ``1`` if any bits are set, ``0`` otherwise.
661 """
662 width = len(self.sig)
663 pa = PartitionedBool(width, self.partpoints)
664 setattr(self.m.submodules, self.get_modname("bool"), pa)
665 self.m.d.comb += pa.a.eq(self.sig)
666 return pa.output
667
668 def any(self):
669 """Check if any bits are ``1``.
670
671 Returns
672 -------
673 Value, out
674 ``1`` if any bits are set, ``0`` otherwise.
675 """
676 return self != Const(0) # leverage the __ne__ operator here
677 return Operator("r|", [self])
678
679 def all(self):
680 """Check if all bits are ``1``.
681
682 Returns
683 -------
684 Value, out
685 ``1`` if all bits are set, ``0`` otherwise.
686 """
687 # something wrong with PartitionedAll, but self == Const(-1)"
688 # XXX https://bugs.libre-soc.org/show_bug.cgi?id=176#c17
689 #width = len(self.sig)
690 #pa = PartitionedAll(width, self.partpoints)
691 #setattr(self.m.submodules, self.get_modname("all"), pa)
692 #self.m.d.comb += pa.a.eq(self.sig)
693 # return pa.output
694 return self == Const(-1) # leverage the __eq__ operator here
695
696 def xor(self):
697 """Compute pairwise exclusive-or of every bit.
698
699 Returns
700 -------
701 Value, out
702 ``1`` if an odd number of bits are set, ``0`` if an
703 even number of bits are set.
704 """
705 width = len(self.sig)
706 pa = PartitionedXOR(width, self.partpoints)
707 setattr(self.m.submodules, self.get_modname("xor"), pa)
708 self.m.d.comb += pa.a.eq(self.sig)
709 return pa.output
710
711 # not needed: Value.implies does the job
712 # def implies(premise, conclusion):
713
714 # TODO. contains a Value.cast which means an override is needed (on both)
715 # def bit_select(self, offset, width):
716 # def word_select(self, offset, width):
717
718 # not needed: Value.matches, amazingly, should do the job
719 # def matches(self, *patterns):
720
721 # TODO, http://bugs.libre-riscv.org/show_bug.cgi?id=713
722 def shape(self):
723 return self.sig.shape()
724
725
726 # temporary to allow tracking back through git revision history
727 PartitionedSignal = SimdSignal