Files
eceg431/02/ALU.hdl
2025-09-03 10:18:19 -04:00

81 lines
2.7 KiB
Plaintext

// This file is part of www.nand2tetris.org
// and the book "The Elements of Computing Systems"
// by Nisan and Schocken, MIT Press.
// File name: projects/2/ALU.hdl
/**
* ALU (Arithmetic Logic Unit):
* Computes out = one of the following functions:
* 0, 1, -1,
* x, y, !x, !y, -x, -y,
* x + 1, y + 1, x - 1, y - 1,
* x + y, x - y, y - x,
* x & y, x | y
* on the 16-bit inputs x, y,
* according to the input bits zx, nx, zy, ny, f, no.
* In addition, computes the two output bits:
* if (out == 0) zr = 1, else zr = 0
* if (out < 0) ng = 1, else ng = 0
*/
// Implementation: Manipulates the x and y inputs
// and operates on the resulting values, as follows:
// if (zx == 1) sets x = 0 // 16-bit constant
// if (nx == 1) sets x = !x // bitwise not
// if (zy == 1) sets y = 0 // 16-bit constant
// if (ny == 1) sets y = !y // bitwise not
// if (f == 1) sets out = x + y // integer 2's complement addition
// if (f == 0) sets out = x & y // bitwise and
// if (no == 1) sets out = !out // bitwise not
CHIP ALU {
IN
x[16], y[16], // 16-bit inputs
zx, // zero the x input?
nx, // negate the x input?
zy, // zero the y input?
ny, // negate the y input?
f, // compute (out = x + y) or (out = x & y)?
no; // negate the out output?
OUT
out[16], // 16-bit output
zr, // if (out == 0) equals 1, else 0
ng; // if (out < 0) equals 1, else 0
PARTS:
// handle zx (zero x)
Mux16(a=x, b=false, sel=zx, out=x1);
// handle nx (negate x)
Not16(in=x1, out=notx1);
Mux16(a=x1, b=notx1, sel=nx, out=x2);
// handle zy (zero y)
Mux16(a=y, b=false, sel=zy, out=y1);
// handle ny (negate y)
Not16(in=y1, out=noty1);
Mux16(a=y1, b=noty1, sel=ny, out=y2);
// handle f (+ or &)
// do both ops here, is this wasteful? otherwise we run an or, but then we have to "predict"
Add16(a=x2, b=y2, out=addout);
And16(a=x2, b=y2, out=andout);
Mux16(a=andout, b=addout, sel=f, out=fout);
// handle no (negate out)
Not16(in=fout, out=notfout);
Mux16(a=fout, b=notfout, sel=no, out=out, out[0..7]=outLow, out[8..15]=outHigh, out[15]=sign);
// compute zr (zero flag)
// check if any bits in low 8 are set
Or8Way(in=outLow, out=tmp1);
// check if any bits in high 8 are set
Or8Way(in=outHigh, out=tmp2);
// combine both halves (true if any bit is set)
Or(a=tmp1, b=tmp2, out=notzr);
// zr = true if no bits are set (output is zero)
Not(in=notzr, out=zr);
// compute ng (negative flag)
And(a=sign, b=true, out=ng);
}