1 from nmigen
import Module
, Signal
, Elaboratable
, Cat
, Repl
4 class CLZ(Elaboratable
):
5 def __init__(self
, width
):
7 self
.sig_in
= Signal(width
, reset_less
=True)
8 out_width
= math
.ceil(math
.log2(width
+1))
9 self
.lz
= Signal(out_width
)
11 def generate_pairs(self
, m
):
14 for i
in range(0, self
.width
, 2):
16 pair
= Signal(1, name
="cnt_1_%d" % (i
/2))
17 comb
+= pair
.eq(~self
.sig_in
[i
])
18 pairs
.append((pair
, 1))
20 pair
= Signal(2, name
="pair%d" % i
)
21 comb
+= pair
.eq(self
.sig_in
[i
:i
+2])
23 pair_cnt
= Signal(2, name
="cnt_1_%d" % (i
/2))
26 comb
+= pair_cnt
.eq(2)
28 comb
+= pair_cnt
.eq(1)
30 comb
+= pair_cnt
.eq(0)
31 pairs
.append((pair_cnt
, 2)) # append pair, max_value
34 def combine_pairs(self
, m
, iteration
, pairs
):
38 for i
in range(0, length
, 2):
42 new_pair
= Signal(width
, name
="cnt_%d_%d" % (iteration
, i
))
43 comb
+= new_pair
.eq(Cat(right
, 0))
44 ret
.append((new_pair
, mv
))
48 width
= right
.width
+ 1
49 new_pair
= Signal(width
, name
="cnt_%d_%d" %
52 with m
.If(left
[-1] == 1):
53 with m
.If(right
[-1] == 1):
54 comb
+= new_pair
.eq(Cat(Repl(0, width
-1), 1))
56 comb
+= new_pair
.eq(Cat(right
[0:-1], 0b01))
58 comb
+= new_pair
.eq(Cat(left
, 0))
60 with m
.If(left
== lv
):
61 comb
+= new_pair
.eq(right
+ left
)
63 comb
+= new_pair
.eq(left
)
66 ret
.append((new_pair
, lv
+rv
))
69 def elaborate(self
, platform
):
73 pairs
= self
.generate_pairs(m
)
76 pairs
= self
.combine_pairs(m
, i
, pairs
)
79 comb
+= self
.lz
.eq(pairs
[0][0])