-
Notifications
You must be signed in to change notification settings - Fork 0
/
ALU.hdl
executable file
·72 lines (57 loc) · 2.22 KB
/
ALU.hdl
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
// This file is part of the materials accompanying the book
// "The Elements of Computing Systems" by Nisan and Schocken,
// MIT Press. Book site: www.idc.ac.il/tecs
// File name: projects/02/ALU.hdl
/**
* The ALU. Computes a pre-defined set of functions out = f(x,y)
* where x and y are two 16-bit inputs. The function f is selected
* by a set of 6 control bits denoted zx, nx, zy, ny, f, no.
* The ALU operation can be described using the following pseudocode:
* if zx=1 set x = 0 // 16-bit zero constant
* if nx=1 set x = !x // Bit-wise negation
* if zy=1 set y = 0 // 16-bit zero constant
* if ny=1 set y = !y // Bit-wise negation
* if f=1 set out = x + y // Integer 2's complement addition
* else set out = x & y // Bit-wise And
* if no=1 set out = !out // Bit-wise negation
*
* In addition to computing out, the ALU computes two 1-bit outputs:
* if out=0 set zr = 1 else zr = 0 // 16-bit equality comparison
* if out<0 set ng = 1 else ng = 0 // 2's complement comparison
*/
CHIP ALU {
IN // 16-bit inputs:
x[16], y[16],
// Control bits:
zx, // Zero the x input
nx, // Negate the x input
zy, // Zero the y input
ny, // Negate the y input
f, // Function code: 1 for add, 0 for and
no; // Negate the out output
OUT // 16-bit output
out[16],
// ALU output flags
zr, // 1 if out=0, 0 otherwise
ng; // 1 if out<0, 0 otherwise
PARTS:
Mux16(a=x, b=false, sel=zx, out=azx);
Not16(in=azx, out=notx);
Mux16(a=azx, b=notx, sel=nx, out=anx);
Mux16(a=y, b=false, sel=zy, out=azy);
Not16(in=azy, out=noty);
Mux16(a=azy, b=noty, sel=ny, out=any);
Add16(a=anx, b=any, out=add);
And16(a=anx, b=any, out=and);
Mux16(a=and, b=add, sel=f, out=res);
Not16(in=res, out=nres);
Mux16(a=res, b=nres, sel=no, out=ores);
And16(a=ores, b=true, out[0..7]=orl, out[8..15]=orh, out[15]=ormax);
And16(a=ores, b=true, out=out);
Not(in=ormax, out=ngc);
Not(in=ngc, out=ng);
Or8Way(in=orl, out=fh);
Or8Way(in=orh, out=sh);
Or(a=fh, b=sh, out=orOut);
Not(in=orOut, out=zr);
}