A "high-level" language for the Gameboy
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

63 lines
1.8 KiB

  1. import { R8 } from "./cpu"
  2. import { Loc, LocType } from "../ir/loc"
  3. import { Operand, AbsInsn2, insnReduce2 } from "../ir/insn"
  4. import { BinaryOp, UnaryOp } from "../ast"
  5. import type { SM83Insn } from "./insn"
  6. export const realizeBlock = (block: Array<AbsInsn2>): Array<SM83Insn> => block.flatMap(realizeInsn)
  7. export const realizeInsn = (insn: AbsInsn2): Array<SM83Insn> => insnReduce2(realizeCopy, realizeUnary, insn)
  8. const getSourceName = (source: Operand): string => typeof source === "number"
  9. ? source.toString()
  10. : source.asmName()
  11. export const realizeCopy = (dest: Loc, source: Operand): Array<SM83Insn> => [
  12. `LD ${dest.asmName()}, ${getSourceName(source)}`
  13. ]
  14. export const realizeUnary = (dest: Loc, op: UnaryOp | BinaryOp, source: Operand): Array<SM83Insn> => {
  15. if (!isA(dest)) {
  16. throw new Error("unexpected form for unary operation")
  17. }
  18. let output: Array<SM83Insn> = []
  19. switch (op) {
  20. case "add":
  21. return [`ADD ${getSourceName(source)}`]
  22. case "subtract":
  23. return [`SUB ${getSourceName(source)}`]
  24. case "bit_and":
  25. return [`AND ${getSourceName(source)}`]
  26. case "bit_or":
  27. return [`OR ${getSourceName(source)}`]
  28. case "bit_xor":
  29. return [`XOR ${getSourceName(source)}`]
  30. case "shift_left":
  31. for (let i = 0; i < source; ++i) {
  32. output.push("SLA A")
  33. }
  34. return output
  35. case "shift_right":
  36. for (let i = 0; i < source; ++i) {
  37. output.push("SRL A")
  38. }
  39. return output
  40. case "arith_negate":
  41. return ["CPL", "INC A"]
  42. case "bit_negate":
  43. return ["CPL"]
  44. }
  45. }
  46. const isA = (loc: Operand): boolean =>
  47. typeof loc === "object" && loc.type === LocType.REGISTER && loc.name === R8.A