desug.ml 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. open Printf
  2. open Types
  3. open Util
  4. (* Generate new variables for array dimensions, to avoid re-evalutation when
  5. * array dimensions are used (e.g., after array dimension reduction). *)
  6. let move_array_dims node =
  7. let patch_dims basename values make_decs make_dimname =
  8. let names = mapi (fun i _ -> make_dimname basename i) values in
  9. let decs = List.concat (List.map2 make_decs values names) in
  10. let make_dim value name = Dim (name, annof value) in
  11. let dims = List.map2 make_dim values names in
  12. (decs, dims)
  13. in
  14. let fresh_dim name _ = fresh_const name in
  15. let rec trav = function
  16. | VarDec (ArrayDims (ctype, values), name, init, ann) ->
  17. let make_decs value name = [VarDec (Int, name, Some value, [])] in
  18. let decs, dims = patch_dims name values make_decs fresh_dim in
  19. Block (decs @ [VarDec (ArrayDims (ctype, dims), name, init, ann)])
  20. (* Omit the trailing "_" for exported variables since they should not be
  21. * pruned by optimisations *)
  22. | GlobalDef (export, ArrayDims (ctype, values), name, init, ann) ->
  23. let make_dimname = if export then generate_array_dim else fresh_dim in
  24. let make_decs value name = [GlobalDef (export, Int, name, Some value, [])] in
  25. let decs, dims = patch_dims name values make_decs make_dimname in
  26. Block (decs @ [GlobalDef (export, ArrayDims (ctype, dims), name, init, ann)])
  27. | node -> traverse_unit trav node
  28. in
  29. trav node
  30. (* Create new constant variables for scalar initialisations on arrays so that
  31. * they are only evaluated once *)
  32. let rec move_scalar_inits = function
  33. (* Prevent next match for ArrayConst initialisations *)
  34. | VarDec (ArrayDims _, _, Some (ArrayConst _), _) as node ->
  35. node
  36. (* Add vardec for scalar value *)
  37. | VarDec (ArrayDims (ctype, dims) as atype, name, Some value, ann) ->
  38. let scalar_dec = VarDec (ctype, fresh_const "scalar", Some value, ann) in
  39. let scalar_use = VarUse (scalar_dec, None, annof value) in
  40. Block [scalar_dec; VarDec (atype, name, Some scalar_use, ann)]
  41. | node -> traverse_unit move_scalar_inits node
  42. (* Split variable initialisation into declaration and assignment *)
  43. let rec split_inits = function
  44. | VarDec (ctype, name, Some init, ann) ->
  45. let dec = VarDec (ctype, name, None, ann) in
  46. Block [dec; VarLet (dec, None, init, ann)]
  47. | GlobalDef (export, ctype, name, Some init, ann) ->
  48. let dec = GlobalDef (export, ctype, name, None, ann) in
  49. Block [dec; VarLet (dec, None, init, ann)]
  50. | node -> traverse_unit split_inits node
  51. (* Add __allocate statements after array declarations *)
  52. let rec add_allocs node =
  53. let create_dimvar = function
  54. | Dim (name, _) as dim -> VarUse (dim, None, [])
  55. | _ -> raise InvalidNode
  56. in
  57. match node with
  58. | VarDec (ArrayDims (_, dims), _, _, ann) ->
  59. Block [node; Allocate (node, List.map create_dimvar dims, ann)]
  60. | GlobalDef (_, ArrayDims (_, dims), _, _, ann) ->
  61. Block [node; Allocate (node, List.map create_dimvar dims, ann)]
  62. | node -> traverse_unit add_allocs node
  63. let dimsof = function
  64. | GlobalDef (_, ArrayDims (_, dims), _, _, _)
  65. | VarDec (ArrayDims (_, dims), _, _, _) -> dims
  66. | _ -> raise InvalidNode
  67. let rec array_init = function
  68. (* Transform array constant initialisation into separate assign statements
  69. * for all entries in the array literal *)
  70. | VarLet (dec, None, (ArrayConst _ as value), ann) ->
  71. let intconst i = Const (IntVal (Int32.of_int i), []) in
  72. let ndims = List.length (dimsof dec) in
  73. let rec make_assigns depth i indices = function
  74. | [] -> []
  75. | hd :: tl ->
  76. let assigns = trav depth (i :: indices) hd in
  77. make_assigns depth (i + 1) indices tl @ assigns
  78. and trav depth indices = function
  79. | ArrayConst (values, _) ->
  80. make_assigns (depth + 1) 0 indices values
  81. | value when depth = ndims ->
  82. let indices = List.map intconst indices in
  83. [VarLet (dec, Some (List.rev indices), value, ann)]
  84. | node ->
  85. raise (FatalError (NodeMsg (node, sprintf
  86. "dimension mismatch: expected %d nesting levels, got %d"
  87. ndims depth)))
  88. in
  89. Block (List.rev (trav 0 [] value))
  90. (* Scalar initialisation *)
  91. | VarLet (dec, None, scalar, ann) when is_array dec ->
  92. let rec nest_loops indices = function
  93. | [] -> Block [VarLet (dec, Some (List.rev indices), scalar, [])]
  94. | dim :: tl ->
  95. let counter = fresh_id "i" in
  96. let start = Const (IntVal 0l, []) in
  97. let stop = VarUse (dim, None, ann) in
  98. let step = Const (IntVal 1l, []) in
  99. let body = nest_loops (Var (counter, None, []) :: indices) tl in
  100. For (counter, start, stop, step, body, [])
  101. in
  102. nest_loops [] (dimsof dec)
  103. | node -> traverse_unit array_init node
  104. let rec for_to_while = function
  105. (* Transform for-loops to while-loops *)
  106. | For (counter, start, stop, step, body, ann) ->
  107. let dec name init = VarDec (Int, name, Some init, []) in
  108. let _i = dec counter start in
  109. let _stop = dec (fresh_const "stop") stop in
  110. let _step = dec (fresh_const "step") step in
  111. let vi = VarUse (_i, None, []) in
  112. let vstop = VarUse (_stop, None, annof stop) in
  113. let vstep = VarUse (_step, None, annof step) in
  114. let cond =
  115. Cond (
  116. Binop (Gt, vstep, Const (IntVal 0l, []), []),
  117. Binop (Lt, vi, vstop, []),
  118. Binop (Gt, vi, vstop, []),
  119. [])
  120. in
  121. Block [
  122. _i; _stop; _step;
  123. While (cond, (Block (
  124. [body; VarLet (_i, None, Binop (Add, vi, vstep, []), [])]
  125. )), ann) |> for_to_while;
  126. ]
  127. (* Transform while-loops to do-while loops in if-statements *)
  128. (* DISABLED, while-loops are explicitly supported by the assembly phase
  129. | While (cond, body, ann) ->
  130. If (cond, DoWhile (cond, for_to_while body, ann), ann)
  131. *)
  132. | node -> traverse_unit for_to_while node
  133. let rec move_vardecs = function
  134. | FunDef (export, ret_type, name, params, body, ann) ->
  135. let rec trav = function
  136. | FunDef _ as node -> (move_vardecs node, [])
  137. | VarDec _ as node -> (DummyNode, [node])
  138. | node -> traverse_list trav node
  139. in
  140. let body, decs = traverse_list trav body in
  141. let body = Block (decs @ (block_body body)) in
  142. FunDef (export, ret_type, name, params, body, ann)
  143. | node -> traverse_unit move_vardecs node
  144. let rec move_inits = function
  145. | Block (VarDecs decs :: (LocalFuns _ as funs) :: body)->
  146. let rec extract_stats decs stats = function
  147. | VarDec _ as dec :: tl -> extract_stats (dec :: decs) stats tl
  148. | stat :: tl -> extract_stats decs (stat :: stats) tl
  149. | [] -> List.rev decs, List.rev stats
  150. in
  151. let decs, stats = extract_stats [] [] decs in
  152. Block (VarDecs decs :: funs :: stats @ body)
  153. | node -> traverse_unit move_inits node
  154. let rec move_global_inits = function
  155. (* Move global initialisations to __init function *)
  156. | Program (decls, ann) ->
  157. let decls = List.map move_global_inits decls in
  158. let rec extract_inits inits = function
  159. | [] ->
  160. (List.rev inits, [])
  161. | (VarLet _ as hd) :: tl
  162. | (Allocate _ as hd) :: tl ->
  163. extract_inits (hd :: inits) tl
  164. | hd :: tl ->
  165. let inits, tl = extract_inits inits tl in
  166. (inits, (hd :: tl))
  167. in
  168. begin match extract_inits [] decls with
  169. | ([], _) -> Program (decls, ann)
  170. | (inits, decls) ->
  171. let init_func = FunDef (true, Void, "__init", [], Block inits, []) in
  172. Program (init_func :: decls, ann)
  173. end
  174. | node -> traverse_unit move_global_inits node
  175. let rec group_vardecs = function
  176. | FunDef (export, ret_type, name, params, Block body, ann) ->
  177. let rec create = function
  178. | (VarDec _ as hd) :: tl -> VarDecs [hd] :: create tl
  179. | tl -> tl
  180. in
  181. let rec merge = function
  182. | VarDecs [a] :: VarDecs b :: tl -> merge (VarDecs (a :: b) :: tl)
  183. | VarDecs a :: VarDecs b :: tl -> merge (VarDecs (a @ b) :: tl)
  184. | tl -> tl
  185. in
  186. let body = Block (create body |> merge) |> group_vardecs in
  187. FunDef (export, ret_type, name, params, body, ann)
  188. | node -> traverse_unit group_vardecs node
  189. let phase = function
  190. | Ast node ->
  191. Ast begin
  192. (* Move array dimensions and scalar initialisations into new variables as
  193. * initialisations, so that they are evaluated exactly once, and so that
  194. * dimension names are consistent with the array name *)
  195. move_array_dims node |> move_scalar_inits |>
  196. (* Split variable initialisations into declarations and assignments *)
  197. split_inits |> add_allocs |>
  198. (* Transform ArrayConst assignment to assignments into for-loops *)
  199. array_init |>
  200. (* Transform for-loops to while-loops *)
  201. for_to_while |> split_inits |>
  202. (* Move initialization assignments to the function body *)
  203. move_inits |>
  204. (* Move variable declarations to the beginning of the function *)
  205. move_vardecs |>
  206. (* Move global initialisation assignments to __init *)
  207. move_global_inits |>
  208. (* Create and merge VarDecs nodes at the start of each function *)
  209. group_vardecs |>
  210. (* Propagate new declaration properties to uses (since we have no
  211. * pointers) *)
  212. Context.analyse false
  213. end
  214. | _ -> raise InvalidInput