text
stringlengths 12
786k
|
---|
type mb_elem = | MB_store of store | MB_const of int32 | MB_code of sexp list |
let push_mb_elem fpad = function | MB_store src -> push_as fpad src RValue | MB_const n -> push_const n | MB_code code -> code |
let makeblock fpad descr src_list tag = let size = List . length src_list in let sexpl_alloc , ptr , young = alloc_set fpad descr size tag in let sexpl_init = if young then List . mapi ( fun field src -> push_mb_elem fpad src |> pop_to_field ptr field ) src_list else List . mapi ( fun field src -> push_field_addr ptr field @ push_mb_elem fpad src @ [ L [ K " call " ; ID " caml_initialize " ] ] ) src_list in let c1 = [ C " < makeblock " > ] in let c2 = [ C " </ makeblock " > ] in ( ptr , c1 @ sexpl_alloc @ List . flatten sexpl_init @ c2 ) |
let makefloatblock fpad descr src_list = let size = List . length src_list in let wosize = size * double_size in let sexpl_alloc , ptr , _ = alloc_set fpad descr wosize double_array_tag in let sexpl_init = List . mapi ( fun field src -> ( push_as fpad src RValue @ load_double ) |> pop_to_double_field ptr field ) src_list in ( ptr , sexpl_alloc @ List . flatten sexpl_init ) |
let lookup_label gpad lab = let letrec_label , subfunc = try Hashtbl . find gpad . funcmapping lab with Not_found -> assert false in let wasmindex = try Hashtbl . find gpad . wasmindex letrec_label with Not_found -> assert false in ( wasmindex , letrec_label , subfunc ) |
let push_wasmptr gpad lab = let wasmindex , letrec_label , subfunc = lookup_label gpad lab in [ L [ K " i32 . const " ; ID ( Hashtbl . find gpad . letrec_name letrec_label ) ] ] |
let push_codeptr gpad lab = let wasmindex , letrec_label , subfunc = lookup_label gpad lab in push_wasmptr gpad lab @ [ L [ K " i32 . const " ; N ( I32 ( Int32 . of_int code_pointer_shift ) ) ] ; L [ K " i32 . shl " ] ; L [ K " i32 . const " ; N ( I32 ( Int32 . of_int ( ( subfunc lsl 2 ) + 1 ) ) ) ] ; L [ K " i32 . or " ] ; ] |
let closurerec gpad fpad descr src_list dest_list = let nfuncs = List . length dest_list in let envofs = nfuncs * 3 - 1 in let mb_src_list = ( List . mapi ( fun i ( _ , label ) -> ( if i > 0 then [ MB_const ( Int32 . of_int ( make_header ( 3 * i ) infix_tag ) ) ] else [ ] ) @ [ MB_code ( push_codeptr gpad label ) ] @ [ MB_const ( Int32 . of_int ( ( ( envofs - 3 * i ) lsl 1 ) + 1 ) ) ] ) dest_list |> List . flatten ) @ List . map ( fun src -> MB_store src ) src_list in let ptr , sexpl_mb = makeblock fpad descr mb_src_list closure_tag in let sexpl_dest = List . mapi ( fun i ( dest , _ ) -> ( [ L [ K " local . get " ; ID ptr ] ] @ ( if i > 0 then [ L [ K " i32 . const " ; N ( I32 ( Int32 . of_int ( 12 * i ) ) ) ] ; L [ K " i32 . add " ] ] else [ ] ) ) |> pop_to fpad dest RValue None ) dest_list |> List . flatten in sexpl_mb @ sexpl_dest |
let c_call gpad fpad descr src_list name = let descr = { descr with stack_save_accu = false } in let sexpl_setup = setup_for_gc fpad descr in let sexpl_restore = restore_after_gc fpad descr in let sexpl_args = List . map ( fun src -> push_as fpad src RValue ) src_list in let sexpl_call = [ L [ K " call " ; ID name ] ] @ pop_to_local " accu " in let p_i32 = L [ K " param " ; K " i32 " ] in let r_i32 = L [ K " result " ; K " i32 " ] in let ty = ( src_list |> List . map ( fun _ -> p_i32 ) ) @ [ r_i32 ] in Hashtbl . replace gpad . primitives name ty ; sexpl_setup @ List . flatten sexpl_args @ sexpl_call @ sexpl_restore |
let c_call_vector gpad fpad descr numargs depth name = let descr = { descr with stack_save_accu = false } in let sexpl_setup = setup_for_gc fpad descr in let sexpl_restore = restore_after_gc fpad descr in let sexpl_call = push_field_addr " fp " ( - depth ) @ push_const ( Int32 . of_int numargs ) @ [ L [ K " call " ; ID name ] ] @ pop_to_local " accu " in let ty = [ L [ K " param " ; K " i32 " ] ; L [ K " param " ; K " i32 " ] ; L [ K " result " ; K " i32 " ] ] in Hashtbl . replace gpad . primitives name ty ; sexpl_setup @ sexpl_call @ sexpl_restore |
let string_label = function | Label k -> sprintf " label % d " k | Loop k -> sprintf " loop % d " k |
let switch fpad src labls_ints labls_blocks = fpad . need_panic <- true ; let value = req_tmp1_i32 fpad in push_as fpad src RValue @ pop_to_local value @ [ L [ K " local . get " ; ID value ] ; L [ K " i32 . const " ; N ( I32 1l ) ] ; L [ K " i32 . and " ] ; L [ K " if " ; L [ K " then " ; L [ K " local . get " ; ID value ] ; L [ K " i32 . const " ; N ( I32 1l ) ] ; L [ K " i32 . shr_s " ] ; L ( [ K " br_table " ] @ ( Array . map ( fun lab -> ID ( string_label lab ) ) labls_ints |> Array . to_list ) @ [ ID " panic " ] ) ; ] ; L [ K " else " ; L [ K " local . get " ; ID value ] ; L [ K " i32 . const " ; N ( I32 4l ) ] ; L [ K " i32 . sub " ] ; L [ K " i32 . load " ; K " align = 2 " ] ; L [ K " i32 . const " ; N ( I32 0xffl ) ] ; L [ K " i32 . and " ] ; L ( [ K " br_table " ] @ ( Array . map ( fun lab -> ID ( string_label lab ) ) labls_blocks |> Array . to_list ) @ [ ID " panic " ] ) ; ] ; ] ] |
let grab fpad num = let sexpl = [ L [ K " local . get " ; ID " codeptr " ] ; L [ K " i32 . const " ; N ( I32 code_pointer_restart_mask ) ] ; L [ K " i32 . and " ] ; L [ K " if " ; L ( [ K " then " ; L [ K " local . get " ; ID " envptr " ] ; L [ K " local . get " ; ID " extra_args " ] ; L [ K " local . get " ; ID " fp " ] ; ] @ call_restart_helper ( ) @ pop_to_fp fpad @ [ L [ K " local . set " ; ID " extra_args " ] ; ] ) ] ; L [ K " local . get " ; ID " extra_args " ] ; L [ K " i32 . const " ; N ( I32 ( Int32 . of_int num ) ) ] ; L [ K " i32 . ge_u " ] ; L [ K " if " ; L [ K " then " ; L [ K " local . get " ; ID " extra_args " ] ; L [ K " i32 . const " ; N ( I32 ( Int32 . of_int num ) ) ] ; L [ K " i32 . sub " ] ; L [ K " local . set " ; ID " extra_args " ] ; ] ; L [ K " else " ; L [ K " local . get " ; ID " envptr " ] ; L [ K " local . get " ; ID " extra_args " ] ; L [ K " local . get " ; ID " codeptr " ] ; L [ K " local . get " ; ID " fp " ] ; L [ K " call " ; ID " grab_helper " ] ; L [ K " return " ] ; ] ] ; ] in sexpl |
let return = [ C " $ return " ; L [ K " local . get " ; ID " extra_args " ] ; L [ K " if " ; L [ K " then " ; L [ K " local . get " ; ID " envptr " ] ; L [ K " local . get " ; ID " extra_args " ] ; L [ K " local . get " ; ID " fp " ] ; L [ K " local . get " ; ID " accu " ] ; L [ K " call " ; ID " return_helper " ] ; L [ K " return " ] ] ] ; L [ K " local . get " ; ID " accu " ] ; L [ K " return " ] ; ] |
let throw fpad = if fpad . fpad_scope . cfg_main && fpad . fpad_scope . cfg_try_labels = [ ] then [ L [ K " call " ; ID " wasicaml_throw " ] ; L [ K " unreachable " ] ] else if fpad . fpad_scope . cfg_try_labels = [ ] then [ L [ K " i32 . const " ; N ( I32 0l ) ] ; L [ K " return " ] ] else [ L [ K " i32 . const " ; N ( I32 0l ) ] ; L [ K " global . set " ; ID " exn_result " ] ; L [ K " i32 . const " ; N ( I32 0l ) ] ; L [ K " return " ] ] |
let apply_direct gpad fpad funlabel numargs depth = let _ , letrec_label , _ = lookup_label gpad funlabel in let letrec_name = Hashtbl . find gpad . letrec_name letrec_label in let env_pos = ( - depth + numargs + 1 ) in ( push_local " accu " |> pop_to_stack fpad env_pos ) @ push_field_addr " fp " env_pos @ [ L [ K " i32 . const " ; N ( I32 ( Int32 . of_int ( numargs - 1 ) ) ) ] ; ] @ push_field " accu " 0 @ push_local " fp " @ [ L [ K " i32 . const " ; N ( I32 ( Int32 . of_int ( 4 * depth ) ) ) ] ; L [ K " i32 . sub " ] ; L [ K " call " ; ID letrec_name ] ; L [ K " local . tee " ; ID " accu " ] ; L [ K " i32 . eqz " ] ; L [ K " if " ; L ( [ K " then " ] @ throw fpad ) ] ; ] |
let apply fpad numargs depth = let env_pos = ( - depth + numargs + 1 ) in let codeptr = req_tmp1_i32 fpad in ( push_local " accu " |> pop_to_stack fpad env_pos ) @ push_field_addr " fp " env_pos @ [ L [ K " i32 . const " ; N ( I32 ( Int32 . of_int ( numargs - 1 ) ) ) ] ; ] @ push_field " accu " 0 @ ( if ! enable_deadbeef_check then [ L [ K " local . get " ; ID " fp " ] ; L [ K " i32 . const " ; N ( I32 ( Int32 . of_int ( 4 * depth ) ) ) ] ; L [ K " i32 . sub " ] ; L [ K " local . get " ; ID " fp " ] ; L [ K " call " ; ID " deadbeef_check " ] ] else [ ] ) @ [ L [ K " local . tee " ; ID codeptr ] ; L [ K " local . get " ; ID " fp " ] ; L [ K " i32 . const " ; N ( I32 ( Int32 . of_int ( 4 * depth ) ) ) ] ; L [ K " i32 . sub " ] ; L [ K " local . get " ; ID codeptr ] ; L [ K " i32 . const " ; N ( I32 ( Int32 . of_int code_pointer_shift ) ) ] ; L [ K " i32 . shr_u " ] ; L [ K " call_indirect " ; N ( I32 0l ) ; L [ K " param " ; K " i32 " ] ; L [ K " param " ; K " i32 " ] ; L [ K " param " ; K " i32 " ] ; L [ K " param " ; K " i32 " ] ; L [ K " result " ; K " i32 " ] ; ] ; L [ K " local . tee " ; ID " accu " ] ; L [ K " i32 . eqz " ] ; L [ K " if " ; L ( [ K " then " ] @ throw fpad ) ] ; ] |
let appterm_common fpad = [ C " $ appterm_common " ; L [ K " local . get " ; ID " envptr " ] ; L [ K " local . get " ; ID " codeptr " ] ; L [ K " local . get " ; ID " accu " ] ; L [ K " local . get " ; ID " extra_args " ] ; L [ K " local . get " ; ID " appterm_new_num_args " ] ; ] @ call_appterm_helper ( ) @ [ L [ K " local . set " ; ID " extra_args " ] ; L [ K " local . tee " ; ID " codeptr " ] ; L [ K " if " ; L [ K " then " ; L [ K " br " ; ID " startover " ] ] ; L [ K " else " ; L [ K " br " ; ID " return " ] ] ] ] |
let appterm gpad fpad numargs oldnumargs depth = let sexpl = if numargs <= 10 then ( gpad . need_reinit_frame_k <- ISet . add numargs gpad . need_reinit_frame_k ; push_local " fp " @ push_const ( Int32 . of_int depth ) @ push_const ( Int32 . of_int oldnumargs ) @ [ L [ K " call " ; ID ( sprintf " reinit_frame_ % d " numargs ) ] ] @ pop_to_local " fp " @ push_const ( Int32 . of_int numargs ) @ pop_to_local " appterm_new_num_args " @ [ L [ K " br " ; ID " appterm_common " ] ] ) else ( gpad . need_reinit_frame <- true ; push_local " fp " @ push_const ( Int32 . of_int depth ) @ push_const ( Int32 . of_int oldnumargs ) @ push_const ( Int32 . of_int numargs ) @ [ L [ K " call " ; ID " reinit_frame " ] ] @ pop_to_local " fp " @ push_const ( Int32 . of_int numargs ) @ pop_to_local " appterm_new_num_args " @ [ L [ K " br " ; ID " appterm_common " ] ] ) in fpad . need_appterm_common <- true ; fpad . need_return <- true ; sexpl |
let trap gpad fpad trylabel catchlabel depth = let local1 = req_tmp1_i32 fpad in let local2 = req_tmp2_i32 fpad in let sexpl_stack = ( push_const 0l |> pop_to_stack fpad ( - depth - 1 ) ) @ ( push_const 0l |> pop_to_stack fpad ( - depth - 2 ) ) @ ( push_const 0l |> pop_to_stack fpad ( - depth - 3 ) ) @ ( push_local " extra_args " |> pop_to_stack fpad ( - depth - 4 ) ) @ ( if ! enable_deadbeef_check then [ L [ K " local . get " ; ID " fp " ] ; L [ K " i32 . const " ; N ( I32 ( Int32 . of_int ( 4 * ( depth + 4 ) ) ) ) ] ; L [ K " i32 . sub " ] ; L [ K " local . get " ; ID " fp " ] ; L [ K " call " ; ID " deadbeef_check " ] ] else [ ] ) in let sexpl_try = push_domain_field domain_field_local_roots @ pop_to_local local2 @ push_wasmptr gpad trylabel @ push_local " envptr " @ push_local " extra_args " @ push_codeptr gpad trylabel @ push_local " fp " @ [ L [ K " i32 . const " ; N ( I32 ( Int32 . of_int ( 4 * ( depth + 4 ) ) ) ) ] ; L [ K " i32 . sub " ] ] @ [ L [ K " call " ; ID " wasicaml_wraptry4 " ] ; L [ K " local . set " ; ID local1 ] ; ] @ ( push_local local2 |> pop_to_domain_field domain_field_local_roots ) @ [ L [ K " local . get " ; ID local1 ] ; L [ K " global . get " ; ID " exn_result " ] ; L [ K " i32 . eqz " ] ; L [ K " i32 . or " ] ; L [ K " if " ; L [ K " then " ; L [ K " global . get " ; ID " wasicaml_domain_state " ] ; L [ K " i32 . load " ; K ( sprintf " offset = 0x % lx " ( Int32 . of_int ( 8 * domain_field_exn_bucket ) ) ) ; K " align = 2 " ] ; L [ K " local . set " ; ID " accu " ] ; L [ K " br " ; ID ( sprintf " label % d " catchlabel ) ] ] ] ; L [ K " global . get " ; ID " exn_result " ] ; L [ K " local . set " ; ID " accu " ] ] in sexpl_stack @ sexpl_try |
let rec emit_instr gpad fpad instr = match instr with | Wcomment s -> [ ] | Wblock arg -> ( match arg . label with | Label lab -> [ L ( [ K " block " ; ID ( sprintf " label % d " lab ) ; BR ] @ emit_instrs gpad fpad arg . body ) ] | Loop lab -> [ L ( [ K " loop " ; ID ( sprintf " loop % d " lab ) ; BR ] @ emit_instrs gpad fpad arg . body ) ] ) | Wcond { cond ; ontrue ; onfalse } -> emit_instr gpad fpad ( if ! cond then ontrue else onfalse ) | Wcopy arg -> copy fpad arg . src arg . dest None | Walloc arg -> copy fpad arg . src arg . dest ( Some arg . descr ) | Wenv arg -> push_env @ load_offset ( 4 * arg . field ) @ pop_to_local " accu " | Wcopyenv arg -> push_env @ add_offset ( 4 * arg . offset ) @ pop_to_local " accu " | Wgetglobal arg -> let Global offset = arg . src in push_global offset @ pop_to_local " accu " | Wunary arg -> emit_unary gpad fpad arg . op arg . src1 arg . dest | Wunaryeffect arg -> emit_unaryeffect fpad arg . op arg . src1 | Wbinary arg -> emit_binary gpad fpad arg . op arg . src1 arg . src2 arg . dest | Wbinaryeffect arg -> emit_binaryeffect fpad arg . op arg . src1 arg . src2 | Wternaryeffect arg -> emit_ternaryeffect fpad arg . op arg . src1 arg . src2 arg . src3 | Wmakeblock arg -> let src = List . map ( fun s -> MB_store s ) arg . src in let ptr , sexpl = makeblock fpad arg . descr src arg . tag in sexpl @ push_local ptr @ pop_to_local " accu " | Wmakefloatblock arg -> let ptr , sexpl = makefloatblock fpad arg . descr arg . src in sexpl @ push_local ptr @ pop_to_local " accu " | Wccall arg -> c_call gpad fpad arg . descr arg . src arg . name | Wccall_vector arg -> c_call_vector gpad fpad arg . descr arg . numargs arg . depth arg . name | Wbranch arg -> [ L [ K " br " ; ID ( string_label arg . label ) ] ] | Wif arg -> ( match repr_of_store arg . src with | RInt -> push_as fpad arg . src RInt @ ( if arg . neg then [ L [ K " i32 . eqz " ] ] else [ ] ) | RIntUnclean -> push_as fpad arg . src RIntUnclean @ [ L [ K " i32 . const " ; N ( I32 0x7fff_ffffl ) ] ; L [ K " i32 . and " ] ] @ ( if arg . neg then [ L [ K " i32 . eqz " ] ] else [ ] ) | _ -> push_as fpad arg . src RIntVal @ [ L [ K " i32 . const " ; N ( I32 1l ) ] ; L [ K ( if arg . neg then " i32 . le_u " else " i32 . gt_u " ) ] ] ) @ [ L [ K " if " ; L ( K " then " :: ( List . map ( emit_instr gpad fpad ) arg . body |> List . flatten ) ) ] ] | Wswitch arg -> switch fpad arg . src arg . labels_int arg . labels_blk | Wapply arg -> apply fpad arg . numargs arg . depth | Wapply_direct arg -> let fn = Wc_traceglobals . Unknown in let src = TracedGlobal ( arg . global , arg . path , fn ) in copy fpad src Wc_unstack . real_accu None @ apply_direct gpad fpad arg . funlabel arg . numargs arg . depth | Wappterm arg -> appterm gpad fpad arg . numargs arg . oldnumargs arg . depth | Wreturn arg -> let no_function = match arg . src with | RealAccu { no_function } -> no_function | _ -> repr_of_store arg . src <> RValue in if no_function then push_as fpad arg . src RValue @ [ L [ K " return " ] ] else ( fpad . need_return <- true ; push_as fpad arg . src RValue @ pop_to_local " accu " @ push_field_addr " fp " arg . arity @ pop_to_local " fp " @ [ L [ K " br " ; ID " return " ] ] ) | Wgrab arg -> grab fpad arg . numargs | Wclosurerec arg -> closurerec gpad fpad arg . descr arg . src arg . dest | Wraise arg -> ( push_as fpad arg . src RValue |> pop_to_domain_field domain_field_exn_bucket ) @ ( push_local " fp " |> pop_to_domain_field domain_field_extern_sp ) @ throw fpad | Wtrap arg -> trap gpad fpad arg . trylabel arg . catchlabel arg . depth | Wtryreturn arg -> push_as fpad arg . src RValue @ [ L [ K " global . set " ; ID " exn_result " ] ; L [ K " i32 . const " ; N ( I32 0l ) ] ; L [ K " return " ] ] | Wnextmain { label } -> push_local " accu " @ push_local " extra_args " @ push_local " codeptr " @ push_local " fp " @ [ L [ K " call " ; ID ( sprintf " letrec_main % d " label ) ] ; L [ K " return " ] ] | Wstop -> [ L [ K " i32 . const " ; N ( I32 0l ) ] ; L [ K " return " ] ] | Wnop -> [ ] | Wunreachable -> [ L [ K " unreachable " ] ] List . fold_left ( fun acc instr -> let comment = string_of_winstruction instr in List . rev_append ( emit_instr gpad fpad instr ) ( List . rev_append [ C comment ] acc ) ) [ ] instrs |> List . rev |
let emit_fblock gpad fpad fblock = let maxdepth = Wc_tracestack . max_stack_depth_of_fblock fblock in fpad . maxdepth <- if maxdepth > 0 then maxdepth + 2 else 0 ; let instrs = Wc_unstack . transl_fblock fpad . lpad fblock |> emit_instrs gpad fpad in set_bp fpad @ ( if ! enable_deadbeef_check && fpad . maxdepth > 0 then [ L [ K " local . get " ; ID " bp " ] ; L [ K " local . get " ; ID " fp " ] ; L [ K " call " ; ID " deadbeef_init " ] ] else [ ] ) @ instrs |
let get_funcmapping scode = let open Wc_control in let funcmapping = Hashtbl . create 7 in let subfunction_num = Hashtbl . create 7 in let subfunctions = Hashtbl . create 7 in IMap . iter ( fun func_label fblock -> let letrec_func_label = match fblock . scope . cfg_letrec_label with | None -> 0 | Some label -> label in let letrec_label = if fblock . scope . cfg_main then Main letrec_func_label else Func letrec_func_label in let subfunc_num = try Hashtbl . find subfunction_num letrec_label with Not_found -> 0 in Hashtbl . replace subfunction_num letrec_label ( subfunc_num + 1 ) ; Hashtbl . add funcmapping func_label ( letrec_label , subfunc_num ) ; let subfunc_list = try Hashtbl . find subfunctions letrec_label with Not_found -> [ ] in Hashtbl . replace subfunctions letrec_label ( func_label :: subfunc_list ) ) scode . functions ; let subfunctions_rev = Hashtbl . create 7 in Hashtbl . iter ( fun letrec_label subfunc_labels -> Hashtbl . add subfunctions_rev letrec_label ( List . rev subfunc_labels ) ) subfunctions ; ( funcmapping , subfunctions_rev ) |
let block_cascade start_sexpl label_sexpl_pairs = let rec shift prev_sexpl pairs = match pairs with | ( label , lsexpl ) :: pairs ' -> ( prev_sexpl , Some label ) :: shift lsexpl pairs ' | [ ] -> [ prev_sexpl , None ] in let rec arrange inner_sexpl shifted = match shifted with | ( sexpl , label_opt ) :: shifted ' -> let body = inner_sexpl @ sexpl @ [ L [ K " unreachable " ] ] in let inner_sexpl ' = match label_opt with | None -> body | Some lab -> [ L ( [ K " block " ; ID lab ; BR ; ] @ body ) ] in arrange inner_sexpl ' shifted ' | [ ] -> inner_sexpl in arrange [ ] ( shift start_sexpl label_sexpl_pairs ) |
let cond_section cond label sexpl_section sexpl_users = if cond then [ L ( [ K " block " ; ID label ; BR ] @ sexpl_users ) ] @ sexpl_section else sexpl_users |
let cond_loop cond label sexpl = if cond then [ L ( [ K " loop " ; ID label ; BR ] @ sexpl ) ] else sexpl |
let eff_label = function | Func l -> l | Main l -> l |
let init_lpad_for_subfunc gpad fpad func_label = let func_offset , environment = ( try Hashtbl . find gpad . glbfun_table func_label with Not_found -> 0 , [ | ] | ) in fpad . lpad . environment <- environment ; fpad . lpad . func_offset <- func_offset |
let generate_function scode gpad letrec_label func_name subfunc_labels export_flag = let fpad = { ( empty_fpad ( ) ) with fpad_letrec_label = letrec_label } in Hashtbl . add fpad . lpad . locals " accu " RValue ; Hashtbl . add fpad . lpad . locals " bp " RValue ; fpad . lpad . avoid_locals <- export_flag ; fpad . lpad . globals_table <- gpad . globals_table ; let subfunc_pairs = List . map ( fun func_label -> let fblock = IMap . find func_label Wc_control . ( scode . functions ) in fpad . fpad_scope <- fblock . scope ; let label = sprintf " func % d " func_label in init_lpad_for_subfunc gpad fpad func_label ; let sexpl = emit_fblock gpad fpad fblock in ( label , sexpl ) ) subfunc_labels in let subfunc_pairs_with_panic = subfunc_pairs @ [ " panic " , [ ] ] in let subfunc_sexpl = match subfunc_pairs with | [ ] -> assert false | [ label , sexpl ] -> cond_section fpad . need_panic " panic " [ L [ K " unreachable " ] ] sexpl | _ -> let labels = List . map ( fun ( label , _ ) -> ID label ) subfunc_pairs_with_panic in let body = [ L [ K " local . get " ; ID " codeptr " ] ; L [ K " i32 . const " ; N ( I32 code_pointer_subfunc_mask ) ] ; L [ K " i32 . and " ] ; L [ K " i32 . const " ; N ( I32 2l ) ] ; L [ K " i32 . shr_u " ] ; L ( [ K " br_table " ] @ labels ) ] in block_cascade body subfunc_pairs_with_panic in let sexpl = ( match letrec_label with | Main 0 | Func _ -> [ L [ K " i32 . const " ; N ( I32 1l ) ] ; L [ K " local . set " ; ID " accu " ] ] | Main _ -> [ L [ K " local . get " ; ID " envptr " ] ; L [ K " local . set " ; ID " accu " ] ; L [ K " i32 . const " ; N ( I32 0xffff_fffcl ) ] ; L [ K " local . set " ; ID " envptr " ] ] ) @ ( subfunc_sexpl |> cond_section fpad . need_appterm_common " appterm_common " ( appterm_common fpad ) |> cond_loop fpad . need_appterm_common " startover " |> cond_section fpad . need_return " return " return ) in if fpad . need_appterm_common then ( Hashtbl . add fpad . lpad . locals " appterm_new_num_args " RInt ; ) ; if fpad . need_xalloc then Hashtbl . add fpad . lpad . locals " xalloc " RValue ; if fpad . need_tmp1_i32 then Hashtbl . add fpad . lpad . locals " tmp1_i32 " RValue ; if fpad . need_tmp2_i32 then Hashtbl . add fpad . lpad . locals " tmp2_i32 " RValue ; if fpad . need_tmp1_f64 then Hashtbl . add fpad . lpad . locals " tmp1_f64 " RValue ; let locals = Hashtbl . fold ( fun name vtype acc -> ( name , vtype ) :: acc ) fpad . lpad . locals [ ] in let letrec = [ L ( [ K " func " ; ID func_name ; ] @ ( if export_flag then [ L [ K " export " ; S func_name ] ] else [ ] ) @ [ L [ K " param " ; ID " envptr " ; K " i32 " ] ; L [ K " param " ; ID " extra_args " ; K " i32 " ] ; L [ K " param " ; ID " codeptr " ; K " i32 " ] ; L [ K " param " ; ID " fp " ; K " i32 " ] ; BR ; L [ K " result " ; K " i32 " ] ; ] @ ( List . map ( fun ( name , repr ) -> L [ K " local " ; ID name ; K ( string_of_vtype ( vtype repr ) ) ] ; ) locals ) L [ K " i32 . const " ; N ( I32 ( - 1l ) ) ] ; L [ K " i32 . ne " ] ; L [ K " if " ; L ( [ K " then " ; L [ K " i32 . const " ; N ( I32 14l ) ] ] @ push_env @ [ L [ K " call " ; ID " debug2 " ] ] ) ] ] ) * @ sexpl @ [ L [ K " unreachable " ] ] ) ] in letrec |
let generate_letrec scode gpad letrec_label = let subfunc_labels = try Hashtbl . find gpad . subfunctions letrec_label with Not_found -> assert false in assert ( subfunc_labels <> [ ] ) ; let func_name = Hashtbl . find gpad . letrec_name letrec_label in let export = ( letrec_label = Main 0 ) in generate_function scode gpad letrec_label func_name subfunc_labels export |
let globals ( ) = [ " wasicaml_global_data " , true , TI32 ; " wasicaml_domain_state " , true , TI32 ; " wasicaml_atom_table " , true , TI32 ; " wasicaml_stack_threshold " , true , TI32 ; " exn_result " , true , TI32 ; ] @ if ! enable_multireturn then [ ] else [ " retval2 " , true , TI32 ; " retval3 " , true , TI32 ; ] |
let imp_functions = [ " env " , " caml_alloc_small_dispatch " , [ L [ K " param " ; K " i32 " ] ; L [ K " param " ; K " i32 " ] ; L [ K " param " ; K " i32 " ] ; L [ K " param " ; K " i32 " ] ; ] ; " env " , " caml_alloc_small " , [ L [ K " param " ; K " i32 " ] ; L [ K " param " ; K " i32 " ] ; L [ K " result " ; K " i32 " ] ] ; " env " , " caml_alloc_shr " , [ L [ K " param " ; K " i32 " ] ; L [ K " param " ; K " i32 " ] ; L [ K " result " ; K " i32 " ] ] ; " env " , " caml_initialize " , [ L [ K " param " ; K " i32 " ] ; L [ K " param " ; K " i32 " ] ; ] ; " env " , " caml_modify " , [ L [ K " param " ; K " i32 " ] ; L [ K " param " ; K " i32 " ] ; ] ; " env " , " caml_raise_zero_divide " , [ ] ; " env " , " caml_raise_stack_overflow " , [ ] ; " env " , " wasicaml_wraptry4 " , [ L [ K " param " ; K " i32 " ] ; L [ K " param " ; K " i32 " ] ; L [ K " param " ; K " i32 " ] ; L [ K " param " ; K " i32 " ] ; L [ K " param " ; K " i32 " ] ; L [ K " result " ; K " i32 " ] ] ; " env " , " wasicaml_get_global_data " , [ L [ K " result " ; K " i32 " ] ] ; " env " , " wasicaml_get_domain_state " , [ L [ K " result " ; K " i32 " ] ] ; " env " , " wasicaml_get_atom_table " , [ L [ K " result " ; K " i32 " ] ] ; " env " , " debug2 " , [ L [ K " param " ; K " i32 " ] ; L [ K " param " ; K " i32 " ] ; ] ; " wasicaml " , " wasicaml_throw " , [ ] ; ] |
let sanitize = String . map ( fun c -> match c with | ' A ' . . ' Z ' | ' a ' . . ' z ' | ' 0 ' . . ' 9 ' | ' _ ' | ' . ' -> c | _ -> ' ' ? ) |
let bigarray_to_string_list limit ba = let n = Array1 . dim ba in let l = ref [ ] in let p = ref 0 in while ! p < n do let q = min ( n - ! p ) limit in let by = Bytes . create q in for i = 0 to q - 1 do Bytes . set by i ba . { ! p + i } done ; l := Bytes . to_string by :: ! l ; p := ! p + q done ; List . rev ! l |
let generate scode exe get_defname globals_table = let ( funcmapping , subfunctions ) = get_funcmapping scode in let letrec_name = Hashtbl . create 7 in Hashtbl . iter ( fun _ ( letrec_label , _ ) -> match letrec_label with | Main 0 -> Hashtbl . add letrec_name letrec_label " letrec_main " | Main lab -> Hashtbl . add letrec_name letrec_label ( sprintf " letrec_main % d " lab ) | Func lab -> let suffix = try let defname = get_defname lab in " _ " ^ sanitize defname with | Not_found -> " " in Hashtbl . add letrec_name letrec_label ( sprintf " letrec % d % s " lab suffix ) ) funcmapping ; let wasmindex = Hashtbl . create 7 in let nextindex = ref 0 in let _elements = Hashtbl . fold ( fun _ ( letrec_label , _ ) acc -> Hashtbl . add wasmindex letrec_label ! nextindex ; incr nextindex ; let name = Hashtbl . find letrec_name letrec_label in ( ID name ) :: acc ) funcmapping [ ] in let data = bigarray_to_string_list 4096 Wc_reader . ( exe . data ) |> List . map ( fun s -> S s ) in let gpad = { funcmapping ; subfunctions ; primitives = Hashtbl . create 7 ; wasmindex ; letrec_name ; need_reinit_frame = false ; need_reinit_frame_k = ISet . empty ; need_mlookup = false ; globals_table ; glbfun_table = Wc_traceglobals . derive_glbfun_table globals_table ; } in let sexpl_code = Hashtbl . fold ( fun letrec_label _ acc -> let sexpl = generate_letrec scode gpad letrec_label in sexpl @ acc ) gpad . subfunctions [ ] in let sexpl_memory = [ L [ K " import " ; S " env " ; S " memory " ; L [ K " memory " ; ID " memory " ; N ( I32 65536l ) ; ] ] ] in let sexpl_table = [ L [ K " import " ; S " env " ; S " table " ; L [ K " table " ; N ( I32 ( Int32 . of_int ( Hashtbl . length subfunctions ) ) ) ; K " funcref " ] ] ] in let sexpl_functions = List . map ( fun ( modname , name , typeuse ) -> L [ K " import " ; S modname ; S name ; L ( [ K " func " ; ID name ; ] @ typeuse ) ] ) imp_functions @ Hashtbl . fold ( fun name typeuse acc -> ( L [ K " import " ; S " env " ; S name ; L ( [ K " func " ; ID name ; ] @ typeuse ) ] ) :: acc ) gpad . primitives [ ] in let sexpl_globals = List . map ( fun ( name , mut , vtype ) -> L ( [ K " global " ; ID name ; ( if mut then L [ K " mut " ; K ( string_of_vtype vtype ) ] else K ( string_of_vtype vtype ) ) ; ] @ zero_expr_of_vtype vtype ) ) ( globals ( ) ) in sexpl_memory @ sexpl_functions @ sexpl_table @ sexpl_globals @ wasicaml_init @ wasicaml_get_data @ wasicaml_get_data_size Wc_reader . ( Array1 . dim exe . data ) @ alloc_fast @ alloc_slow ( ) @ grab_helper gpad @ return_helper @ appterm_helper ( ) @ restart_helper gpad @ ( if gpad . need_reinit_frame then reinit_frame else [ ] ) @ ( if gpad . need_mlookup then mlookup else [ ] ) @ ( if ! enable_deadbeef_check then deadbeef_init @ deadbeef_check else [ ] ) @ ( ISet . elements gpad . need_reinit_frame_k |> List . map reinit_frame_k |> List . flatten ) @ sexpl_code @ [ L ( [ K " data " ; L [ K " memory " ; N ( I32 0l ) ] ; ID " data " ; ] @ data ) ] |
type repr = | RValue | RInt | RIntUnclean | RIntVal | RNatInt | RInt32 | RInt64 | RFloat |
type global_lookup = | Glb of int | Env of int |
type store = | RealStack of int | RealAccu of { no_function : bool } | Const of int | Local of repr * string | Atom of int | TracedGlobal of global_lookup * int list * Wc_traceglobals . initvalue | Invalid |
type global = Global of int |
type label = Label of int | Loop of int |
type stack_descriptor = { stack_uninit : int list ; stack_depth : int ; stack_save_accu : bool ; } |
type unop = | Pnegint | Pboolnot | Poffsetint of int | Pisint | Pgetfield of int | Pgetfloatfield of int | Pvectlength | Pgetpubmet of int |
type uneffect = | Poffsetref of int | Psetglobal of global |
type binop = | Paddint | Psubint | Pmulint | Pdivint | Pmodint | Pandint | Porint | Pxorint | Plslint | Plsrint | Pasrint | Pintcomp of Lambda . integer_comparison | Puintcomp of Lambda . integer_comparison | Pgetvectitem | Pgetstringchar | Pgetbyteschar | Pgetmethod | Pgetdynmet |
type bineffect = | Psetfield of int | Psetfloatfield of int |
type terneffect = | Psetvectitem | Psetbyteschar |
type winstruction = | Wcomment of string | Wblock of { label : label ; body : winstruction list } | Wcond of { cond : bool ref ; ontrue : winstruction ; onfalse : winstruction } | Wcopy of { src : store ; dest : store } | Walloc of { src : store ; dest : store ; descr : stack_descriptor } | Wenv of { field : int } | Wcopyenv of { offset : int } | Wgetglobal of { src : global } | Wunary of { op : unop ; src1 : store ; dest : store } | Wunaryeffect of { op : uneffect ; src1 : store } | Wbinary of { op : binop ; src1 : store ; src2 : store ; dest : store } | Wbinaryeffect of { op : bineffect ; src1 : store ; src2 : store } | Wternaryeffect of { op : terneffect ; src1 : store ; src2 : store ; src3 : store } | Wmakeblock of { tag : int ; src : store list ; descr : stack_descriptor } | Wmakefloatblock of { src : store list ; descr : stack_descriptor } | Wccall of { name : string ; src : store list ; descr : stack_descriptor } | Wccall_vector of { name : string ; numargs : int ; depth : int ; descr : stack_descriptor } | Wbranch of { label : label } | Wif of { src : store ; neg : bool ; body : winstruction list } | Wswitch of { labels_int : label array ; labels_blk : label array ; src : store } | Wapply of { numargs : int ; depth : int } | Wapply_direct of { funlabel : int ; global : global_lookup ; path : int list ; numargs : int ; depth : int } | Wappterm of { numargs : int ; oldnumargs : int ; depth : int } | Wreturn of { src : store ; arity : int } | Wgrab of { numargs : int } | Wclosurerec of { src : store list ; dest ( : store * int ) list ; descr : stack_descriptor } | Wraise of { src : store ; kind : Lambda . raise_kind } | Wtrap of { trylabel : int ; catchlabel : int ; depth : int } | Wtryreturn of { src : store } | Wnextmain of { label : int } | Wstop | Wnop | Wunreachable |
let repr_comparable_as_i32 r1 r2 = match r1 , r2 with | ( RValue | RIntVal ) , ( RValue | RIntVal ) -> true | ( RInt | RNatInt | RInt32 ) , ( RInt | RNatInt | RInt32 ) -> true | _ -> false |
let repr_of_store = function | RealStack _ -> RValue | Const _ -> RInt | Local ( repr , _ ) -> repr | RealAccu _ -> RValue | Atom _ -> RValue | TracedGlobal _ -> RValue | Invalid -> assert false |
let empty_descr = { stack_uninit = [ ] ; stack_depth = 0 ; stack_save_accu = false ; } |
let string_of_store = function | RealStack pos -> sprintf " fp [ % d ] " pos | RealAccu _ -> " accu " | Const k -> sprintf " % d " k | Local ( repr , name ) -> name | Atom k -> sprintf " atom % d " k | TracedGlobal ( glb , path , _ ) -> let s_glb = match glb with | Glb i -> sprintf " global % d " i | Env i -> sprintf " env +% d " i in let s_path = if path = [ ] then " " else List . map ( fun d -> sprintf " [ % d ] " d ) path |> String . concat " " in sprintf " % s % s " s_glb s_path | Invalid -> " invalid " |
let string_label = function | Label k -> sprintf " label % d " k | Loop k -> sprintf " loop % d " k |
let extract_directly_callable_function st = match st with | TracedGlobal ( glb , path , FuncInEnv { func_offset ; env } ) -> let func = env . ( func_offset ) in ( match func with | Function { label } -> Some ( glb , path , label , env ) | _ -> None ) | _ -> None |
let rec string_of_winstruction = function | Wcomment s -> s | Wblock arg -> ( match arg . label with | Label k -> sprintf " Wblock ( . . . , label % d ) " k | Loop k -> sprintf " Wblock ( loop % d , . . . ) " k ) | Wcond { cond ; ontrue ; onfalse } -> string_of_winstruction ( if ! cond then ontrue else onfalse ) | Wcopy arg -> sprintf " Wcopy ( % s = % s ) " ( string_of_store arg . dest ) ( string_of_store arg . src ) | Walloc arg -> sprintf " Walloc ( % s = % s ) " ( string_of_store arg . dest ) ( string_of_store arg . src ) | Wenv arg -> sprintf " Wenv ( accu = env [ % d ] ) " arg . field | Wcopyenv arg -> sprintf " Wcopyenv ( accu = env +% d ) " arg . offset | Wgetglobal { src = Global k } -> sprintf " Wgetglobal ( accu = global % d ) " k | Wunary arg -> sprintf " Wunary ( % s = f ( % s ) ) " ( string_of_store arg . dest ) ( string_of_store arg . src1 ) | Wunaryeffect arg -> sprintf " Wunaryeffect ( f ( % s ) ) " ( string_of_store arg . src1 ) | Wbinary arg -> sprintf " Wbinary ( % s = f ( % s , % s ) ) " ( string_of_store arg . dest ) ( string_of_store arg . src1 ) ( string_of_store arg . src2 ) | Wbinaryeffect arg -> sprintf " Wbinaryeffect ( f ( % s , % s ) ) " ( string_of_store arg . src1 ) ( string_of_store arg . src2 ) | Wternaryeffect arg -> sprintf " Wbinaryeffect ( f ( % s , % s , % s ) ) " ( string_of_store arg . src1 ) ( string_of_store arg . src2 ) ( string_of_store arg . src3 ) | Wmakeblock arg -> sprintf " Wmakeblock ( tag =% d , accu [ =% s ] ) " arg . tag ( List . map string_of_store arg . src |> String . concat " , " ) | Wmakefloatblock arg -> sprintf " Wmakefloatblock ( accu [ =% s ] ) " ( List . map string_of_store arg . src |> String . concat " , " ) | Wccall arg -> sprintf " Wccall ( accu = % S ( % s ) ) " arg . name ( List . map string_of_store arg . src |> String . concat " , " ) | Wccall_vector arg -> sprintf " Wccall_vector ( accu = % S ( fp [ % d ] . . . fp [ % d ] ) ) " arg . name ( - arg . depth ) ( - arg . depth + arg . numargs - 1 ) | Wbranch arg -> sprintf " Wbranch ( % s ) " ( string_label arg . label ) | Wif arg -> sprintf " Wif ( if % s % s -> % s ) " ( if arg . neg then " not " else " " ) ( string_of_store arg . src ) ( List . map string_of_winstruction arg . body |> String . concat " , " ) | Wswitch arg -> let s1 = Array . to_list arg . labels_int |> List . map string_label |> String . concat " , " in let s2 = Array . to_list arg . labels_blk |> List . map string_label |> String . concat " , " in sprintf " Wswitch ( % s ; % s on % s ) " s1 s2 ( string_of_store arg . src ) | Wapply arg -> sprintf " Wapply ( f = accu , args [ = fp [ % d ] . . . fp [ % d ] ] ) " ( - arg . depth ) ( - arg . depth + arg . numargs - 1 ) | Wapply_direct arg -> sprintf " Wapply_direct ( f = letrec % d , args [ = fp [ % d ] . . . fp [ % d ] ] ) " arg . funlabel ( - arg . depth ) ( - arg . depth + arg . numargs - 1 ) | Wappterm arg -> sprintf " Wappterm ( f = accu , args [ = fp [ % d ] . . . fp [ % d ] ] , oldnum =% d ) " ( - arg . depth ) ( - arg . depth + arg . numargs - 1 ) arg . oldnumargs | Wreturn arg -> sprintf " Wreturn ( % s ) " ( string_of_store arg . src ) | Wgrab arg -> sprintf " Wgrab ( num =% d ) " arg . numargs | Wclosurerec arg -> sprintf " Wclosurerec ( env [ =% s ] , dest [ =% s ] ) " ( List . map string_of_store arg . src |> String . concat " , " ) ( List . map ( fun ( s , lab ) -> sprintf " % s = label % d " ( string_of_store s ) lab ) arg . dest |> String . concat " , " ) | Wraise arg -> sprintf " Wraise ( % s ) " ( string_of_store arg . src ) | Wtrap arg -> sprintf " Wtrap ( try label % d catch label % d , depth =% d ) " arg . trylabel arg . catchlabel arg . depth | Wtryreturn arg -> sprintf " Wtryreturn ( % s ) " ( string_of_store arg . src ) | Wnextmain arg -> sprintf " Wnextmain ( letrec_main % d ) " arg . label | Wstop -> " Wstop " | Wnop -> " Wnop " | Wunreachable -> " Wunreachable " |
let mk_table l = let tab = Hashtbl . create 7 in List . iter ( fun k -> Hashtbl . add tab k ( ) ) l ; tab |
let prims_non_func_result = [ " caml_abs_float " ; " caml_acos_float " ; " caml_add_debug_info " ; " caml_add_float " ; " caml_alloc_dummy_float " ; " caml_array_append " ; " caml_array_blit " ; " caml_array_concat " ; " caml_array_fill " ; " caml_array_get_float " ; " caml_array_set " ; " caml_array_set_addr " ; " caml_array_set_float " ; " caml_array_sub " ; " caml_array_unsafe_get_float " ; " caml_array_unsafe_set " ; " caml_array_unsafe_set_addr " ; " caml_array_unsafe_set_float " ; " caml_asin_float " ; " caml_atan2_float " ; " caml_atan_float " ; " caml_ba_blit " ; " caml_ba_change_layout " ; " caml_ba_create " ; " caml_ba_dim " ; " caml_ba_dim_1 " ; " caml_ba_dim_2 " ; " caml_ba_dim_3 " ; " caml_ba_fill " ; " caml_ba_get_1 " ; " caml_ba_get_2 " ; " caml_ba_get_3 " ; " caml_ba_get_generic " ; " caml_ba_kind " ; " caml_ba_layout " ; " caml_ba_num_dims " ; " caml_ba_reshape " ; " caml_ba_set_1 " ; " caml_ba_set_2 " ; " caml_ba_set_3 " ; " caml_ba_set_generic " ; " caml_ba_slice " ; " caml_ba_sub " ; " caml_ba_uint8_get16 " ; " caml_ba_uint8_get32 " ; " caml_ba_uint8_get64 " ; " caml_ba_uint8_set16 " ; " caml_ba_uint8_set32 " ; " caml_ba_uint8_set64 " ; " caml_backtrace_status " ; " caml_blit_bytes " ; " caml_blit_string " ; " caml_bswap16 " ; " caml_bytes_compare " ; " caml_bytes_equal " ; " caml_bytes_get " ; " caml_bytes_get16 " ; " caml_bytes_get32 " ; " caml_bytes_get64 " ; " caml_bytes_greaterequal " ; " caml_bytes_greaterthan " ; " caml_bytes_lessequal " ; " caml_bytes_lessthan " ; " caml_bytes_notequal " ; " caml_bytes_of_string " ; " caml_bytes_set " ; " caml_bytes_set16 " ; " caml_bytes_set32 " ; " caml_bytes_set64 " ; " caml_ceil_float " ; " caml_channel_descriptor " ; " caml_classify_float " ; " caml_compare " ; " caml_convert_raw_backtrace " ; " caml_convert_raw_backtrace_slot " ; " caml_copysign_float " ; " caml_cos_float " ; " caml_cosh_float " ; " caml_create_bytes " ; " caml_create_string " ; " caml_div_float " ; " caml_dynlink_add_primitive " ; " caml_dynlink_close_lib " ; " caml_dynlink_get_current_libs " ; " caml_dynlink_lookup_symbol " ; " caml_dynlink_open_lib " ; " caml_ensure_stack_capacity " ; " caml_ephe_blit_data " ; " caml_ephe_blit_key " ; " caml_ephe_check_data " ; " caml_ephe_check_key " ; " caml_ephe_create " ; " caml_ephe_get_data " ; " caml_ephe_get_data_copy " ; " caml_ephe_get_key " ; " caml_ephe_get_key_copy " ; " caml_ephe_set_data " ; " caml_ephe_set_key " ; " caml_ephe_unset_data " ; " caml_ephe_unset_key " ; " caml_eq_float " ; " caml_equal " ; " caml_eventlog_pause " ; " caml_eventlog_resume " ; " caml_exp_float " ; " caml_expm1_float " ; " caml_fill_bytes " ; " caml_fill_string " ; " caml_final_register " ; " caml_final_register_called_without_value " ; " caml_final_release " ; " caml_float_compare " ; " caml_float_of_int " ; " caml_float_of_string " ; " caml_floatarray_blit " ; " caml_floatarray_create " ; " caml_floatarray_get " ; " caml_floatarray_set " ; " caml_floatarray_unsafe_get " ; " caml_floatarray_unsafe_set " ; " caml_floor_float " ; " caml_fma_float " ; " caml_fmod_float " ; " caml_format_float " ; " caml_format_int " ; " caml_fresh_oo_id " ; " caml_frexp_float " ; " caml_gc_compaction " ; " caml_gc_counters " ; " caml_gc_full_major " ; " caml_gc_get " ; " caml_gc_huge_fallback_count " ; " caml_gc_major " ; " caml_gc_major_slice " ; " caml_gc_minor " ; " caml_gc_minor_words " ; " caml_gc_quick_stat " ; " caml_gc_set " ; " caml_gc_stat " ; " caml_ge_float " ; " caml_get_current_callstack " ; " caml_get_current_environment " ; " caml_get_exception_backtrace " ; " caml_get_exception_raw_backtrace " ; " caml_get_global_data " ; " caml_get_major_bucket " ; " caml_get_major_credit " ; " caml_get_minor_free " ; " caml_get_public_method " ; " caml_get_section_table " ; " caml_greaterequal " ; " caml_greaterthan " ; " caml_gt_float " ; " caml_hash " ; " caml_hexstring_of_float " ; " caml_hypot_float " ; " caml_install_signal_handler " ; " caml_int32_add " ; " caml_int32_and " ; " caml_int32_bits_of_float " ; " caml_int32_bswap " ; " caml_int32_compare " ; " caml_int32_div " ; " caml_int32_float_of_bits " ; " caml_int32_format " ; " caml_int32_mod " ; " caml_int32_mul " ; " caml_int32_neg " ; " caml_int32_of_float " ; " caml_int32_of_int " ; " caml_int32_of_string " ; " caml_int32_or " ; " caml_int32_shift_left " ; " caml_int32_shift_right " ; " caml_int32_shift_right_unsigned " ; " caml_int32_sub " ; " caml_int32_to_float " ; " caml_int32_to_int " ; " caml_int32_xor " ; " caml_int64_add " ; " caml_int64_add_native " ; " caml_int64_and " ; " caml_int64_and_native " ; " caml_int64_bits_of_float " ; " caml_int64_bswap " ; " caml_int64_compare " ; " caml_int64_div " ; " caml_int64_div_native " ; " caml_int64_float_of_bits " ; " caml_int64_format " ; " caml_int64_mod " ; " caml_int64_mod_native " ; " caml_int64_mul " ; " caml_int64_mul_native " ; " caml_int64_neg " ; " caml_int64_neg_native " ; " caml_int64_of_float " ; " caml_int64_of_int " ; " caml_int64_of_int32 " ; " caml_int64_of_nativeint " ; " caml_int64_of_string " ; " caml_int64_or " ; " caml_int64_or_native " ; " caml_int64_shift_left " ; " caml_int64_shift_right " ; " caml_int64_shift_right_unsigned " ; " caml_int64_sub " ; " caml_int64_sub_native " ; " caml_int64_to_float " ; " caml_int64_to_int " ; " caml_int64_to_int32 " ; " caml_int64_to_nativeint " ; " caml_int64_xor " ; " caml_int64_xor_native " ; " caml_int_as_pointer " ; " caml_int_compare " ; " caml_int_of_float " ; " caml_int_of_string " ; " caml_lazy_make_forward " ; " caml_ldexp_float " ; " caml_le_float " ; " caml_lessequal " ; " caml_lessthan " ; " caml_lex_engine " ; " caml_log10_float " ; " caml_log1p_float " ; " caml_log_float " ; " caml_lt_float " ; " caml_make_array " ; " caml_make_float_vect " ; " caml_make_vect " ; " caml_marshal_data_size " ; " caml_md5_chan " ; " caml_md5_string " ; " caml_memprof_start " ; " caml_memprof_stop " ; " caml_ml_bytes_length " ; " caml_ml_channel_size " ; " caml_ml_channel_size_64 " ; " caml_ml_close_channel " ; " caml_ml_debug_info_status " ; " caml_ml_enable_runtime_warnings " ; " caml_ml_flush " ; " caml_ml_input " ; " caml_ml_input_char " ; " caml_ml_input_int " ; " caml_ml_input_scan_line " ; " caml_ml_open_descriptor_in " ; " caml_ml_open_descriptor_out " ; " caml_ml_out_channels_list " ; " caml_ml_output " ; " caml_ml_output_bytes " ; " caml_ml_output_char " ; " caml_ml_output_int " ; " caml_ml_pos_in " ; " caml_ml_pos_in_64 " ; " caml_ml_pos_out " ; " caml_ml_pos_out_64 " ; " caml_ml_runtime_warnings_enabled " ; " caml_ml_seek_in " ; " caml_ml_seek_in_64 " ; " caml_ml_seek_out " ; " caml_ml_seek_out_64 " ; " caml_ml_set_binary_mode " ; " caml_ml_set_channel_name " ; " caml_ml_string_length " ; " caml_modf_float " ; " caml_mul_float " ; " caml_nativeint_add " ; " caml_nativeint_and " ; " caml_nativeint_bswap " ; " caml_nativeint_compare " ; " caml_nativeint_div " ; " caml_nativeint_format " ; " caml_nativeint_mod " ; " caml_nativeint_mul " ; " caml_nativeint_neg " ; " caml_nativeint_of_float " ; " caml_nativeint_of_int " ; " caml_nativeint_of_int32 " ; " caml_nativeint_of_string " ; " caml_nativeint_or " ; " caml_nativeint_shift_left " ; " caml_nativeint_shift_right " ; " caml_nativeint_shift_right_unsigned " ; " caml_nativeint_sub " ; " caml_nativeint_to_float " ; " caml_nativeint_to_int " ; " caml_nativeint_to_int32 " ; " caml_nativeint_xor " ; " caml_neg_float " ; " caml_neq_float " ; " caml_new_lex_engine " ; " caml_nextafter_float " ; " caml_notequal " ; " caml_obj_block " ; " caml_obj_make_forward " ; " caml_obj_reachable_words " ; " caml_obj_set_raw_field " ; " caml_obj_set_tag " ; " caml_obj_tag " ; " caml_output_value " ; " caml_output_value_to_buffer " ; " caml_output_value_to_bytes " ; " caml_output_value_to_string " ; " caml_parse_engine " ; " caml_power_float " ; " caml_raw_backtrace_length " ; " caml_raw_backtrace_next_slot " ; " caml_raw_backtrace_slot " ; " caml_realloc_global " ; " caml_record_backtrace " ; " caml_register_named_value " ; " caml_reify_bytecode " ; " caml_remove_debug_info " ; " caml_reset_afl_instrumentation " ; " caml_restore_raw_backtrace " ; " caml_round_float " ; " caml_runtime_parameters " ; " caml_runtime_variant " ; " caml_set_oo_id " ; " caml_set_parser_trace " ; " caml_setup_afl " ; " caml_signbit " ; " caml_signbit_float " ; " caml_sin_float " ; " caml_sinh_float " ; " caml_sqrt_float " ; " caml_static_release_bytecode " ; " caml_string_compare " ; " caml_string_equal " ; " caml_string_get " ; " caml_string_get16 " ; " caml_string_get32 " ; " caml_string_get64 " ; " caml_string_greaterequal " ; " caml_string_greaterthan " ; " caml_string_lessequal " ; " caml_string_lessthan " ; " caml_string_notequal " ; " caml_string_of_bytes " ; " caml_string_set " ; " caml_sub_float " ; " caml_sys_argv " ; " caml_sys_chdir " ; " caml_sys_close " ; " caml_sys_const_backend_type " ; " caml_sys_const_big_endian " ; " caml_sys_const_int_size " ; " caml_sys_const_max_wosize " ; " caml_sys_const_naked_pointers_checked " ; " caml_sys_const_ostype_cygwin " ; " caml_sys_const_ostype_unix " ; " caml_sys_const_ostype_win32 " ; " caml_sys_const_word_size " ; " caml_sys_executable_name " ; " caml_sys_exit " ; " caml_sys_file_exists " ; " caml_sys_get_argv " ; " caml_sys_get_config " ; " caml_sys_getcwd " ; " caml_sys_getenv " ; " caml_sys_is_directory " ; " caml_sys_isatty " ; " caml_sys_mkdir " ; " caml_sys_modify_argv " ; " caml_sys_open " ; " caml_sys_random_seed " ; " caml_sys_read_directory " ; " caml_sys_remove " ; " caml_sys_rename " ; " caml_sys_rmdir " ; " caml_sys_system_command " ; " caml_sys_time " ; " caml_sys_time_include_children " ; " caml_sys_unsafe_getenv " ; " caml_tan_float " ; " caml_tanh_float " ; " caml_terminfo_rows " ; " caml_trunc_float " ; " caml_update_dummy " ; " caml_weak_blit " ; " caml_weak_check " ; " caml_weak_create " ; " caml_weak_get " ; " caml_weak_get_copy " ; " caml_weak_set " ; ] |> mk_table |
type executable = { dll_paths : string list ; dll_names : string list ; primitives : string array ; code : string ; data : ( char , int8_unsigned_elt , c_layout ) Array1 . t ; symbols : Symtable . global_map ; debug : ( int , string ) Hashtbl . t ; } |
let read_bigstring f len = let ba = Array1 . create Char c_layout len in let by = Bytes . create 4096 in let n = ref len in let k = ref 0 in while ! n > 0 do let p = min ! n 4096 in really_input f by 0 p ; for i = 0 to p - 1 do ba . { ! k + i } <- Bytes . get by i done ; k := ! k + p ; n := ! n - p ; done ; ba |
let input_stringlist f section = try let s = Bytesections . read_section_string f section in let l = String . split_on_char ' \ 000 ' s in List . filter ( fun elem -> elem <> " " ) l with | Not_found -> [ ] |
let input_objarray_as_bigstring f section = try let _len = Bytesections . seek_section f section in let p1 = pos_in f in let _dummay = Marshal . from_channel f in let p2 = pos_in f in let _len = Bytesections . seek_section f section in read_bigstring f ( p2 - p1 ) with | Not_found -> Array1 . create Char c_layout 0 |
let input_symbols f section : Symtable . global_map = try let _len = Bytesections . seek_section f section in Marshal . from_channel f with | Not_found -> Symtable . empty_global_map |
let input_debug f section = let ht = Hashtbl . create 7 in try let _len = Bytesections . seek_section f section in let n = input_binary_int f in for k = 1 to n do let ofs = input_binary_int f in let evl = input_value f in let _ = input_value f in List . iter ( fun ev -> Hashtbl . add ht I . ( ( ofs + ev . ev_pos ) / 4 ) I . ( ev . ev_defname ) ) evl done ; ht with | Not_found -> ht |
let read_executable name = let f = open_in name in Bytesections . read_toc f ; let dll_paths = input_stringlist f " DLPT " in let dll_names = input_stringlist f " DLLS " in let primitives = input_stringlist f " PRIM " |> Array . of_list in let code = Bytesections . read_section_string f " CODE " in let data = input_objarray_as_bigstring f " DATA " in let symbols = input_symbols f " SYMB " in let debug = input_debug f " DBUG " in close_in f ; { dll_paths ; dll_names ; primitives ; code ; data ; symbols ; debug } |
type format = | C | L | LO | N | NN | LL |
let instructions exec = [ O . opACC0 , [ ] , ( fun args -> [ I . Kacc 0 ] ) ; O . opACC1 , [ ] , ( fun args -> [ I . Kacc 1 ] ) ; O . opACC2 , [ ] , ( fun args -> [ I . Kacc 2 ] ) ; O . opACC3 , [ ] , ( fun args -> [ I . Kacc 3 ] ) ; O . opACC4 , [ ] , ( fun args -> [ I . Kacc 4 ] ) ; O . opACC5 , [ ] , ( fun args -> [ I . Kacc 5 ] ) ; O . opACC6 , [ ] , ( fun args -> [ I . Kacc 6 ] ) ; O . opACC7 , [ ] , ( fun args -> [ I . Kacc 7 ] ) ; O . opACC , [ C ] , ( fun args -> [ I . Kacc args . ( 0 ) ] ) ; O . opPUSH , [ ] , ( fun args -> [ I . Kpush ] ) ; O . opPUSHACC0 , [ ] , ( fun args -> [ I . Kpush ; I . Kacc 0 ] ) ; O . opPUSHACC1 , [ ] , ( fun args -> [ I . Kpush ; I . Kacc 1 ] ) ; O . opPUSHACC2 , [ ] , ( fun args -> [ I . Kpush ; I . Kacc 2 ] ) ; O . opPUSHACC3 , [ ] , ( fun args -> [ I . Kpush ; I . Kacc 3 ] ) ; O . opPUSHACC4 , [ ] , ( fun args -> [ I . Kpush ; I . Kacc 4 ] ) ; O . opPUSHACC5 , [ ] , ( fun args -> [ I . Kpush ; I . Kacc 5 ] ) ; O . opPUSHACC6 , [ ] , ( fun args -> [ I . Kpush ; I . Kacc 6 ] ) ; O . opPUSHACC7 , [ ] , ( fun args -> [ I . Kpush ; I . Kacc 7 ] ) ; O . opPUSHACC , [ C ] , ( fun args -> [ I . Kpush ; I . Kacc args . ( 0 ) ] ) ; O . opPOP , [ C ] , ( fun args -> [ I . Kpop args . ( 0 ) ] ) ; O . opASSIGN , [ C ] , ( fun args -> [ I . Kassign args . ( 0 ) ] ) ; O . opENVACC1 , [ ] , ( fun args -> [ I . Kenvacc 1 ] ) ; O . opENVACC2 , [ ] , ( fun args -> [ I . Kenvacc 2 ] ) ; O . opENVACC3 , [ ] , ( fun args -> [ I . Kenvacc 3 ] ) ; O . opENVACC4 , [ ] , ( fun args -> [ I . Kenvacc 4 ] ) ; O . opENVACC , [ C ] , ( fun args -> [ I . Kenvacc args . ( 0 ) ] ) ; O . opPUSHENVACC1 , [ ] , ( fun args -> [ I . Kpush ; I . Kenvacc 1 ] ) ; O . opPUSHENVACC2 , [ ] , ( fun args -> [ I . Kpush ; I . Kenvacc 2 ] ) ; O . opPUSHENVACC3 , [ ] , ( fun args -> [ I . Kpush ; I . Kenvacc 3 ] ) ; O . opPUSHENVACC4 , [ ] , ( fun args -> [ I . Kpush ; I . Kenvacc 4 ] ) ; O . opPUSHENVACC , [ C ] , ( fun args -> [ I . Kpush ; I . Kenvacc args . ( 0 ) ] ) ; O . opPUSH_RETADDR , [ L ] , ( fun args -> [ I . Kpush_retaddr args . ( 0 ) ] ) ; O . opAPPLY , [ C ] , ( fun args -> [ I . Kapply args . ( 0 ) ] ) ; O . opAPPLY1 , [ ] , ( fun args -> [ I . Kapply 1 ] ) ; O . opAPPLY2 , [ ] , ( fun args -> [ I . Kapply 2 ] ) ; O . opAPPLY3 , [ ] , ( fun args -> [ I . Kapply 3 ] ) ; O . opAPPTERM , [ C ; C ] , ( fun args -> [ I . Kappterm ( args . ( 0 ) , args . ( 1 ) ) ] ) ; O . opAPPTERM1 , [ C ] , ( fun args -> [ I . Kappterm ( 1 , args . ( 0 ) ) ] ) ; O . opAPPTERM2 , [ C ] , ( fun args -> [ I . Kappterm ( 2 , args . ( 0 ) ) ] ) ; O . opAPPTERM3 , [ C ] , ( fun args -> [ I . Kappterm ( 3 , args . ( 0 ) ) ] ) ; O . opRETURN , [ C ] , ( fun args -> [ I . Kreturn args . ( 0 ) ] ) ; O . opRESTART , [ ] , ( fun args -> [ I . Krestart ] ) ; O . opGRAB , [ C ] , ( fun args -> [ I . Kgrab args . ( 0 ) ] ) ; O . opCLOSURE , [ C ; L ] , ( fun args -> [ I . Kclosure ( args . ( 1 ) , args . ( 0 ) ) ] ) ; O . opCLOSUREREC , [ N ; C ; LO ; LL ] , ( fun args -> let n = args . ( 0 ) in [ I . Kclosurerec ( Array . sub args 2 n |> Array . to_list , args . ( 1 ) ) ] ) ; O . opOFFSETCLOSUREM3 , [ ] , ( fun args -> [ I . Koffsetclosure ( - 3 ) ] ) ; O . opOFFSETCLOSURE0 , [ ] , ( fun args -> [ I . Koffsetclosure 0 ] ) ; O . opOFFSETCLOSURE3 , [ ] , ( fun args -> [ I . Koffsetclosure 3 ] ) ; O . opOFFSETCLOSURE , [ C ] , ( fun args -> [ I . Koffsetclosure args . ( 0 ) ] ) ; O . opPUSHOFFSETCLOSUREM3 , [ ] , ( fun args -> [ I . Kpush ; I . Koffsetclosure ( - 3 ) ] ) ; O . opPUSHOFFSETCLOSURE0 , [ ] , ( fun args -> [ I . Kpush ; I . Koffsetclosure 0 ] ) ; O . opPUSHOFFSETCLOSURE3 , [ ] , ( fun args -> [ I . Kpush ; I . Koffsetclosure 3 ] ) ; O . opPUSHOFFSETCLOSURE , [ C ] , ( fun args -> [ I . Kpush ; I . Koffsetclosure args . ( 0 ) ] ) ; O . opGETGLOBAL , [ C ] , ( fun args -> let ident = Ident . create_persistent ( sprintf " % d " args . ( 0 ) ) in [ I . Kgetglobal ident ] ) ; O . opPUSHGETGLOBAL , [ C ] , ( fun args -> let ident = Ident . create_persistent ( sprintf " % d " args . ( 0 ) ) in [ I . Kpush ; I . Kgetglobal ident ] ) ; O . opGETGLOBALFIELD , [ C ; C ] , ( fun args -> let ident = Ident . create_persistent ( sprintf " % d " args . ( 0 ) ) in [ I . Kgetglobal ident ; I . Kgetfield args . ( 1 ) ] ) ; O . opPUSHGETGLOBALFIELD , [ C ; C ] , ( fun args -> let ident = Ident . create_persistent ( sprintf " % d " args . ( 0 ) ) in [ I . Kpush ; I . Kgetglobal ident ; I . Kgetfield args . ( 1 ) ] ) ; O . opSETGLOBAL , [ C ] , ( fun args -> let ident = Ident . create_persistent ( sprintf " % d " args . ( 0 ) ) in [ I . Ksetglobal ident ] ) ; O . opATOM0 , [ ] , ( fun args -> [ I . Kmakeblock ( 0 , 0 ) ] ) ; O . opATOM , [ C ] , ( fun args -> [ I . Kmakeblock ( 0 , args . ( 0 ) ) ] ) ; O . opPUSHATOM0 , [ ] , ( fun args -> [ I . Kpush ; I . Kmakeblock ( 0 , 0 ) ] ) ; O . opPUSHATOM , [ C ] , ( fun args -> [ I . Kpush ; I . Kmakeblock ( 0 , args . ( 0 ) ) ] ) ; O . opMAKEBLOCK , [ C ; C ] , ( fun args -> [ I . Kmakeblock ( args . ( 0 ) , args . ( 1 ) ) ] ) ; O . opMAKEBLOCK1 , [ C ] , ( fun args -> [ I . Kmakeblock ( 1 , args . ( 0 ) ) ] ) ; O . opMAKEBLOCK2 , [ C ] , ( fun args -> [ I . Kmakeblock ( 2 , args . ( 0 ) ) ] ) ; O . opMAKEBLOCK3 , [ C ] , ( fun args -> [ I . Kmakeblock ( 3 , args . ( 0 ) ) ] ) ; O . opMAKEFLOATBLOCK , [ C ] , ( fun args -> [ I . Kmakefloatblock args . ( 0 ) ] ) ; O . opGETFIELD0 , [ ] , ( fun args -> [ I . Kgetfield 0 ] ) ; O . opGETFIELD1 , [ ] , ( fun args -> [ I . Kgetfield 1 ] ) ; O . opGETFIELD2 , [ ] , ( fun args -> [ I . Kgetfield 2 ] ) ; O . opGETFIELD3 , [ ] , ( fun args -> [ I . Kgetfield 3 ] ) ; O . opGETFIELD , [ C ] , ( fun args -> [ I . Kgetfield args . ( 0 ) ] ) ; O . opGETFLOATFIELD , [ C ] , ( fun args -> [ I . Kgetfloatfield args . ( 0 ) ] ) ; O . opSETFIELD0 , [ ] , ( fun args -> [ I . Ksetfield 0 ] ) ; O . opSETFIELD1 , [ ] , ( fun args -> [ I . Ksetfield 1 ] ) ; O . opSETFIELD2 , [ ] , ( fun args -> [ I . Ksetfield 2 ] ) ; O . opSETFIELD3 , [ ] , ( fun args -> [ I . Ksetfield 3 ] ) ; O . opSETFIELD , [ C ] , ( fun args -> [ I . Ksetfield args . ( 0 ) ] ) ; O . opSETFLOATFIELD , [ C ] , ( fun args -> [ I . Ksetfloatfield args . ( 0 ) ] ) ; O . opVECTLENGTH , [ ] , ( fun args -> [ I . Kvectlength ] ) ; O . opGETVECTITEM , [ ] , ( fun args -> [ I . Kgetvectitem ] ) ; O . opSETVECTITEM , [ ] , ( fun args -> [ I . Ksetvectitem ] ) ; O . opGETBYTESCHAR , [ ] , ( fun args -> [ I . Kgetbyteschar ] ) ; O . opSETBYTESCHAR , [ ] , ( fun args -> [ I . Ksetbyteschar ] ) ; O . opBRANCH , [ L ] , ( fun args -> [ I . Kbranch args . ( 0 ) ] ) ; O . opBRANCHIF , [ L ] , ( fun args -> [ I . Kbranchif args . ( 0 ) ] ) ; O . opBRANCHIFNOT , [ L ] , ( fun args -> [ I . Kbranchifnot args . ( 0 ) ] ) ; O . opSWITCH , [ NN ; LO ; LL ; LL ] , ( fun args -> let n_const = args . ( 0 ) land 0xffff in let n_block = args . ( 0 ) lsr 16 in let tbl_const = Array . sub args 1 n_const in let tbl_block = Array . sub args ( 1 + n_const ) n_block in [ I . Kswitch ( tbl_const , tbl_block ) ] ) ; O . opBOOLNOT , [ ] , ( fun args -> [ I . Kboolnot ] ) ; O . opPUSHTRAP , [ L ] , ( fun args -> [ I . Kpushtrap args . ( 0 ) ] ) ; O . opPOPTRAP , [ ] , ( fun args -> [ I . Kpoptrap ] ) ; O . opRAISE , [ ] , ( fun args -> [ I . Kraise Lambda . Raise_regular ] ) ; O . opCHECK_SIGNALS , [ ] , ( fun args -> [ I . Kcheck_signals ] ) ; O . opC_CALL1 , [ C ] , ( fun args -> [ I . Kccall ( exec . primitives . ( args . ( 0 ) ) , 1 ) ] ) ; O . opC_CALL2 , [ C ] , ( fun args -> [ I . Kccall ( exec . primitives . ( args . ( 0 ) ) , 2 ) ] ) ; O . opC_CALL3 , [ C ] , ( fun args -> [ I . Kccall ( exec . primitives . ( args . ( 0 ) ) , 3 ) ] ) ; O . opC_CALL4 , [ C ] , ( fun args -> [ I . Kccall ( exec . primitives . ( args . ( 0 ) ) , 4 ) ] ) ; O . opC_CALL5 , [ C ] , ( fun args -> [ I . Kccall ( exec . primitives . ( args . ( 0 ) ) , 5 ) ] ) ; O . opC_CALLN , [ C ; C ] , ( fun args -> [ I . Kccall ( exec . primitives . ( args . ( 1 ) ) , args . ( 0 ) ) ] ) ; O . opCONST0 , [ ] , ( fun args -> [ I . Kconst ( Lambda . Const_base ( Asttypes . Const_int 0 ) ) ] ) ; O . opCONST1 , [ ] , ( fun args -> [ I . Kconst ( Lambda . Const_base ( Asttypes . Const_int 1 ) ) ] ) ; O . opCONST2 , [ ] , ( fun args -> [ I . Kconst ( Lambda . Const_base ( Asttypes . Const_int 2 ) ) ] ) ; O . opCONST3 , [ ] , ( fun args -> [ I . Kconst ( Lambda . Const_base ( Asttypes . Const_int 3 ) ) ] ) ; O . opCONSTINT , [ C ] , ( fun args -> [ I . Kconst ( Lambda . Const_base ( Asttypes . Const_int args . ( 0 ) ) ) ] ) ; O . opPUSHCONST0 , [ ] , ( fun args -> [ I . Kpush ; I . Kconst ( Lambda . Const_base ( Asttypes . Const_int 0 ) ) ] ) ; O . opPUSHCONST1 , [ ] , ( fun args -> [ I . Kpush ; I . Kconst ( Lambda . Const_base ( Asttypes . Const_int 1 ) ) ] ) ; O . opPUSHCONST2 , [ ] , ( fun args -> [ I . Kpush ; I . Kconst ( Lambda . Const_base ( Asttypes . Const_int 2 ) ) ] ) ; O . opPUSHCONST3 , [ ] , ( fun args -> [ I . Kpush ; I . Kconst ( Lambda . Const_base ( Asttypes . Const_int 3 ) ) ] ) ; O . opPUSHCONSTINT , [ C ] , ( fun args -> [ I . Kpush ; I . Kconst ( Lambda . Const_base ( Asttypes . Const_int args . ( 0 ) ) ) ] ) ; O . opNEGINT , [ ] , ( fun args -> [ I . Knegint ] ) ; O . opADDINT , [ ] , ( fun args -> [ I . Kaddint ] ) ; O . opSUBINT , [ ] , ( fun args -> [ I . Ksubint ] ) ; O . opMULINT , [ ] , ( fun args -> [ I . Kmulint ] ) ; O . opDIVINT , [ ] , ( fun args -> [ I . Kdivint ] ) ; O . opMODINT , [ ] , ( fun args -> [ I . Kmodint ] ) ; O . opANDINT , [ ] , ( fun args -> [ I . Kandint ] ) ; O . opORINT , [ ] , ( fun args -> [ I . Korint ] ) ; O . opXORINT , [ ] , ( fun args -> [ I . Kxorint ] ) ; O . opLSLINT , [ ] , ( fun args -> [ I . Klslint ] ) ; O . opLSRINT , [ ] , ( fun args -> [ I . Klsrint ] ) ; O . opASRINT , [ ] , ( fun args -> [ I . Kasrint ] ) ; O . opEQ , [ ] , ( fun args -> [ I . Kintcomp Ceq ] ) ; O . opNEQ , [ ] , ( fun args -> [ I . Kintcomp Cne ] ) ; O . opLTINT , [ ] , ( fun args -> [ I . Kintcomp Clt ] ) ; O . opLEINT , [ ] , ( fun args -> [ I . Kintcomp Cle ] ) ; O . opGTINT , [ ] , ( fun args -> [ I . Kintcomp Cgt ] ) ; O . opGEINT , [ ] , ( fun args -> [ I . Kintcomp Cge ] ) ; O . opOFFSETINT , [ C ] , ( fun args -> [ I . Koffsetint args . ( 0 ) ] ) ; O . opOFFSETREF , [ C ] , ( fun args -> [ I . Koffsetref args . ( 0 ) ] ) ; O . opISINT , [ ] , ( fun args -> [ I . Kisint ] ) ; O . opGETMETHOD , [ ] , ( fun args -> [ I . Kgetmethod ] ) ; O . opBEQ , [ C ; L ] , ( fun args -> let const = Lambda . Const_base ( Const_int args . ( 0 ) ) in [ Kpush ; Kconst const ; Kintcomp Ceq ; Kbranchif args . ( 1 ) ] ) ; O . opBNEQ , [ C ; L ] , ( fun args -> let const = Lambda . Const_base ( Const_int args . ( 0 ) ) in [ Kpush ; Kconst const ; Kintcomp Cne ; Kbranchif args . ( 1 ) ] ) ; O . opBLTINT , [ C ; L ] , ( fun args -> let const = Lambda . Const_base ( Const_int args . ( 0 ) ) in [ Kpush ; Kconst const ; Kintcomp Clt ; Kbranchif args . ( 1 ) ] ) ; O . opBLEINT , [ C ; L ] , ( fun args -> let const = Lambda . Const_base ( Const_int args . ( 0 ) ) in [ Kpush ; Kconst const ; Kintcomp Cle ; Kbranchif args . ( 1 ) ] ) ; O . opBGTINT , [ C ; L ] , ( fun args -> let const = Lambda . Const_base ( Const_int args . ( 0 ) ) in [ Kpush ; Kconst const ; Kintcomp Cgt ; Kbranchif args . ( 1 ) ] ) ; O . opBGEINT , [ C ; L ] , ( fun args -> let const = Lambda . Const_base ( Const_int args . ( 0 ) ) in [ Kpush ; Kconst const ; Kintcomp Cge ; Kbranchif args . ( 1 ) ] ) ; O . opULTINT , [ ] , ( fun args -> [ I . Kisout ] ) ; O . opUGEINT , [ ] , ( fun args -> assert false ) ; O . opBULTINT , [ C ; L ] , ( fun args -> let const = Lambda . Const_base ( Const_int args . ( 0 ) ) in [ Kpush ; Kconst const ; Kisout ; Kbranchif args . ( 1 ) ] ) ; O . opBUGEINT , [ C ; L ] , ( fun args -> let const = Lambda . Const_base ( Const_int args . ( 0 ) ) in [ Kpush ; Kconst const ; Kisout ; Kbranchifnot args . ( 1 ) ] ) ; O . opGETPUBMET , [ C ; C ] , ( fun args -> [ I . Kgetpubmet args . ( 0 ) ] ) ; O . opGETDYNMET , [ ] , ( fun args -> [ I . Kgetdynmet ] ) ; O . opSTOP , [ ] , ( fun args -> [ I . Kstop ] ) ; O . opEVENT , [ ] , ( fun args -> [ ] ) ; O . opBREAK , [ ] , ( fun args -> failwith " bad instruction : BREAK " ) ; O . opRERAISE , [ ] , ( fun args -> [ I . Kraise Lambda . Raise_reraise ] ) ; O . opRAISE_NOTRACE , [ ] , ( fun args -> [ I . Kraise Lambda . Raise_notrace ] ) ; O . opGETSTRINGCHAR , [ ] , ( fun args -> [ I . Kgetstringchar ] ) ; ] |
let map_label_in_instr f instr = match instr with | I . Klabel _ -> assert false | I . Kpush_retaddr lab -> I . Kpush_retaddr ( f lab ) | I . Kclosure ( lab , k ) -> I . Kclosure ( f lab , k ) | I . Kclosurerec ( labl , k ) -> I . Kclosurerec ( List . map f labl , k ) | I . Kbranch lab -> I . Kbranch ( f lab ) | I . Kbranchif lab -> I . Kbranchif ( f lab ) | I . Kbranchifnot lab -> I . Kbranchifnot ( f lab ) | I . Kstrictbranchif _ -> assert false | I . Kstrictbranchifnot _ -> assert false | I . Kswitch ( laba1 , laba2 ) -> I . Kswitch ( Array . map f laba1 , Array . map f laba2 ) | I . Kpushtrap lab -> I . Kpushtrap ( f lab ) | _ -> instr |
let get_labels_in_instr instr = match instr with | I . Klabel _ -> assert false | I . Kpush_retaddr lab [ -> lab ] | I . Kclosure ( lab , k ) -> [ lab ] | I . Kclosurerec ( labl , k ) -> labl | I . Kbranch lab -> [ lab ] | I . Kbranchif lab -> [ lab ] | I . Kbranchifnot lab -> [ lab ] | I . Kstrictbranchif _ -> assert false | I . Kstrictbranchifnot _ -> assert false | I . Kswitch ( laba1 , laba2 ) -> Array . append laba1 laba2 |> Array . to_list | I . Kpushtrap lab -> [ lab ] | _ -> [ ] |
let decode exec = let instrs_l = instructions exec in let num = List . fold_left ( fun acc ( n , _ , _ ) -> max acc n ) ( - 1 ) instrs_l + 1 in let instrs = Array . make num ( [ ] , fun args -> failwith " bad instruction " ) in List . iter ( fun ( opcode , signature , decoder ) -> instrs . ( opcode ) <- ( signature , decoder ) ) instrs_l ; let code = exec . code in let decoded = ref [ ] in let p = ref 0 in let read_int ( ) = let k = ( Char . code code . [ ! p ] ) lor ( Char . code code . [ ! p + 1 ] lsl 8 ) lor ( Char . code code . [ ! p + 2 ] lsl 16 ) lor ( Char . code code . [ ! p + 3 ] lsl 24 ) in p := ! p + 4 ; let bit30 = ( k land 0x4000_0000 ) <> 0 in let neg_fixup = if bit30 then ( - 1 ) lxor 0x3fff_ffff else 0 in k lor neg_fixup in while ! p < String . length code do let p0 = ! p in let label_origin = ref ( - 1 ) in let op = read_int ( ) in if op < 0 || op >= num then failwith " bad instruction " ; let ( signature , decoder ) = instrs . ( op ) in let len0 = ref 0 in let len1 = ref 0 in let q = Queue . create ( ) in List . iter ( function | C -> Queue . add ( read_int ( ) ) q | L -> let b = ! p in let rel_label = read_int ( ) in let abs_label = b / 4 + rel_label in Queue . add abs_label q | N -> len0 := read_int ( ) ; len1 := 0 ; Queue . add ! len0 q | NN -> let k = read_int ( ) in len0 := k land 0xffff ; len1 := k lsr 16 ; Queue . add k q | LO -> label_origin := ! p | LL -> let n = ! len0 in len0 := ! len1 ; len1 := 0 ; if ! label_origin < 0 then failwith " no label origin " ; for k = 1 to n do let rel_label = read_int ( ) in let abs_label = ! label_origin / 4 + rel_label in Queue . add abs_label q done ) signature ; let args = Array . make ( Queue . length q ) 0 in let k = ref 0 in Queue . iter ( fun arg -> args . ( ! k ) <- arg ; incr k ) q ; let instr_l = decoder args |> List . map ( fun instr -> ( p0 , instr ) ) in decoded := List . rev_append instr_l ! decoded ; done ; let decoded_a = List . rev ! decoded |> Array . of_list in let labels = Array . make ( ! p / 4 ) ( - 1 ) in Array . iteri ( fun i ( bytepos , _ ) -> if labels . ( bytepos / 4 ) = ( - 1 ) then labels . ( bytepos / 4 ) <- i ) decoded_a ; let all_labels = ref ISet . empty in let map_label lab = if lab < 0 || lab >= Array . length labels then failwith " bad label " ; let lab ' = labels . ( lab ) in if lab ' < 0 then failwith " bad label " ; all_labels := ISet . add lab ' ! all_labels ; lab ' in let ext_map_label lab = if lab < 0 || lab >= Array . length labels then raise Not_found ; let lab ' = labels . ( lab ) in if lab ' < 0 then raise Not_found ; lab ' in let all_instrs = decoded_a |> Array . mapi ( fun i ( _ , instr ) -> match instr with | I . Klabel _ -> assert false | I . Kpush_retaddr lab -> I . Kpush_retaddr ( map_label lab ) | I . Kclosure ( lab , k ) -> I . Kclosure ( map_label lab , k ) | I . Kclosurerec ( labl , k ) -> I . Kclosurerec ( List . map map_label labl , k ) | I . Kbranch lab -> I . Kbranch ( map_label lab ) | I . Kbranchif lab -> I . Kbranchif ( map_label lab ) | I . Kbranchifnot lab -> I . Kbranchifnot ( map_label lab ) | I . Kstrictbranchif _ -> assert false | I . Kstrictbranchifnot _ -> assert false | I . Kswitch ( laba1 , laba2 ) -> I . Kswitch ( Array . map map_label laba1 , Array . map map_label laba2 ) | I . Kpushtrap lab -> I . Kpushtrap ( map_label lab ) | _ -> instr ) in ( all_instrs , ! all_labels , ext_map_label ) |
let defname_of_label exec map_label = let ht = Hashtbl . create 7 in Hashtbl . iter ( fun pos defname -> try let lab = map_label pos in try let ( old_pos , _ ) = Hashtbl . find ht lab in if pos < old_pos then Hashtbl . replace ht lab ( pos , defname ) with | Not_found -> Hashtbl . add ht lab ( pos , defname ) with | Not_found -> ( ) ) exec . debug ; ( fun lab -> try snd ( Hashtbl . find ht lab ) with | Not_found -> snd ( Hashtbl . find ht ( lab + 1 ) ) ) |
type sexp = | K of string | ID of string | N of number | S of string | C of string | BR | L of sexp list |
let itable = Hashtbl . create 7 |
let indentation k = try Hashtbl . find itable k with | Not_found -> let s = String . make ( k / 8 ) ' \ t ' ^ String . make ( k mod 8 ) ' ' in Hashtbl . add itable k s ; s |
let rec quote s = let b = Buffer . create 80 in String . iter ( fun c -> if c = ' " ' || c = ' ' \\ || Char . code c < 32 || Char . code c >= 127 then ( Buffer . add_char b ' ' ; \\ Buffer . add_char b Wc_util . hexdigits . ( Char . code c lsr 4 ) ; Buffer . add_char b Wc_util . hexdigits . ( Char . code c land 15 ) ; ) else Buffer . add_char b c ) s ; Buffer . contents b |
let rec string_of_sexp sexp = match sexp with | K x -> x | ID x -> " " $ ^ x | S x -> " " " \ ^ ( quote x ) ^ " " " \ | N x -> string_of_number x | C x -> sprintf " ( ; % s ; ) " x | BR -> " " | L l -> let l = List . filter ( fun e -> e <> BR ) l in " ( " ^ string_of_sexp_list l ^ " ) " List . map string_of_sexp l |> String . concat " " |
let fits_onto_line width sexp = let rec single width sexp = match sexp with | K _ | ID _ | S _ | N _ | C _ | BR -> string_of_sexp sexp |> String . length | L l -> if width >= 2 then list ( width - 2 ) l + 2 else width + 1 and list width l = match l with | BR :: l ' -> list width l ' | x :: l ' -> let len = single width x in let len = ( if l ' <> [ ] then len + 1 else len ) in if len >= width then width + 1 else list ( width - len ) l ' + len | [ ] -> 0 in single width sexp <= width |
let break l = let rec recurse acc l = match l with | BR :: l ' -> ( List . rev acc , l ' ) | x :: l ' -> recurse ( x :: acc ) l ' | [ ] -> ( [ ] , List . rev acc ) in recurse [ ] l |
let rec print_indented f indent width sexp = match sexp with | K _ | ID _ | S _ | N _ | C _ | BR -> fprintf f " % s % s " ( indentation indent ) ( string_of_sexp sexp ) | L l -> if width > indent && fits_onto_line ( width - indent ) sexp then fprintf f " % s % s " ( indentation indent ) ( string_of_sexp sexp ) else let l_nobreak , l_break = break l in let first_line , tail = match l_nobreak , l_break with | [ ] , [ ] -> [ ] , [ ] | [ ] , ( x :: l ) -> [ x ] , l | _ -> l_nobreak , l_break in fprintf f " % s ( % s " ( indentation indent ) ( string_of_sexp_list first_line ) ; List . iter ( fun elem -> fprintf f " \ n " ; print_indented f ( indent + 2 ) width elem ) tail ; fprintf f " ) " |
let rec ascii s = let b = Buffer . create 80 in Buffer . add_string b " \ t . ascii " " ; \ String . iteri ( fun i c -> if i > 0 && i mod 32 = 0 then ( Buffer . add_string b " " \\ n \ t . ascii " " ; \ ) ; if c = ' " ' || c = ' ' \\ || Char . code c < 32 || Char . code c >= 127 then ( Buffer . add_char b ' ' ; \\ Buffer . add_char b ' x ' ; Buffer . add_char b Wc_util . hexdigits . ( Char . code c lsr 4 ) ; Buffer . add_char b Wc_util . hexdigits . ( Char . code c land 15 ) ; ) * Buffer . add_char b ' ' ; \\ Buffer . add_char b Wc_util . hexdigits . ( Char . code c lsr 6 ) ; Buffer . add_char b Wc_util . hexdigits . ( ( Char . code c lsr 3 ) land 7 ) ; Buffer . add_char b Wc_util . hexdigits . ( Char . code c land 7 ) ; ) else Buffer . add_char b c ) s ; Buffer . add_string b " " \\ n " ; Buffer . contents b |
let extract_func_type l = let rec scan params results l = match l with | ( L [ K " param " ; K ty ] ) :: l ' -> scan ( ty :: params ) results l ' | ( L [ K " result " ; K ty ] ) :: l ' -> scan params ( ty :: results ) l ' | other -> let llvm_type = sprintf " ( % s ) -> ( % s ) " ( String . concat " , " ( List . rev params ) ) ( String . concat " , " ( List . rev results ) ) in ( llvm_type , other ) in scan [ ] [ ] l |
let abbrev_empty_type s = if s = " ( ) -> ( ) " then " " else s |
let llvm_type_of_func_type typeuse = let ( llvm_type , rest ) = extract_func_type typeuse in if rest <> [ ] then failwith ( " llvm_type_of_func_type : " ^ string_of_sexp ( L rest ) ) ; llvm_type |
let extract_label l = match l with | ( ID label ) :: rest -> ( label , rest ) | _ -> ( " < empty " , > l ) |
let extract_load_store_params l = let rec recurse offset align l = match l with | ( K tok ) :: rest -> ( try let offset = Scanf . sscanf tok " offset =% i " ( fun x -> x ) in recurse offset align rest with End_of_file | Scanf . Scan_failure _ -> ( try let align = Scanf . sscanf tok " align =% i " ( fun x -> x ) in recurse offset align rest with End_of_file | Scanf . Scan_failure _ -> raise Not_found ) ) | _ :: _ -> raise Not_found | [ ] -> ( offset , align ) in recurse 0 0 l |
let find_label name l = let rec recurse i l = match l with | x :: l ' -> if name = x then i else recurse ( i + 1 ) l ' | [ ] -> raise Not_found in recurse 0 l |
let itable = Hashtbl . create 7 |
let indentation k = try Hashtbl . find itable k with | Not_found -> let s = String . make ( k / 8 ) ' \ t ' ^ String . make ( k mod 8 ) ' ' in Hashtbl . add itable k s ; s |
let write_func_body f func_name locals_table sexpl = let rec next labels depth sexpl = let bad ( ) = failwith ( sprintf " bad code - function % s - % s " func_name ( string_of_sexp ( L sexpl ) ) ) in let indent = indentation ( 4 * depth ) in match sexpl with | L [ K ( " local . get " " | local . set " " | local . tee " as instr ) ; ID name ] :: rest -> let index = try Hashtbl . find locals_table name with Not_found -> failwith ( sprintf " local not found - function % s local % s " func_name name ) in fprintf f " \ t % s % s % d # $% s \ n " indent instr index name ; next labels depth rest | L ( K ( " i32 . load " " | i32 . store " " | i64 . load " " | i64 . store " | " f32 . load " " | f32 . store " " | f64 . load " " | f64 . store " as instr ) :: inner ) :: rest -> let offset , align = try extract_load_store_params inner with Not_found -> bad ( ) in fprintf f " \ t % s % s 0x % x : p2align =% d \ n " indent instr offset align ; next labels depth rest | L ( K ( " i32 . load8_u " | " i32 . load8_s " | " i32 . store8 " as instr ) :: inner ) :: rest -> let offset , align = try extract_load_store_params inner with Not_found -> bad ( ) in if align <> 0 then bad ( ) ; fprintf f " \ t % s % s 0x % x \ n " indent instr offset ; next labels depth rest | L ( K ( " br " " | br_if " " | br_table " as instr ) :: inner ) :: rest -> let lab_names = List . map ( function | ID lab -> lab | bad -> failwith ( sprintf " bad code - function % s - % s " func_name ( string_of_sexp bad ) ) ) inner in let all_lab_names = lab_names |> String . concat " , " in let lab_nums = List . map ( fun name -> try find_label name labels with Not_found -> failwith ( sprintf " label not found - function % s label % s " func_name name ) ) lab_names in let branches = List . map string_of_int lab_nums |> String . concat " , " in let opt_curlies = if instr = " br_table " then " { " ^ branches ^ " } " else branches in fprintf f " \ t % s % s % s # % s \ n " indent instr opt_curlies all_lab_names ; next labels depth rest | L ( K " call_indirect " :: N ( I32 table ) :: inner ) :: rest -> let ty , inner2 = extract_func_type inner in if inner2 <> [ ] then failwith ( sprintf " bad code - function % s - % s " func_name ( string_of_sexp ( L sexpl ) ) ) ; fprintf f " \ t % scall_indirect % s \ n " indent ty ; next labels depth rest | L ( K " block " :: inner ) :: rest -> let label , inner2 = extract_label inner in let ty , body = extract_func_type inner2 in let ty = abbrev_empty_type ty in fprintf f " \ t % sblock % s # label % s \ n " indent ty label ; next ( label :: labels ) ( depth + 1 ) body ; fprintf f " \ t % send_block # label % s \ n " indent label ; next labels depth rest | L ( K " loop " :: inner ) :: rest -> let label , inner2 = extract_label inner in let ty , body = extract_func_type inner2 in let ty = abbrev_empty_type ty in fprintf f " \ t % sloop % s # label % s \ n " indent ty label ; next ( label :: labels ) ( depth + 1 ) body ; fprintf f " \ t % send_loop # label % s \ n " indent label ; next labels depth rest | L ( K " if " :: inner ) :: rest -> let label , inner2 = extract_label inner in let ty , body = extract_func_type inner2 in let ty = abbrev_empty_type ty in ( match body with | [ L ( K " then " :: then_sexpl ) ] -> fprintf f " \ t % sif % s # label % s \ n " indent ty label ; next ( label :: labels ) ( depth + 1 ) then_sexpl ; fprintf f " \ t % send_if # label % s \ n " indent label ; | [ L ( K " then " :: then_sexpl ) ; L ( K " else " :: else_sexpl ) ] -> fprintf f " \ t % sif % s # label % s \ n " indent ty label ; next ( label :: labels ) ( depth + 1 ) then_sexpl ; fprintf f " \ t % selse \ n " indent ; next ( label :: labels ) ( depth + 1 ) else_sexpl ; fprintf f " \ t % send_if # label % s \ n " indent label ; | _ -> failwith ( sprintf " bad code - function % s - % s " func_name ( string_of_sexp ( L body ) ) ) ) ; next labels depth rest | L [ K instr ] :: rest -> fprintf f " \ t % s % s \ n " indent instr ; next labels depth rest | L [ K instr ; N ( I32 x ) ] :: rest -> fprintf f " \ t % s % s 0x % lx \ n " indent instr x ; next labels depth rest | L [ K instr ; N ( I64 x ) ] :: rest -> fprintf f " \ t % s % s 0x % Lx \ n " indent instr x ; next labels depth rest | L [ K instr ; N ( F64 x ) ] :: rest -> fprintf f " \ t % s % s % h \ n " indent instr x ; next labels depth rest | L [ K instr ; ID name ] :: rest -> fprintf f " \ t % s % s % s \ n " indent instr name ; next labels depth rest | _ :: _ -> bad ( ) | [ ] -> ( ) in next [ ] 0 sexpl |
let rec remove_stuff l = let rec f = function | BR -> None | C _ -> None | L l -> Some ( L ( remove_stuff l ) ) | other -> Some other in List . filter_map f l |
let write_file f filename sexpl = let import sym mod_name obj_name = fprintf f " \ t . import_module % s , % s \ n " sym mod_name ; fprintf f " \ t . import_name % s , % s \ n " sym obj_name in let export sym obj_name = fprintf f " \ t . export_name % s , % s \ n " sym obj_name in let global glb_name w_type = let glb_type , is_mut = ( match w_type with | L [ K " mut " ; K ty ] :: _ -> ty , true | K ty :: _ -> ty , false | _ -> failwith ( sprintf " bad global % s " glb_name ) ) in fprintf f " \ t . globaltype % s , % s % s \ n " glb_name glb_type " " in let datasection name = fprintf f " \ t . section . rodata . % s , " " , \\@\ n " name ; fprintf f " \ t . hidden % s \ n " name ; fprintf f " \ t . type % s , @ object \ n " name ; fprintf f " % s :\ n " name in let emitdata l = let have_section = ref None in let size_section = ref 0 in let print_size ( ) = match ! have_section with | Some name -> fprintf f " \ t . size % s , % d \ n " name ! size_section | None -> ( ) in List . iter ( function | L ( K " memory " :: _ ) -> ( ) | L ( K " offset " :: _ ) -> ( ) | ID name -> print_size ( ) ; datasection name ; have_section := Some name | S data -> ( match ! have_section with | None -> print_size ( ) ; datasection " __anondata " ; have_section := Some " __anondata " | Some _ -> ( ) ) ; output_string f ( ascii data ) ; size_section := ! size_section + String . length data | _ -> failwith ( " cannot decode ' data ' " ) ) l ; print_size ( ) in let rec func_1 func_name exp_name_opt params results locals sexpl = match sexpl with | L [ K " export " ; S n ] :: rest -> func_1 func_name ( Some n ) params results locals rest | L [ K " param " ; ID n ; K ty ] :: rest -> func_1 func_name exp_name_opt ( ( n , ty ) :: params ) results locals rest | L [ K " result " ; K ty ] :: rest -> func_1 func_name exp_name_opt params ( ty :: results ) locals rest | L [ K " local " ; ID n ; K ty ] :: rest -> func_1 func_name exp_name_opt params results ( ( n , ty ) :: locals ) rest | body -> fprintf f " \ n \ t . section . text . % s , " " , \\@\ n " func_name ; ( match exp_name_opt with | None -> fprintf f " \ t . hidden % s \ n " func_name | Some exp_name -> export func_name exp_name ) ; fprintf f " \ t . globl % s \ n " func_name ; fprintf f " \ t . type % s , @ function \ n " func_name ; fprintf f " % s :\ n " func_name ; fprintf f " \ t . functype % s ( % s ) -> ( % s ) \ n " func_name ( List . rev params |> List . map snd |> String . concat " , " ) ( List . rev results |> String . concat " , " ) ; if locals <> [ ] then fprintf f " \ t . local % s \ n " ( List . rev locals |> List . map snd |> String . concat " , " ) ; let locals_table = Hashtbl . create 7 in Array . iteri ( fun i ( n , _ ) -> Hashtbl . add locals_table n i ) ( Array . append ( List . rev params |> Array . of_list ) ( List . rev locals |> Array . of_list ) ) ; write_func_body f func_name locals_table body ; fprintf f " \ tend_function \ n " in let func func_name sexpl = match sexpl with | K " export " :: S obj_name :: rest -> func_1 func_name ( Some obj_name ) [ ] [ ] [ ] rest | _ -> func_1 func_name None [ ] [ ] [ ] sexpl in fprintf f " \ t . text \ n " ; fprintf f " \ t . file % S \ n " filename ; List . iter ( fun mod_sexp -> match mod_sexp with | L [ K " import " ; S mod_name ; S obj_name ; L imp_sexpl ] -> ( match imp_sexpl with | ( K " memory " ) :: _ -> ( ) | ( K " table " ) :: _ -> ( ) | ( K " func " ) :: ( ID func_name ) :: w_type -> let func_type = llvm_type_of_func_type w_type in fprintf f " \ t . functype % s % s \ n " func_name func_type ; import func_name mod_name obj_name | ( K " global " ) :: ( ID glb_name ) :: w_type -> global glb_name w_type ; import glb_name mod_name obj_name | _ -> failwith ( " write_file : bad import : " ^ string_of_sexp ( L imp_sexpl ) ) ) ; | L ( K ( " memory " | " table " ) :: _ ) -> ( ) | L ( K " func " :: ID func_name :: rest ) -> func func_name rest | L ( K " global " :: ( ID glb_name ) :: w_type ) -> global glb_name w_type ; fprintf f " % s :\ n " glb_name ; | L ( K " data " :: inner ) -> emitdata inner | L [ K " export " ; ID obj_name ; L descr ] -> ( match descr with | [ K ( " func " | " global " ) ; ID sym_name ] -> export sym_name obj_name | ( K ( " memory " | " table " ) :: _ ) -> ( ) | _ -> failwith ( " write_file : bad export : " ^ string_of_sexp ( L descr ) ) ) | _ -> failwith ( " write_file : bad definition : " ^ string_of_sexp mod_sexp ) ) ( remove_stuff sexpl ) |
type initvalue = | Unknown | Function of { label : int } | FuncInEnv of { func_offset : int ; env : initvalue array } | Block of initvalue array |
let is_function = function | Function _ -> true | _ -> false |
type shape = { stack : initvalue list ; length : int ; accu : initvalue } |
let empty_shape = { stack = [ ] ; length = 0 ; accu = Unknown } |
let print_initvalue prefix initvalue = let rec recurse prefix initvalue = match initvalue with | Unknown -> ( ) | Function fn -> printf " % s = letrec_ % d \ n " prefix fn . label | FuncInEnv fenv -> Array . iteri ( fun i iv -> recurse ( sprintf " % s . env [ % d ] ( % d ) " prefix i fenv . func_offset ) iv ) fenv . env | Block b -> Array . iteri ( fun i iv -> recurse ( sprintf " % s [ % d ] " prefix i ) iv ) b in recurse prefix initvalue |
let rec merge_initvalues v1 v2 = match v1 , v2 with | Function fn1 , Function fn2 when fn1 . label = fn2 . label -> v1 | FuncInEnv fenv1 , FuncInEnv fenv2 when fenv1 . func_offset = fenv2 . func_offset && Array . length fenv1 . env = Array . length fenv2 . env -> let env = merge_initvalue_arrays fenv1 . env fenv2 . env in FuncInEnv { fenv1 with env } | Block b1 , Block b2 when Array . length b1 = Array . length b2 -> Block ( merge_initvalue_arrays b1 b2 ) | _ -> Unknown Array . mapi ( fun i bv1 -> let bv2 = a2 . ( i ) in merge_initvalues bv1 bv2 ) a1 |
let merge_stacks s1 s2 = assert ( s1 . length = s2 . length ) ; { stack = List . map2 merge_initvalues s1 . stack s2 . stack ; length = s1 . length ; accu = merge_initvalues s1 . accu s2 . accu ; } |
let rec delete n l = if n <= 0 then l else match l with | x :: l ' -> delete ( n - 1 ) l ' | [ ] -> [ ] |
let global_offset ident = assert ( Ident . global ident ) ; let name = Ident . name ident in int_of_string name |
let trace_globals_of_fblock globals_table fblock = let shape_table = Hashtbl . create 7 in let update_shape_table stack labels = List . iter ( fun label -> try let lstack = Hashtbl . find shape_table label in if lstack . length <> stack . length then ( eprintf " [ DEBUG ] Bad function : % d \ n " fblock . scope . cfg_func_label ; eprintf " [ DEBUG ] Bad label : % d \ n " label ; eprintf " [ DEBUG ] stack . length =% d lstack . length =% d \ n " stack . length lstack . length ; Wc_tracestack . dump fblock . block 0 ; assert false ; ) ; let merged = merge_stacks stack lstack in Hashtbl . replace shape_table label merged with | Not_found -> Hashtbl . add shape_table label stack ) labels in let trace_instr shape i = match i with | I . Kacc sp -> if sp < shape . length then { shape with accu = List . nth shape . stack sp } else { shape with accu = Unknown } | Kpush -> { shape with stack = shape . accu :: shape . stack ; length = shape . length + 1 } | Kpop n -> { shape with stack = delete n shape . stack ; length = shape . length - n } | Kassign sp -> let stack = List . mapi ( fun i x -> if i = sp then shape . accu else x ) shape . stack in { shape with stack } | Kmakeblock ( size , 0 ) when size > 0 -> let block = shape . accu :: list_prefix ( size - 1 ) shape . stack |> Array . of_list |> ( fun a -> Block a ) in { stack = delete ( size - 1 ) shape . stack ; length = shape . length - ( size - 1 ) ; accu = block } | Kclosure ( label , num ) -> let env_fields = if num = 0 then [ ] else shape . accu :: list_prefix ( num - 1 ) shape . stack in let env = Array . of_list ( Function { label } :: Unknown :: env_fields ) in let n = max ( num - 1 ) 0 in { accu = FuncInEnv { func_offset = 0 ; env } ; stack = delete n shape . stack ; length = shape . length - n } | Kclosurerec ( labs , num ) when labs <> [ ] -> let num_labs = List . length labs in let env_fields = if num = 0 then [ ] else shape . accu :: list_prefix ( num - 1 ) shape . stack in let env_fields_a = Array . of_list env_fields in let unknowns = Array . make ( 2 + 3 * ( num_labs - 1 ) ) Unknown in let env = Array . append unknowns env_fields_a in let n = max ( num - 1 ) 0 in let funcs = List . rev labs |> List . mapi ( fun i label -> let func_offset = 3 * ( num_labs - i - 1 ) in env . ( func_offset ) <- Function { label } ; FuncInEnv { func_offset ; env } ) in { stack = funcs @ delete n shape . stack ; length = shape . length + - n + List . length funcs ; accu = Unknown } | Ksetglobal ident -> let offset = global_offset ident in Hashtbl . replace globals_table offset shape . accu ; shape | _ -> let d = Wc_traceinstr . trace_stack_instr 0 i in if d > 0 then let nstack = Array . make d Unknown |> Array . to_list in { stack = nstack @ shape . stack ; length = shape . length + d ; accu = Unknown } else if d < 0 then { stack = delete ( - d ) shape . stack ; length = shape . length + d ; accu = Unknown } else { shape with accu = Unknown } in let rec recurse block = Array . fold_left ( fun shape instr -> match instr with | Label label -> let stack = try Hashtbl . find shape_table label with Not_found -> empty_shape in stack | Simple i -> let labels = Wc_tracestack . local_branch_labels i in update_shape_table shape labels ; let stack ' = trace_instr shape i in stack ' | Trap { catchlabel ; poplabel = Some pop } -> update_shape_table shape [ catchlabel ; pop ] ; shape | Trap { catchlabel ; poplabel = None } -> update_shape_table shape [ catchlabel ] ; shape | TryReturn -> shape | NextMain _ -> shape | Block inner -> recurse inner ) empty_shape block . instructions in ignore ( recurse fblock . block ) |
let trace_globals scode = let globals_table = Hashtbl . create 7 in IMap . iter ( fun func_label fblock -> if fblock . scope . cfg_main then trace_globals_of_fblock globals_table fblock ) scode . functions ; globals_table |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.