bf.ml 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. open Llvm
  2. type program = command list
  3. and command =
  4. | Incptr | Decptr
  5. | Incdata | Decdata
  6. | Output | Input
  7. | Loop of program
  8. | Addptr of int
  9. | Adddata of int
  10. | Setptr of int
  11. | Setdata of int
  12. let read_program ic =
  13. let rec next cur stack =
  14. try
  15. match input_char ic, stack with
  16. | '>', _ -> next (Incptr :: cur) stack
  17. | '<', _ -> next (Decptr :: cur) stack
  18. | '+', _ -> next (Incdata :: cur) stack
  19. | '-', _ -> next (Decdata :: cur) stack
  20. | '.', _ -> next (Output :: cur) stack
  21. | ',', _ -> next (Input :: cur) stack
  22. | '[', _ -> next [] (cur :: stack)
  23. | ']', [] -> failwith "unmatched ']'"
  24. | ']', (hd :: tl) -> next (Loop (List.rev cur) :: hd) tl
  25. | _ -> next cur stack
  26. with End_of_file ->
  27. if List.length stack > 0 then failwith "unmatched '['";
  28. List.rev cur
  29. in
  30. next [] []
  31. let rec string_of_program program =
  32. let rec cat buf = function
  33. | [] -> buf
  34. | cmd :: tl -> cat (buf ^ string_of_command cmd) tl
  35. in
  36. cat "" program
  37. and string_of_command = function
  38. | Incptr -> ">"
  39. | Decptr -> "<"
  40. | Incdata -> "+"
  41. | Decdata -> "-"
  42. | Output -> "."
  43. | Input -> ","
  44. | Loop p -> "[" ^ string_of_program p ^ "]"
  45. | Addptr n when n < 0 -> "(<" ^ string_of_int (-n) ^ ")"
  46. | Addptr n -> "(>" ^ string_of_int n ^ ")"
  47. | Adddata n when n < 0 -> "(" ^ string_of_int n ^ ")"
  48. | Adddata n -> "(+" ^ string_of_int n ^ ")"
  49. | Setptr n -> "(<>" ^ string_of_int n ^ ")"
  50. | Setdata n -> "(=" ^ string_of_int n ^ ")"
  51. let compile memsize program =
  52. let ctx = global_context () in
  53. let m = create_module ctx "brainfucker" in
  54. let byte_ty = i8_type ctx in
  55. let byteptr_ty = pointer_type byte_ty in
  56. let bool_ty = i1_type ctx in
  57. let i32_ty = i32_type ctx in
  58. let void_ty = void_type ctx in
  59. let memset =
  60. let arg_types = [|byteptr_ty; byte_ty; i32_ty; i32_ty; bool_ty|] in
  61. declare_function "llvm.memset.p0i8.i32" (function_type void_ty arg_types) m
  62. in
  63. let putchar = declare_function "putchar" (function_type i32_ty [|byte_ty|]) m in
  64. let getchar = declare_function "getchar" (function_type byte_ty [||]) m in
  65. let cexit = declare_function "exit" (function_type void_ty [|i32_ty|]) m in
  66. (* use custom _start symbol rather than main function to reduce complexity *)
  67. let f = define_function "_start" (function_type void_ty [||]) m in
  68. let bb_cur = ref (entry_block f) in
  69. let b = builder_at_end ctx !bb_cur in
  70. let set_cur_bb bb =
  71. position_at_end bb b;
  72. bb_cur := bb
  73. in
  74. let i w n = const_int (integer_type ctx w) n in
  75. let i8 = i 8 in
  76. let i32 = i 32 in
  77. let mem = build_alloca (array_type byte_ty memsize) "mem" b in
  78. let ptr = build_alloca byteptr_ty "ptr" b in
  79. set_alignment 2 mem;
  80. let load p = build_load p "" b in
  81. let store p value = ignore (build_store value p b) in
  82. let gep n = build_in_bounds_gep (load ptr) [|i32 n|] "" b in
  83. let rec compile_command = function
  84. | Incptr ->
  85. store ptr (gep 1)
  86. | Decptr ->
  87. store ptr (gep (-1))
  88. | Incdata ->
  89. build_add (load (gep 0)) (i8 1) "" b |> store (gep 0)
  90. | Decdata ->
  91. build_sub (load (gep 0)) (i8 1) "" b |> store (gep 0)
  92. | Output ->
  93. build_call putchar [|load (gep 0)|] "" b |> ignore
  94. | Input ->
  95. build_call getchar [||] "" b |> store (gep 0)
  96. | Loop p ->
  97. let bb_end = append_block ctx "" f in
  98. move_block_after !bb_cur bb_end;
  99. let bb_body = insert_block ctx "" bb_end in
  100. let bb_cond = insert_block ctx "" bb_body in
  101. build_br bb_cond b |> ignore;
  102. position_at_end bb_cond b;
  103. let cond = build_icmp Icmp.Eq (load (gep 0)) (i8 0) "" b in
  104. build_cond_br cond bb_end bb_body b |> ignore;
  105. set_cur_bb bb_body;
  106. List.iter compile_command p;
  107. build_br bb_cond b |> ignore;
  108. set_cur_bb bb_end
  109. | Addptr n ->
  110. store ptr (gep n)
  111. | Adddata n ->
  112. build_add (load (gep 0)) (i8 n) "" b |> store (gep 0)
  113. | Setptr n ->
  114. let memptr = build_in_bounds_gep mem [|i32 0; i32 n|] "" b in
  115. build_bitcast memptr byteptr_ty "" b |> store ptr
  116. | Setdata n ->
  117. store (gep 0) (i8 n)
  118. in
  119. (* zero-initialize memory (use intrinsic for optimization assumptions) *)
  120. set_data_layout "e" m; (* little-endian, needed for optimization *)
  121. let memptr = build_bitcast mem byteptr_ty "" b in
  122. build_call memset [|memptr; i8 0; i32 memsize; i32 0; i 1 0|] "" b |> ignore;
  123. (* set pivot to index 0 and compile program commands *)
  124. build_in_bounds_gep mem [|i32 0; i32 0|] "" b |> store ptr;
  125. List.iter compile_command program;
  126. (* exit gracefully *)
  127. build_call cexit [|i32 0|] "" b |> ignore;
  128. build_ret_void b |> ignore;
  129. m
  130. let compile_to_c memsize program =
  131. let indent = Str.global_replace (Str.regexp "^\\(.\\)") " \\1" in
  132. let rec compile_commands buf = function
  133. | [] -> buf
  134. | cmd :: tl -> compile_commands (buf ^ compile_command cmd ^ "\n") tl
  135. and compile_command = function
  136. | Incptr -> "++ptr;"
  137. | Decptr -> "--ptr;"
  138. | Incdata -> "++*ptr;"
  139. | Decdata -> "--*ptr;"
  140. | Output -> "putchar(*ptr);"
  141. | Input -> "*ptr = getchar();"
  142. | Loop p -> "while (*ptr) {\n" ^ indent (compile_commands "" p) ^ "}"
  143. | Addptr n -> "ptr += " ^ string_of_int n ^ ";"
  144. | Adddata n -> "*ptr += " ^ string_of_int n ^ ";"
  145. | Setptr n -> "ptr = " ^ string_of_int n ^ ";"
  146. | Setdata n -> "*ptr = " ^ string_of_int n ^ ";"
  147. in
  148. "#include <stdio.h>\n" ^
  149. "#include <stdlib.h>\n" ^
  150. "void _start() {\n" ^
  151. " unsigned char mem[" ^ string_of_int memsize ^ "] = {};\n" ^
  152. " unsigned char *ptr = mem;\n" ^
  153. indent (compile_commands "" program) ^
  154. " exit(0);\n" ^
  155. "}\n"
  156. let rec optimize program =
  157. let rec opt = function
  158. | Incptr :: tl -> opt (Addptr 1 :: tl)
  159. | Decptr :: tl -> opt (Addptr (-1) :: tl)
  160. | Incdata :: tl -> opt (Adddata 1 :: tl)
  161. | Decdata :: tl -> opt (Adddata (-1) :: tl)
  162. | Addptr a :: Addptr b :: tl -> opt (Addptr (a + b) :: tl)
  163. | Adddata a :: Adddata b :: tl -> opt (Adddata (a + b) :: tl)
  164. | Loop [Addptr -1] :: tl -> opt (Setptr 0 :: tl)
  165. | Loop [Adddata (1 | -1)] :: tl -> opt (Setdata 0 :: tl)
  166. | (Addptr 0 | Adddata 0) :: tl
  167. | (Addptr _ | Setptr _) :: (Setptr _ :: _ as tl)
  168. | (Adddata _ | Setdata _) :: (Setdata _ :: _ as tl) -> opt tl
  169. | Loop p :: tl -> Loop (optimize p) :: opt tl
  170. | hd :: tl -> hd :: opt tl
  171. | [] -> []
  172. in
  173. match opt program with
  174. | p when p <> program -> optimize p
  175. | p -> p
  176. let rec flatten = function
  177. | Addptr 1 :: tl -> Incptr :: flatten tl
  178. | Addptr (-1) :: tl -> Decptr :: flatten tl
  179. | Adddata 1 :: tl -> Incdata :: flatten tl
  180. | Adddata (-1) :: tl -> Decdata :: flatten tl
  181. | Loop p :: tl -> Loop (flatten p) :: flatten tl
  182. | hd :: tl -> hd :: flatten tl
  183. | [] -> []
  184. let () =
  185. let args = List.tl (Array.to_list Sys.argv) in
  186. stdin |> read_program
  187. |> (if List.mem "-o" args then optimize else fun p -> p)
  188. |> fun program ->
  189. if List.mem "-e" args then
  190. program |> flatten |> string_of_program |> print_endline
  191. else if List.mem "-c" args then
  192. program |> flatten |> compile_to_c 30000 |> print_string
  193. else
  194. program |> compile 30000 |> string_of_llmodule |> print_string