desug.ml 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. open Printf
  2. open Types
  3. open Util
  4. let rec var_init = function
  5. (* Move global initialisations to __init function *)
  6. | Program (decls, ann) ->
  7. let decls = flatten_blocks (List.map var_init decls) in
  8. let rec trav assigns = function
  9. | [] -> (assigns, [])
  10. | (Assign _ as hd) :: tl
  11. | (Allocate _ as hd) :: tl -> trav (assigns @ [hd]) tl
  12. | hd :: tl ->
  13. let (assigns, decls) = trav assigns tl in
  14. (assigns, (hd :: decls))
  15. in
  16. let (assigns, decls) = trav [] decls in (
  17. match assigns with
  18. | [] -> Program (decls, ann)
  19. | assigns ->
  20. let init_func = FunDef (true, Void, "__init", [], Block assigns, []) in
  21. Program (init_func :: decls, ann)
  22. )
  23. (* Global variable initialisation:
  24. * Add an assign statement and the Program node will remove it later on *)
  25. | GlobalDef (export, ctype, name, Some init, ann) ->
  26. Block [GlobalDef (export, ctype, name, None, ann);
  27. Assign (name, None, init, ann)]
  28. (* Global array definition:
  29. * - Create a new global variable for each dimension and initialise it to
  30. * the given expression
  31. * - create __allocate statement in __init *)
  32. | GlobalDef (export, Array (ctype, dims), name, None, ann) as dec ->
  33. let rec create_dimvars i = function
  34. | [] -> []
  35. | hd :: tl ->
  36. let dimname = name ^ "$" ^ string_of_int i in
  37. let var = Var (dimname, None, ann) in
  38. var :: (create_dimvars (i + 1) tl)
  39. in
  40. let dimvars = create_dimvars 1 dims in
  41. let create_globaldef dim = function
  42. | Var (dimname, None, ann) ->
  43. var_init (GlobalDef (export, Int, dimname, Some dim, ann))
  44. | _ -> raise InvalidNode
  45. in
  46. let vardecs = List.map2 create_globaldef dims dimvars in
  47. let alloc = [Allocate (name, dimvars, dec, ann)] in
  48. Block (vardecs @
  49. [GlobalDef (export, Array (ctype, dimvars), name, None, ann)] @
  50. alloc)
  51. (* Split local variable initialisations in declaration and assignment *)
  52. | FunDef (export, ret_type, name, params, Block body, ann) ->
  53. let move_inits body =
  54. let rec trav inits node = match node with
  55. (* Translate scalar array initialisation to ArrayScalar node,
  56. * for easy replacement later on *)
  57. | VarDec (Array _ as vtype, name, Some (BoolConst _ as v), ann) :: tl
  58. | VarDec (Array _ as vtype, name, Some (FloatConst _ as v), ann) :: tl
  59. | VarDec (Array _ as vtype, name, Some (IntConst _ as v), ann) :: tl ->
  60. let init = Some (ArrayInit (ArrayScalar v, vtype)) in
  61. trav inits (VarDec (vtype, name, init, ann) :: tl)
  62. (* Wrap ArrayConst in ArrayInit to pass dimensions *)
  63. | VarDec (Array _ as vtype, name, Some (ArrayConst _ as v), ann) :: tl ->
  64. let init = Some (ArrayInit (v, vtype)) in
  65. trav inits (VarDec (vtype, name, init, ann) :: tl)
  66. | VarDec (ctype, name, init, ann) as dec :: tl ->
  67. (* array definition: create __allocate statement *)
  68. let alloc = match ctype with
  69. | Array (_, dims) -> [Allocate (name, dims, dec, ann)]
  70. | _ -> []
  71. in
  72. (* initialisation: create assign statement *)
  73. let add = match init with
  74. | Some value -> alloc @ [Assign (name, None, value, ann)]
  75. | None -> alloc
  76. in
  77. VarDec (ctype, name, None, ann) :: (trav (inits @ add) tl)
  78. (* initialisations need to be placed after local functions *)
  79. | (FunDef (_, _, _, _, _, _) as h) :: tl ->
  80. (var_init h) :: (trav inits tl)
  81. (* rest of function body: recurse *)
  82. | rest -> inits @ (List.map var_init rest)
  83. in
  84. flatten_blocks (trav [] body)
  85. in
  86. let params = flatten_blocks (List.map var_init params) in
  87. FunDef (export, ret_type, name, params, Block (move_inits body), ann)
  88. | node -> transform_children var_init node
  89. let rec replace_var var replacement node =
  90. let trav = (replace_var var replacement) in
  91. match node with
  92. | Var (name, None, ann) when name = var ->
  93. Var (replacement, None, ann)
  94. | For (counter, start, stop, step, body, ann) when counter = var ->
  95. For (replacement, trav start, trav stop, trav step, trav body, ann)
  96. | node ->
  97. transform_children trav node
  98. let for_to_while node =
  99. let rec traverse new_vars = function
  100. | FunDef (export, ret_type, name, params, body, ann) ->
  101. let new_vars = ref [] in
  102. let body = traverse new_vars body in
  103. let create_vardec name = VarDec (Int, name, None, []) in
  104. let new_vardecs = List.map create_vardec !new_vars in
  105. let _body = new_vardecs @ (flatten_blocks (block_body body)) in
  106. FunDef (export, ret_type, name, params, Block _body, ann)
  107. (* Transform for-loops to while-loops *)
  108. | For (counter, start, stop, step, body, ann) ->
  109. let _i = fresh_var counter in
  110. let _stop = fresh_const "stop" in
  111. let _step = fresh_const "step" in
  112. new_vars := !new_vars @ [_i; _stop; _step];
  113. let vi = Var (_i, None, []) in
  114. let vstop = Var (_stop, None, annof stop) in
  115. let vstep = Var (_step, None, annof step) in
  116. let cond = Cond (
  117. Binop (Gt, vstep, IntConst (0, []), []),
  118. Binop (Lt, vi, vstop, []),
  119. Binop (Gt, vi, vstop, []),
  120. []
  121. ) in
  122. Block [
  123. Assign (_i, None, start, annof start);
  124. Assign (_stop, None, stop, annof stop);
  125. Assign (_step, None, step, annof step);
  126. traverse new_vars (While (cond, (Block (
  127. block_body (replace_var counter _i body) @
  128. [Assign (_i, None, Binop (Add, vi, vstep, []), [])]
  129. )), ann));
  130. ]
  131. (* Transform while-loops to do-while loops in if-statements *)
  132. | While (cond, body, ann) ->
  133. let cond = traverse new_vars cond in
  134. let body = traverse new_vars body in
  135. Block [If (cond, Block [DoWhile (cond, body, ann)], ann)]
  136. | node -> transform_children (traverse new_vars) node
  137. in
  138. traverse (ref []) node
  139. let rec array_init = function
  140. (* Transform scalar assignment into nested for-loops *)
  141. | Assign (name, None, ArrayInit (ArrayScalar value, Array (_, dims)), ann) ->
  142. let rec add_loop indices = function
  143. | [] ->
  144. Assign (name, Some indices, value, ann)
  145. | dim :: rest ->
  146. let counter = fresh_var "i" in
  147. let body = Block [add_loop (indices @ [Var (counter, None, [])]) rest] in
  148. For (counter, IntConst (0, []), dim, IntConst (1, []), body, [])
  149. in
  150. add_loop [] dims
  151. (* Transform array constant inisialisation into separate assign statements
  152. * for all entries in the constant array *)
  153. (* TODO: only allow when array dimensions are constant? *)
  154. | Assign (name, None, ArrayInit (ArrayConst _ as value, Array (_, dims)), ann) ->
  155. let ndims = list_size dims in
  156. let rec make_assigns depth i indices = function
  157. | [] -> []
  158. | hd :: tl ->
  159. let assigns = traverse depth (i :: indices) hd in
  160. make_assigns depth (i + 1) indices tl @ assigns
  161. and traverse depth indices = function
  162. | ArrayConst (values, _) ->
  163. make_assigns (depth + 1) 0 indices values
  164. | value when depth = ndims ->
  165. let indices = List.map (fun i -> IntConst (i, [])) indices in
  166. [Assign (name, Some (List.rev indices), value, ann)]
  167. | node ->
  168. let msg = sprintf
  169. "dimension mismatch: expected %d nesting levels, got %d"
  170. ndims depth
  171. in
  172. raise (NodeError (node, msg))
  173. in
  174. Block (List.rev (traverse 0 [] value))
  175. | node -> transform_children array_init node
  176. (* Generate new variables for array dimensions in function bodies, to avoid
  177. * re-evalutation after array dimension reduction. For example:
  178. *
  179. * int dims = 0;
  180. *
  181. * int dim() {
  182. * dims = dims 1; // Side effect => dims() should be called once
  183. * return 10;
  184. * }
  185. *
  186. * void foo() {
  187. * int[10, dim()] arr;
  188. * arr[0, 1] = 1;
  189. * }
  190. *
  191. * After dimension reduction, this would become:
  192. * void foo() {
  193. * int[] arr;
  194. * arr = allocate(10, dim());
  195. * arr[1 * dim() + 0] = 1;
  196. * }
  197. *
  198. * This behaviour is of course incorrect. To avoid dim() from being evaluated
  199. * twice, the snippet above is transformed into (note the $$ which will help
  200. * later during constant propagation):
  201. * void foo() {
  202. * int a$dim$$1 = 10;
  203. * int a$dim$$2 = dim();
  204. * int[a$dim$$1, a$dim$$2] arr;
  205. * arr[1, 2] = 1;
  206. * }
  207. *
  208. * ... which then becomes:
  209. * void foo() {
  210. * int a$dim$$1;
  211. * int a$dim$$2;
  212. * int[a$dim$$1, a$dim$$2] arr;
  213. * a$dim$1 = 10;
  214. * a$dim$2 = dim();
  215. * arr = __allocate(a$dim$1 * a$dim$2);
  216. * arr[1 * a$dim$2 * 0] = 1;
  217. * }
  218. * *)
  219. let rec array_dims = function
  220. | VarDec (Array (ctype, dims), name, init, ann) ->
  221. let make_dimname i _ = name ^ "$dim$$" ^ string_of_int (i + 1) in
  222. let dimnames = mapi make_dimname dims in
  223. let make_dimvar d n = Var (n, None, annof d) in
  224. let dimvars = List.map2 make_dimvar dims dimnames in
  225. let make_dimdec dimname dim = VarDec (Int, dimname, Some dim, []) in
  226. let dimdecs = List.map2 make_dimdec dimnames dims in
  227. Block (dimdecs @ [VarDec (Array (ctype, dimvars), name, init, ann)])
  228. | node -> transform_children array_dims node
  229. let rec phase input =
  230. log_line 2 "- Desugaring";
  231. match input with
  232. | Types node ->
  233. Types (for_to_while (array_init (var_init (array_dims node))))
  234. | _ -> raise (InvalidInput "desugar")