summaryrefslogtreecommitdiff
path: root/hdl/core/alu.py
blob: 4380b8e50c07444c1be86692b42998c28012b132 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
from amaranth import *
from amaranth.sim import Simulator, Settle, Delay
from enum import Enum, unique

from hdl.utils import sim, e2s, cmd, rand_bits_mix
from hdl.lib.in_out_buff import InOutBuff
from hdl.config import NUM_RAND_TESTS

@unique
class AluOpCodes(Enum):
    add = 0
    addc = 1
    sub = 2
    subc = 3
    bit_and = 4
    bit_or = 5
    bit_xor = 6
    bit_nor = 7
    lleft = 8
    lright = 9
    aright = 10
    multul = 11     # low 32 bits of unsigned multiplication
    multuh = 12     # high 32 bits of unsigned multiplication
    multsl = 13     # low 32 bits of signed multiplication
    multsh = 14     # high 32 bits of signed multiplication

@unique
class ALUFlags(Enum):
    zero = 0
    carry = 1
    overflow = 2
    negative = 3

class ALU(Elaboratable):

    def __init__(self, **kargs):
        self.in1 = Signal(32, reset_less=True)
        self.in2 = Signal(32, reset_less=True)
        self.c_in = Signal(1)
        self.op = Signal(e2s(AluOpCodes), reset_less=True)

        self.tmp = Signal(33, reset_less=True)

        self.c_out = Signal(1, reset_less=True)
        self.overflow = Signal(1, reset_less=True)
        self.zero = Signal(1, reset_less=True)
        self.neg = Signal(1, reset_less=True)

        self.alu_flags = Signal(len(ALUFlags), reset_less=True) # alu flags is one hot
        self.out = Signal(32, reset_less=True)

        self.sim = kargs.get('sim', False)

        ports_in = [self.in1, self.in2, self.op, self.c_in]
        ports_out = [self.c_in, self.out, self.alu_flags]
        self.ports = {'in': ports_in, 'out': ports_out}

    def elaborate(self, platform=None):
        m = Module()

        with m.Switch(self.op):
            with m.Case(AluOpCodes.add.value):
                m.d.comb += self.tmp.eq(self.in1 + self.in2)

            with m.Case(AluOpCodes.addc.value):
                m.d.comb += self.tmp.eq(self.in1 + self.in2 + self.c_in)

            with m.Case(AluOpCodes.sub.value):
                m.d.comb += self.tmp.eq(self.in1 - self.in2)

            with m.Case(AluOpCodes.subc.value):
                m.d.comb += self.tmp.eq(self.in1 + ~self.in2 + self.c_in)

            with m.Case(AluOpCodes.bit_and.value):
                m.d.comb += self.tmp.eq(Cat(self.in1 & self.in2, 0))

            with m.Case(AluOpCodes.bit_or.value):
                m.d.comb += self.tmp.eq(Cat(self.in1 | self.in2, 0))

            with m.Case(AluOpCodes.bit_xor.value):
                m.d.comb += self.tmp.eq(Cat(self.in1 ^ self.in2, 0))
            
            with m.Case(AluOpCodes.bit_nor.value):
                m.d.comb += self.tmp.eq(Cat(~(self.in1 | self.in2), 0))

            with m.Case(AluOpCodes.lleft.value):
                m.d.comb += self.tmp.eq(Cat(self.in1, 0) << self.in2[0:5])

            with m.Case(AluOpCodes.lright.value):
                tmp2 = Signal(33)
                m.d.comb += tmp2.eq(Cat(0, self.in1) >> self.in2)
                m.d.comb += self.tmp.eq(Cat(tmp2[1:33], tmp2[0]))   # move shifted bit to carry bit

            with m.Case(AluOpCodes.aright.value):
                tmp2 = Signal(33)
                m.d.comb += tmp2.eq(Cat(0, self.in1).as_signed() >> self.in2)
                m.d.comb += self.tmp.eq(Cat(tmp2[1:33], tmp2[0]))   # move shifted bit to carry bit

            with m.Case(AluOpCodes.multul.value):
                m.d.comb += self.tmp.eq(Cat((self.in1 * self.in2)[:32], 0))

            with m.Case(AluOpCodes.multuh.value):
                m.d.comb += self.tmp.eq(Cat((self.in1 * self.in2)[32:], 0))
            
            with m.Case(AluOpCodes.multsl.value):
                m.d.comb += self.tmp.eq(Cat((self.in1.as_signed() * self.in2.as_signed())[:32], 0))

            with m.Case(AluOpCodes.multsh.value):
                m.d.comb += self.tmp.eq(Cat((self.in1.as_signed() * self.in2.as_signed())[32:], 0))
            

            # bad juju, 
            # TODO: come back and check this will work
            # with m.Case(AluOpCodes.udiv.value):
            #     m.d.comb += self.tmp.eq(Cat(self.in1 // self.in2, 0))
            
            # with m.Case(AluOpCodes.sdiv.value):
            #     m.d.comb += self.tmp.eq(self.in1.as_signed() // self.in2.as_signed())   # for some reason I have not confirmed, signed div can yield a 33 bit number, acording to amaranth

            with m.Case():
                m.d.comb += self.tmp.eq(0)
        
        m.d.comb += self.c_out.eq(self.tmp[32])
        m.d.comb += self.overflow.eq(self.tmp[32] ^ self.tmp[31])
        m.d.comb += self.neg.eq(self.out[31])
        m.d.comb += self.zero.eq(self.out == 0)

        m.d.comb += self.alu_flags[ALUFlags.zero.value].eq(self.zero)
        m.d.comb += self.alu_flags[ALUFlags.carry.value].eq(self.c_out)
        m.d.comb += self.alu_flags[ALUFlags.overflow.value].eq(self.overflow)
        m.d.comb += self.alu_flags[ALUFlags.negative.value].eq(self.neg)
        m.d.comb += self.out.eq(self.tmp[0:32])
        
        return m

def sub_proc(dut, val1, val2, c_in=0):
    yield dut.in1.eq(val1)
    yield dut.in2.eq(val2)
    yield dut.c_in.eq(c_in)
    yield Settle()

# test addition
def test_alu_add():
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.add.value)
        yield from sub_proc(dut, 27, 13)
        out = yield dut.out
        assert 27 + 13 == (out), f'ERROR: {out} != {27 + 13}'
    sim(dut, proc, sync=False)

# test addition with carry
def test_alu_addc():
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.addc.value)
        yield from sub_proc(dut, 11, 43, 1)
        out = yield dut.out.as_signed()
        assert 11 + 43 + 1 == out, f'ERROR: {out} != {11 + 43 + 1}'
    sim(dut, proc, sync=False)

# test subtraction
def test_alu_sub():
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.sub.value)
        yield from sub_proc(dut, 25, 13)
        out = yield dut.out
        assert 25 - 13 == out, f'ERROR: {out} != {25 - 13}'
    sim(dut, proc, sync=False)
        
# test subtraction with carry
def test_alu_subc_0():
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.subc.value)
        yield from sub_proc(dut, 25, -13, 0)
        out = yield dut.out.as_signed()
        assert 25 + 13 -1 +0 == out, f'ERROR: {out} != {25 + 13 -1 +0}'
    sim(dut, proc, sync=False)

# test subtraction with carry
def test_alu_subc_1():
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.subc.value)
        yield from sub_proc(dut, 25, -13, 1)
        out = yield dut.out.as_signed()
        assert 25 + 13 -1 +1 == out, f'ERROR: {out} != {25 + 13 -1 +1}'
    sim(dut, proc, sync=False)

# test binary and
def test_alu_and():
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.bit_and.value)
        yield from sub_proc(dut, 0b10101011, 0b01010101)
        out = yield dut.out
        assert 0b00000001 == out, f'ERROR: {out} != {0b00000001}'
    sim(dut, proc, sync=False)

# test binary or
def test_alu_or():
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.bit_or.value)
        yield from sub_proc(dut, 0b10101011, 0b01000101)
        out = yield dut.out
        assert 0b11101111 == out, f'ERROR: {out} != {0b11101111}'
    sim(dut, proc, sync=False)

# test binary nor
def test_alu_nor():
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.bit_nor.value)
        yield from sub_proc(dut, 0b10001011, 0b01000101)
        out = yield dut.out
        assert 0b11111111111111111111111100110000 == out, f'ERROR: {bin(out)} != {bin(0b11111111111111111111111100110000)}'
    sim(dut, proc, sync=False)

# test binary xor
def test_alu_xor():
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.bit_xor.value)
        yield from sub_proc(dut, 0b10001011, 0b01000101)
        out = yield dut.out
        assert 0b11001110 == out, f'ERROR: {out} != {0b11001110}'
    sim(dut, proc, sync=False)

# test logical shift left
def test_alu_logic_shift_left():
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.lleft.value)
        yield from sub_proc(dut, 0b10001011, 25) # shift left by 5
        out = yield dut.out
        assert 0b00010110000000000000000000000000 == out, f'ERROR: {bin(out)} != {bin(0b00010110000000000000000000000000)}'
        out = yield dut.c_out
        assert 1 == out, f'ERROR: {out} != {1}'
    sim(dut, proc, sync=False)

# test logical shift right
def test_alu_logic_shift_right():
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.lright.value)
        yield from sub_proc(dut, 0b10001011, 4) # shift right by 5
        out = yield dut.out
        assert 0b1000 == out, f'ERROR: {bin(out)} != {bin(0b1000)}'
        out = yield dut.c_out
        assert 1 == out, f'ERROR: {out} != {1}'
    sim(dut, proc, sync=False)

# test arithmetic shift right
def test_alu_arith_shift_right():
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.aright.value)
        yield from sub_proc(dut, 0x80001234, 4) # shift right by 4
        out = yield dut.out
        assert 0xF8000123 == out, f'ERROR: {out} != {0xF8000123}'
        out = yield dut.c_out
        assert 0 == out, f'ERROR: {out} != {0}'
    sim(dut, proc, sync=False)

# test low unsigned multiply
def test_alu_mul_low_u(tests=NUM_RAND_TESTS):
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.multul.value)
        yield dut.c_in.eq(0)
        
        for _ in range(tests):
            in1 = rand_bits_mix(32, sus='u')
            in2 = rand_bits_mix(32, sus='u')
            yield dut.in1.eq(in1)
            yield dut.in2.eq(in2)
            yield Settle()
            expected = (in1 * in2) & 0xFFFFFFFF
            assert (yield dut.out) == expected, f"mul_low_u failed: in1={hex(in1)}, in2={hex(in2)}, out={hex((yield dut.out))}, expected={hex(expected)}"

    sim(dut, proc, sync=False)

# test high unsigned multiply
def test_alu_mul_high_u(tests=NUM_RAND_TESTS):
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.multuh.value)
        yield dut.c_in.eq(0)
        
        for _ in range(tests):
            in1 = rand_bits_mix(32, sus='u')
            in2 = rand_bits_mix(32, sus='u')
            yield dut.in1.eq(in1)
            yield dut.in2.eq(in2)
            yield Settle()
            expected = ((in1 * in2) >> 32) & 0xFFFFFFFF
            assert (yield dut.out) == expected, f"mul_high_u failed: in1={hex(in1)}, in2={hex(in2)}, out={hex((yield dut.out))}, expected={hex(expected)}"

    sim(dut, proc, sync=False)

# test low signed multiply
def test_alu_mul_low_s(tests=NUM_RAND_TESTS):
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.multsl.value)
        yield dut.c_in.eq(0)
        
        for _ in range(tests):
            in1 = rand_bits_mix(32, sus='s')
            in2 = rand_bits_mix(32, sus='s')
            yield dut.in1.eq(in1)
            yield dut.in2.eq(in2)
            yield Settle()
            expected = (in1 * in2) & 0xFFFFFFFF
            assert (yield dut.out) == expected, f"mul_low_s failed: in1={hex(in1)}, in2={hex(in2)}, out={hex((yield dut.out))}, expected={hex(expected)}"

    sim(dut, proc, sync=False)

# test high signed multiply
def test_alu_mul_high_s(tests=NUM_RAND_TESTS):
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.multsh.value)
        yield dut.c_in.eq(0)
        
        for _ in range(tests):
            in1 = rand_bits_mix(32, sus='s')
            in2 = rand_bits_mix(32, sus='s')
            yield dut.in1.eq(in1)
            yield dut.in2.eq(in2)
            yield Settle()
            expected = ((in1 * in2) >> 32) & 0xFFFFFFFF
            assert (yield dut.out) == expected, f"mul_high_s failed: in1={hex(in1)}, in2={hex(in2)}, out={hex((yield dut.out))}, expected={hex(expected)}"

    sim(dut, proc, sync=False)


# test unsigned overflow
def test_alu_unsigned_overflow():
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.add.value)
        yield from sub_proc(dut, 0xFFFFFFFF, 1) # add 1 to 0xFFFFFFFF
        out = yield dut.overflow
        assert out == 1, f'ERROR: {out} != {1}'
        out = yield dut.c_out
        assert out == 1, f'ERROR: {out} != {1}'
    sim(dut, proc, sync=False)

# test unsigned underflow
def test_alu_unsigned_underflow():
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.add.value)
        yield from sub_proc(dut, 0, -1) # subtract 1 from 0
        out = yield dut.overflow
        assert out == 1, f'ERROR: {out} != {1}'
        out = yield dut.c_out
        assert out == 0, f'ERROR: {out} != {0}'
    sim(dut, proc, sync=False)

# test zero
def test_alu_zero_0():
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.add.value)
        yield from sub_proc(dut, 0, 1) # add 0 to 0
        out = yield dut.zero
        assert out == 0, f'ERROR: {out} != {0}'
    sim(dut, proc, sync=False)

# test zero
def test_alu_zero_1():
    dut = ALU(sim=True)
    def proc():
        yield dut.op.eq(AluOpCodes.add.value)
        yield from sub_proc(dut, 0, 0) # add 0 to 0
        out = yield dut.zero
        assert out == 1, f'ERROR: {out} != {1}'
    sim(dut, proc, sync=False)

       


if __name__ == '__main__':
    hdl = InOutBuff(ALU())
    cmd(hdl)