peephole.ml 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. open Types
  2. open Util
  3. let rec strip_comments = function
  4. | Comment _ :: tl -> strip_comments tl
  5. | InlineComment (EmptyLine, _) :: tl -> strip_comments tl
  6. | InlineComment (instr, _) :: tl -> strip_comments (instr :: tl)
  7. | hd :: tl -> hd :: (strip_comments tl)
  8. | [] -> []
  9. let rec peephole = function
  10. (* Constant load before branch becomes a jump when the branch condition
  11. * matches the loaded value ... *)
  12. | LoadImm (BoolVal b) :: Branch (cond, tgt) :: tl when cond = b ->
  13. InlineComment (Jump tgt, "branch -> jump") :: (peephole tl)
  14. (* ... otherwise, both instructions can be removed *)
  15. | LoadImm (BoolVal _) :: Branch (_, tgt) :: tl ->
  16. InlineComment (EmptyLine, "load + branch removed") :: peephole tl
  17. (* Transform addition/subtraction by constant to increment/decrement:
  18. * iload L | iload L
  19. * iloadc[_ ]C | iloadc_1
  20. * i{add,sub} | i{add,sub}
  21. * istore L | istore L
  22. * | |
  23. * v v
  24. * i{inc,dec} L C | i{inc,dec}_1 L
  25. *)
  26. | (Load (Int, Current, index) :: LoadImm (IntVal i) :: Op (Add, Int) ::
  27. Store (Int, Current, store) :: tl
  28. | LoadImm (IntVal i) :: Load (Int, Current, index) :: Op (Add, Int) ::
  29. Store (Int, Current, store) :: tl) when store = index ->
  30. InlineComment (Inc (index, i), "add -> inc") :: (peephole tl)
  31. | (Load (Int, Current, index) :: LoadImm (IntVal i) :: Op (Sub, Int) ::
  32. Store (Int, Current, store) :: tl
  33. | LoadImm (IntVal i) :: Load (Int, Current, index) :: Op (Sub, Int) ::
  34. Store (Int, Current, store) :: tl) when store = index ->
  35. InlineComment (Dec (index, i), "sub -> dec") :: (peephole tl)
  36. | hd :: tl -> hd :: (peephole tl)
  37. | [] -> []
  38. let rec phase input =
  39. log_line 1 "- Peephole optimization";
  40. match input with
  41. | Assembly instrs -> Assembly (peephole (strip_comments instrs))
  42. | _ -> raise (InvalidInput "peephole")