assemble.ml 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. open Printf
  2. open Types
  3. open Util
  4. open Stringify
  5. let comline comment = InlineComment (EmptyLine, comment)
  6. let assemble program =
  7. let labcounter = ref 0 in
  8. let genlabel suffix =
  9. labcounter := !labcounter + 1;
  10. string_of_int !labcounter ^ "_" ^ suffix
  11. in
  12. let consts = Hashtbl.create 20 in
  13. let rec trav node =
  14. let rec trav_all = function
  15. | [] -> []
  16. | hd :: tl -> trav hd @ (trav_all tl)
  17. in
  18. let rec traverse_localfuns = function
  19. | LocalFuns body -> List.concat (List.map trav body)
  20. | Block body -> List.concat (List.map traverse_localfuns body)
  21. | _ -> []
  22. in
  23. match node with
  24. (* Global *)
  25. | Program (decls, _) ->
  26. trav_all decls
  27. | GlobalDef (_, ctype, name, _, _) ->
  28. [Comment (sprintf "global var \"%s\" at index %d" name (indexof node));
  29. Global ctype]
  30. | FunDec (ret_type, name, params, _) ->
  31. [Comment (sprintf "extern fun \"%s\" at index %d" name (indexof node));
  32. Import (name, ret_type, List.map typeof params)]
  33. | FunDef (export, ret_type, name, params, body, _) ->
  34. let label = labelof node in
  35. (if export then
  36. let param_types = List.map typeof params in
  37. [Export (name, ret_type, param_types, label)]
  38. else []) @
  39. [Comment (sprintf "fun \"%s\" with %d local vars" label (indexof node));
  40. Label label;
  41. RtnEnter (indexof node)] @
  42. (trav body) @
  43. (match ret_type with Void -> [Ret Void] | _ -> []) @
  44. [EmptyLine] @
  45. (traverse_localfuns body)
  46. | VarDec (_, name, _, _) ->
  47. [comline (sprintf "local var \"%s\" at index %d" name (indexof node))]
  48. | LocalFuns _ -> []
  49. | Block body | VarDecs body -> trav_all body
  50. (* Statements *)
  51. | VarLet (dec, None, value, _) ->
  52. let store = match (depthof dec, depthof node) with
  53. | (0, _) -> Store (typeof dec, Glob, indexof dec)
  54. | (a, b) when a = b -> Store (typeof dec, Current, indexof dec)
  55. | (a, b) -> Store (typeof dec, Rel (b - a), indexof dec)
  56. in
  57. trav value @ [InlineComment (store, node2str node)]
  58. | Return (value, _) ->
  59. trav value @ [InlineComment (Ret (typeof value), node2str node)]
  60. | If (cond, body, _) ->
  61. let endlabel = genlabel "end" in
  62. (trav cond) @
  63. [Branch (false, endlabel);
  64. comline ("if (" ^ (node2str cond) ^ ") {")] @
  65. (trav body) @
  66. [comline "}";
  67. Label endlabel]
  68. | IfElse (cond, true_body, false_body, _) ->
  69. let elselabel = genlabel "else" in
  70. let endlabel = genlabel "end" in
  71. (trav cond) @
  72. [Branch (false, elselabel);
  73. comline ("if (" ^ (node2str cond) ^ ") {")] @
  74. (trav true_body) @
  75. [Jump endlabel;
  76. comline "} else {";
  77. Label elselabel] @
  78. (trav false_body) @
  79. [comline "}";
  80. Label endlabel]
  81. | While (cond, body, _) ->
  82. let startlabel = genlabel "while" in
  83. let endlabel = genlabel "end" in
  84. let com = ("while (" ^ (node2str cond) ^ ") {") in
  85. [Label startlabel] @
  86. (trav cond) @
  87. [InlineComment (Branch (false, endlabel), com)] @
  88. (trav body) @
  89. [Jump startlabel;
  90. Label endlabel;
  91. comline "}"]
  92. | DoWhile (cond, body, _) ->
  93. let startlabel = genlabel "dowhile" in
  94. let com = ("} while (" ^ (node2str cond) ^ ");") in
  95. [comline "do {";
  96. Label startlabel] @
  97. (trav body) @
  98. (trav cond) @
  99. [InlineComment (Branch (true, startlabel), com)]
  100. (* Expression statement pops the disregarded expression value from the
  101. * stack, if any *)
  102. | Expr value ->
  103. let pop = match typeof value with
  104. | Void -> [comline (node2str node)]
  105. | ctype -> [InlineComment (Pop ctype, node2str node)]
  106. in
  107. (trav value) @ pop
  108. (* Expressions *)
  109. (* Immediate values are handled here, and not in the peephole optimizer,
  110. * for convenience: the indices in the constant table would be altered,
  111. * so entries cannot be removed. By this early detection (also during
  112. * index analysis), they are not added in the first place *)
  113. | Const (value, _) when is_immediate_const value ->
  114. [InlineComment (LoadImm value, node2str node)]
  115. | Const (value, _) ->
  116. Hashtbl.replace consts value (indexof node);
  117. let load = LoadConst (typeof node, indexof node) in
  118. [InlineComment (load, node2str node)]
  119. | VarUse (dec, None, _) ->
  120. let load = match (depthof dec, depthof node) with
  121. | (0, _) -> Load (typeof dec, Glob, indexof dec)
  122. | (a, b) when a = b -> Load (typeof dec, Current, indexof dec)
  123. | (a, b) -> Load (typeof dec, Rel (b - a), indexof dec)
  124. in
  125. [InlineComment (load, node2str node)]
  126. | Monop (op, value, _) ->
  127. (trav value) @
  128. [InlineComment (Op (op, typeof value), op2str op)]
  129. | Binop (op, left, right, _) ->
  130. (trav left) @
  131. (trav right) @
  132. [InlineComment (Op (op, typeof left), op2str op)]
  133. | TypeCast (ctype, value, _) ->
  134. let vtype = typeof value in
  135. (match (ctype, vtype) with
  136. | (Float, Int) | (Int, Float) -> ()
  137. | _ ->
  138. let msg = sprintf
  139. "invalid typecast: %s -> %s"
  140. (type2str vtype) (type2str ctype)
  141. in raise (NodeError (node, msg))
  142. );
  143. trav value @ [Convert (vtype, ctype)]
  144. (* Function calls *)
  145. | FunUse (dec, args, _) ->
  146. let init = match (depthof dec, depthof node) with
  147. | (0, _) -> RtnInit Glob
  148. | (a, b) when a = b - 1 -> RtnInit Current
  149. | (a, b) when a = b -> RtnInit Local
  150. | (a, b) -> RtnInit (Rel (b - a - 1))
  151. in
  152. let jmp = match dec with
  153. | FunDec _ -> RtnJmp (ExternFun (indexof dec))
  154. | FunDef _ -> RtnJmp (LocalFun (List.length args, labelof dec))
  155. | _ -> raise InvalidNode
  156. in
  157. init :: (trav_all args) @ [jmp]
  158. | Arg value -> trav value
  159. (* Conditional expression (short-circuit evaluation) *)
  160. (* <cond>
  161. * branch_f else
  162. * <true_expr>
  163. * jump end
  164. * else:
  165. * <false_expr>
  166. * end:
  167. *)
  168. | Cond (cond, texp, fexp, _) ->
  169. let elselabel = genlabel "false_expr" in
  170. let endlabel = genlabel "end" in
  171. (trav cond) @
  172. [Branch (false, elselabel)] @
  173. (trav texp) @
  174. [Jump (endlabel);
  175. Label (elselabel)] @
  176. (trav fexp) @
  177. [InlineComment (Label (endlabel), node2str node)]
  178. (* Arrays *)
  179. | Allocate (dec, dims, _) ->
  180. let store = match (depthof dec, depthof node) with
  181. | (0, _) -> Store (typeof dec, Glob, indexof dec)
  182. | (a, b) when a = b -> Store (typeof dec, Current, indexof dec)
  183. | _ -> raise InvalidNode
  184. in
  185. trav_all dims @
  186. [NewArray (basetypeof dec, List.length dims);
  187. InlineComment (store, node2str node)]
  188. | VarUse (dec, Some dims, _) ->
  189. let load = match (depthof dec, depthof node) with
  190. | (0, _) -> Load (typeof dec, Glob, indexof dec)
  191. | (a, b) when a = b -> Load (typeof dec, Current, indexof dec)
  192. | (a, b) -> Load (typeof dec, Rel (b - a), indexof dec)
  193. in
  194. (trav_all (List.rev dims)) @ (* push dimensions *)
  195. [InlineComment (load, nameof dec)] @ (* push array reference *)
  196. [InlineComment (LoadArray (basetypeof dec), node2str node)]
  197. | VarLet (dec, Some dims, value, _) ->
  198. let load = match (depthof dec, depthof node) with
  199. | (0, _) -> Load (typeof dec, Glob, indexof dec)
  200. | (a, b) when a = b -> Load (typeof dec, Current, indexof dec)
  201. | (a, b) -> Load (typeof dec, Rel (b - a), indexof dec)
  202. in
  203. (trav value) @ (* push value *)
  204. (trav_all dims) @ (* push dimensions *)
  205. [InlineComment (load, nameof dec)] @ (* push array reference *)
  206. [InlineComment (StoreArray (basetypeof dec), node2str node)]
  207. | _ -> raise InvalidNode
  208. in
  209. let instrs = trav program in
  210. (* Sort aggregated constants and add definitions
  211. * If possible, this should be rewritten in the future because it's a little
  212. * cumbersome right now... *)
  213. let pairs = ref [] in
  214. let add_pair value index =
  215. let com = sprintf "index %d" index in
  216. pairs := (InlineComment (ConstDef value, com), index) :: !pairs;
  217. in
  218. Hashtbl.iter add_pair consts;
  219. let cmp (_, i) (_, j) = compare i j in
  220. let sorted_pairs = List.sort cmp !pairs in
  221. let const_defs = List.map (fun (d, _) -> d) sorted_pairs in
  222. instrs @ const_defs
  223. let phase = function
  224. | Ast node -> Assembly (assemble node)
  225. | _ -> raise (InvalidInput "assembly")