assemble.ml 8.2 KB

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