/projects/02/ALU.hdl

https://github.com/cpatuzzo/nand2tetris · Unknown · 79 lines · 67 code · 12 blank · 0 comment · 0 complexity · 2e9e564bef16f4bb99aa54d87e68505f MD5 · raw file

  1. // This file is part of www.nand2tetris.org
  2. // and the book "The Elements of Computing Systems"
  3. // by Nisan and Schocken, MIT Press.
  4. // File name: projects/02/ALU.hdl
  5. /**
  6. * The ALU. Computes one of the following functions:
  7. * x+y, x-y, y-x, 0, 1, -1, x, y, -x, -y, !x, !y,
  8. * x+1, y+1, x-1, y-1, x&y, x|y on two 16-bit inputs.
  9. * Which function to compute is determined by 6 input bits
  10. * denoted zx, nx, zy, ny, f, no.
  11. * The computed function's value is called "out".
  12. * In addition to computing out, the ALU computes two
  13. * 1-bit outputs called zr and ng:
  14. * if out == 0, zr = 1; otherwise zr = 0;
  15. * If out < 0, ng = 1; otherwise ng = 0.
  16. * The 6-bit combinations (zx,nx,zy,ny,f,no) and
  17. * their effect are documented in the book.
  18. */
  19. // Implementation: the ALU manipulates the x and y
  20. // inputs and then operates on the resulting values,
  21. // as follows:
  22. // if (zx == 1) sets x = 0 // 16-bit constant
  23. // if (nx == 1) sets x = ~x // bitwise "not"
  24. // if (zy == 1) sets y = 0 // 16-bit constant
  25. // if (ny == 1) sets y = ~y // bitwise "not"
  26. // if (f == 1) sets out = x + y // integer 2's-complement addition
  27. // if (f == 0) sets out = x & y // bitwise And
  28. // if (no == 1) sets out = ~out // bitwise Not
  29. // if (out == 0) sets zr = 1
  30. // if (out < 0) sets ng = 1
  31. CHIP ALU {
  32. IN
  33. x[16], y[16], // 16-bit inputs
  34. zx, // zero the x input?
  35. nx, // negate the x input?
  36. zy, // zero the y input?
  37. ny, // negate the y input?
  38. f, // compute out = x + y (if f == 1) or out = x & y (if == 0)
  39. no; // negate the out output?
  40. OUT
  41. out[16], // 16-bit output
  42. zr, // 1 if (out == 0), 0 otherwise
  43. ng; // 1 if (out < 0), 0 otherwise
  44. PARTS:
  45. // zx
  46. Mux16(a=x, b=false, sel=zx, out=x1);
  47. // nx
  48. Not16(in=x1, out=notx1);
  49. Mux16(a=x1, b=notx1, sel=nx, out=x2);
  50. // zy
  51. Mux16(a=y, b=false, sel=zy, out=y1);
  52. // ny
  53. Not16(in=y1, out=noty1);
  54. Mux16(a=y1, b=noty1, sel=ny, out=y2);
  55. // f
  56. And16(a=x2, b=y2, out=and);
  57. Add16(a=x2, b=y2, out=add);
  58. Mux16(a=and, b=add, sel=f, out=func);
  59. // no, ng
  60. Not16(in=func, out=notfunc);
  61. Mux16(a=func, b=notfunc, sel=no, out=out, out[0..7]=lower, out[8..15]=upper, out[15]=ng);
  62. // zr
  63. Or8Way(in=lower, out=or1);
  64. Or8Way(in=upper, out=or2);
  65. Or(a=or1, b=or2, out=or);
  66. Not(in=or, out=zr);
  67. }