text
stringlengths
0
601k
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
let derive_glbfun_table globals_table = let glbfun_table = Hashtbl . create 7 in let rec recurse initvalue = match initvalue with | Unknown -> ( ) | Block b -> Array . iter recurse b | FuncInEnv { env ; _ } -> Array . iteri ( fun func_offset env_val -> match env_val with | Function { label } -> Hashtbl . replace glbfun_table label ( func_offset , env ) | _ -> ( ) ) env | Function _ -> assert false in Hashtbl . iter ( fun glb initvalue -> recurse initvalue ) globals_table ; glbfun_table
let trace_stack_max depth instr = match instr with | I . Kapply num -> if num < 4 then depth + 3 else depth | Kappterm ( num , slots ) -> max depth ( depth - slots + num ) | Kpushtrap _ -> depth + 4 | _ -> depth
let trace_stack_instr depth instr = match instr with | I . Klabel _ -> assert false | Krestart -> depth | Kconst _ | Kacc _ | Kassign _ | Kenvacc _ | Kgetglobal _ -> depth | Kpush -> depth + 1 | Kpop num -> depth - num | ( Knegint | Kboolnot | Koffsetint _ | Koffsetref _ | Kisint | Ksetglobal _ | Kgetfield _ | Kgetfloatfield _ | Kvectlength ) -> depth | ( Kaddint | Ksubint | Kmulint | Kdivint | Kmodint | Kandint | Korint | Kxorint | Klslint | Klsrint | Kasrint | Kintcomp _ | Kisout | Ksetfield _ | Ksetfloatfield _ | Kgetvectitem | Kgetstringchar | Kgetbyteschar ) -> depth - 1 | ( Ksetvectitem | Ksetbyteschar ) -> depth - 2 | ( Kmakeblock ( size , _ ) | Kmakefloatblock size ) -> depth ( - max ( size - 1 ) 0 ) | Kccall ( _ , num ) -> depth ( - num - 1 ) | Kbranch _ | Kbranchif _ | Kbranchifnot _ | Kswitch _ -> depth | Kpush_retaddr _ -> depth + 3 | Kapply num -> depth - num - ( if num < 4 then 0 else 3 ) | Kappterm _ | Kreturn _ | Kraise _ | Kstop -> depth | Kgrab _ -> depth | Kclosure ( _ , num ) -> depth ( - max ( num - 1 ) 0 ) | Kclosurerec ( funcs , num ) -> let num_funcs = List . length funcs in depth ( - max ( num - 1 ) 0 ) + num_funcs | Koffsetclosure _ -> depth | Kpushtrap _ | Kpoptrap -> depth | Kcheck_signals -> depth | Kgetmethod -> depth | Kgetpubmet _ -> depth + 1 | Kgetdynmet -> depth | Kevent _ -> depth | Kstrictbranchif _ -> assert false | Kstrictbranchifnot _ -> assert false
let max_stack_depth_of_instrs instrs = let len = Array . length instrs in let rec recurse mdepth depth k = if k < len then let mdep = trace_stack_max depth instrs . ( k ) in let depth ' = trace_stack_instr depth instrs . ( k ) in recurse ( max mdepth ( max mdep depth ' ) ) depth ' ( k + 1 ) else mdepth in recurse 0 0 0
let local_branch_labels = function | I . Kbranch l -> [ l ] | Kbranchif l -> [ l ] | Kbranchifnot l -> [ l ] | Kswitch ( la1 , la2 ) -> Array . to_list la1 @ Array . to_list la2 | _ -> [ ]
let rec dump block indent = let open Wc_control in let open Wc_util in let istr = String . make ( 4 * indent ) ' ' in eprintf " % sBLOCK % s % s \ n " istr ( match block . loop_label with | Some l -> sprintf " loop =% d " l | None -> " " ) ( match block . break_label with | Some l -> sprintf " break =% d " l | None -> " " ) ; Array . iter ( function | Label label -> eprintf " % sLABEL % d \ n " istr label | Simple i -> eprintf " % s % s \ n " istr ( string_of_kinstruction i ) | Trap { trylabel ; catchlabel ; poplabel } -> eprintf " % sTrap try =% d catch =% d pop =% s \ n " istr trylabel catchlabel ( Option . map string_of_int poplabel |> Option . value ~ default " " ) : | TryReturn -> eprintf " % sTryReturn \ n " istr | NextMain label -> eprintf " % sNextMain % d \ n " istr label | Block inner -> dump inner ( indent + 1 ) ) block . instructions
let max_stack_depth_of_fblock fblock = let open Wc_control in let depth_table = Hashtbl . create 7 in let update_depth_table depth labels = List . iter ( fun label -> try let d = Hashtbl . find depth_table label in if d <> depth then ( eprintf " [ DEBUG ] Bad function : % d \ n " fblock . scope . cfg_func_label ; eprintf " [ DEBUG ] Bad label : % d \ n " label ; eprintf " [ DEBUG ] d =% d depth =% d \ n " d depth ; dump fblock . block 0 ; assert false ; ) with | Not_found -> Hashtbl . add depth_table label depth ) labels in let rec recurse block = Array . fold_left ( fun ( max_depth , depth ) instr -> match instr with | Label label -> let depth = try Hashtbl . find depth_table label with Not_found -> 0 in ( max max_depth depth , depth ) | Simple i -> let labels = local_branch_labels i in update_depth_table depth labels ; let depth ' = Wc_traceinstr . trace_stack_instr depth i in ( max depth ' max_depth , depth ' ) | Trap { catchlabel ; poplabel = Some pop } -> update_depth_table depth [ catchlabel ; pop ] ; ( max_depth , depth ) | Trap { catchlabel ; poplabel = None } -> update_depth_table depth [ catchlabel ] ; ( max_depth , depth ) | TryReturn -> ( max_depth , depth ) | NextMain _ -> ( max_depth , depth ) | Block inner -> recurse inner ) ( 0 , 0 ) block . instructions in recurse fblock . block |> fst
type state = { camlstack : store list ; camldepth : int ; accu : store ; realaccu : ISet . t ; arity : int ; }
type lpad = { locals : ( string , repr ) Hashtbl . t ; mutable avoid_locals : bool ; mutable loops : ISet . t ; indegree : ( int , int ) Hashtbl . t ; state_table : ( int , state ) Hashtbl . t ; mutable globals_table : ( int , Wc_traceglobals . initvalue ) Hashtbl . t ; mutable environment : Wc_traceglobals . initvalue array ; mutable func_offset : int ; }
let real_accu = RealAccu { no_function = false }
let real_accu_no_func = RealAccu { no_function = true }
let empty_state = { camlstack = [ ] ; camldepth = 0 ; accu = Invalid ; realaccu = ISet . empty ; arity = 1 ; }
let empty_lpad ( ) = { locals = Hashtbl . create 7 ; avoid_locals = false ; loops = ISet . empty ; indegree = Hashtbl . create 7 ; state_table = Hashtbl . create 7 ; globals_table = Hashtbl . create 1 ; environment = [ | ] ; | func_offset = 0 ; }
let new_local lpad repr = let k = Hashtbl . length lpad . locals in let s = sprintf " x % d " k in Hashtbl . add lpad . locals s repr ; s
let stack_descr state = let cd = state . camldepth in let rd = ref 0 in let stack = Array . make cd false in List . iter ( fun st -> match st with | RealStack pos -> assert ( pos >= ( - cd ) ) ; if pos < 0 then ( stack . ( pos + cd ) <- true ; rd := max ! rd ( - pos ) ) | _ -> ( ) ) state . camlstack ; let uninit = ref [ ] in Array . iteri ( fun i used -> if not used && i >= cd - ! rd then uninit := ( - cd + i ) :: ! uninit ) stack ; let stack_save_accu = state . realaccu <> ISet . empty || ( match state . accu with RealAccu _ -> true | _ -> false ) in { stack_uninit = ! uninit ; stack_depth = ! rd ; stack_save_accu }
let set_camlstack pos store state = let cd = state . camldepth in if pos >= ( - cd ) && pos <= ( - 1 ) then let camlstack = List . mapi ( fun i old_store -> if ( - cd + i ) = pos then store else old_store ) state . camlstack in camlstack else state . camlstack
let pop_camlstack state = let cd = state . camldepth in let cpos = ( - cd ) in match state . camlstack with | RealStack pos :: tl -> { state with camlstack = tl ; camldepth = cd - 1 ; } | ( RealAccu _ ) :: tl -> { state with camlstack = tl ; camldepth = cd - 1 ; realaccu = ISet . remove cpos state . realaccu ; } | ( Const _ | Local _ | Atom _ | TracedGlobal _ | Invalid ) :: tl -> { state with camlstack = tl ; camldepth = cd - 1 } | [ ] -> assert false
let rec popn_camlstack number state = if number = 0 then state else popn_camlstack ( number - 1 ) ( pop_camlstack state )
let push_camlstack store state = let cd = state . camldepth in let cpos = ( - cd - 1 ) in match store with | RealStack pos -> { state with camlstack = store :: state . camlstack ; camldepth = cd + 1 ; } | RealAccu _ -> { state with camlstack = store :: state . camlstack ; camldepth = cd + 1 ; realaccu = ISet . add cpos state . realaccu ; } | ( Const _ | Local _ | Atom _ | TracedGlobal _ ) -> { state with camlstack = store :: state . camlstack ; camldepth = cd + 1 ; } | Invalid -> assert false
let flush_accu lpad state = let instrs_rev = ISet . fold ( fun pos instr_acc -> let instr = Wcopy { src = real_accu ; dest = RealStack pos } in instr :: instr_acc ) state . realaccu [ ] in let instrs = List . rev instrs_rev in let camlstack = List . mapi ( fun i old -> let pos = ( - state . camldepth + i ) in if ISet . mem pos state . realaccu then ( RealStack pos ) else old ) state . camlstack in let state = { state with camlstack ; realaccu = ISet . empty ; } in ( state , instrs )
let straighten_accu lpad state = let state , instrs_flush = flush_accu lpad state in match state . accu with | Invalid -> ( state , [ ] ) | RealAccu _ -> ( state , instrs_flush ) | store -> let instr = Wcopy { src = store ; dest = real_accu } in let state = { state with accu = real_accu } in ( state , instrs_flush @ [ instr ] )
let straighten_accu_when_on_stack lpad state = match state . accu with | ( RealStack _ ) -> straighten_accu lpad state | _ -> ( state , [ ] )
let straighten_accu_for_branch lpad state = match state . accu with | RealStack _ | Const _ | Atom _ | TracedGlobal _ -> straighten_accu lpad state | Local _ | RealAccu _ | Invalid -> ( state , [ ] )
let pop_real_stack lpad state num = let cd = state . camldepth in match state . accu with | ( RealStack pos ) when pos >= ( - cd ) && pos <= ( - cd + num - 1 ) -> straighten_accu lpad state | _ -> ( state , [ ] )
let flush_real_stack_only_accu_at lpad state pos = match state . accu with | ( RealStack p ) when p = pos -> straighten_accu lpad state | _ -> ( state , [ ] )
let patch camlstack depth patches = let rec recurse camlstack pos patches = match patches with | [ ] -> camlstack | next_patch :: patches ' -> if pos = next_patch then match camlstack with | _ :: tl -> RealStack pos :: ( recurse tl ( pos + 1 ) patches ' ) | [ ] -> assert false else match camlstack with | hd :: tl -> hd :: recurse tl ( pos + 1 ) patches | [ ] -> assert false in recurse camlstack ( - depth ) ( ISet . elements patches )
let flush_real_stack_at lpad state pos = let cd = state . camldepth in let state , instrs1 = flush_real_stack_only_accu_at lpad state pos in let _ , positions = List . fold_left ( fun ( q , acc ) store -> match store with | RealStack p when p = pos && q <> p -> assert ( p > q ) ; let acc ' = ISet . add q acc in ( q + 1 , acc ' ) | _ -> ( q + 1 , acc ) ) ( - cd , ISet . empty ) state . camlstack in let instrs2 = positions |> ISet . elements |> List . map ( fun q -> Wcopy { src = RealStack pos ; dest = RealStack q } ) in let camlstack = patch state . camlstack cd positions in let state = { state with camlstack ; } in ( state , instrs1 @ instrs2 ) let cd = state . camldepth in let state , instrs1 = flush_real_stack_only_accu_at lpad state pos in let local = new_local lpad RIntVal in let _ , positions = List . fold_left ( fun ( q , acc ) store -> match store with | RealStack p when p = pos && q <> p -> assert ( p > q ) ; let acc ' = ISet . add q acc in ( q + 1 , acc ' ) | _ -> ( q + 1 , acc ) ) ( - cd , ISet . empty ) state . camlstack in let src = RealStack pos in let instrs2 = [ Wcopy { src ; dest = Local ( RIntVal , local ) } ] in let camlstack = List . mapi ( fun i old -> let q = - cd + i in if ISet . mem q positions then Local ( RIntVal , local ) else old ) state . camlstack in let state = { state with camlstack } in ( state , instrs1 @ instrs2 ) ) *
let straighten_stack_at lpad state pos = if pos >= 0 then ( state , [ Wcomment ( sprintf " ****** STRANGE CASE : straighten_stack_at pos =% d " ***** pos ) ] ) else let k = pos + state . camldepth in let store = List . nth state . camlstack k in match store with | RealAccu _ -> assert ( ISet . mem pos state . realaccu ) ; let state , instrs = flush_accu lpad state in ( state , instrs ) | RealStack p when p = pos -> ( state , [ ] ) | _ -> assert ( not ( List . mem ( RealStack pos ) state . camlstack ) ) ; let instrs = [ Wcopy { src = store ; dest = RealStack pos } ] in let state = { state with camlstack = set_camlstack pos ( RealStack pos ) state ; } in ( state , instrs )
let straighten_stack_multi lpad state pos_list = let state , rev_acc = List . fold_left ( fun ( state , rev_acc ) pos -> let ( state , instrs ) = straighten_stack_at lpad state pos in ( state , List . rev_append instrs rev_acc ) ) ( state , [ ] ) pos_list in ( state , List . rev rev_acc )
let accu_is_realaccu state = match state . accu with | RealAccu _ -> true | _ -> false
let accu_is_realaccu_or_invalid state = match state . accu with | RealAccu _ | Invalid -> true | _ -> false
let straighten_stack lpad state = let state , instrs1 = flush_accu lpad state in let cd = state . camldepth in let pos_list = state . camlstack |> List . mapi ( fun i store -> ( i , store ) ) |> List . concat_map ( fun ( i , store ) -> match store with | RealStack p when p <> - cd + i -> [ - cd + i ] | _ -> [ - cd + i ] ) in let state , instrs2 = straighten_stack_multi lpad state pos_list in ( state , instrs1 @ instrs2 )
let straighten_all lpad state = let state , instrs1 = straighten_accu lpad state in assert ( accu_is_realaccu_or_invalid state && state . realaccu = ISet . empty ) ; let state , instrs2 = straighten_stack lpad state in ( state , instrs1 @ instrs2 )
let localize_accu lpad state repr = match state . accu with | RealStack _ | RealAccu _ -> let local = new_local lpad repr in let lstore = Local ( repr , local ) in let instrs = [ Wcopy { src = state . accu ; dest = lstore } ] in let cd = state . camldepth in let positions = List . mapi ( fun i st -> if st = state . accu then i else ( - 1 ) ) state . camlstack |> List . filter ( fun i -> i >= 0 ) |> List . map ( fun i -> - cd + i ) in let state = List . fold_left ( fun state pos -> { state with camlstack = set_camlstack pos lstore state } ) state positions in let state = { state with accu = lstore } in ( state , instrs ) | _ -> ( state , [ ] )
let unary_operation ( ? no_function = false ) lpad state op_repr op_code = let src1 = state . accu in let op_repr = if lpad . avoid_locals then RValue else op_repr in match op_repr with | RValue -> let state , instrs_flush = flush_accu lpad state in let state = { state with accu = real_accu } in let instrs_op = [ Wunary { op = op_code ; src1 ; dest = real_accu } ] in ( state , instrs_flush @ instrs_op ) | _ -> let dest_name = new_local lpad op_repr in let dest = Local ( op_repr , dest_name ) in let state = { state with accu = dest } in let instrs_op = [ Wunary { op = op_code ; src1 ; dest } ] in ( state , instrs_op )
let unary_effect lpad state op_code = let src1 = state . accu in let state = { state with accu = Const 0 } in let instrs_op = [ Wunaryeffect { op = op_code ; src1 } ] in ( state , instrs_op )
let binary_operation ( ? no_function = false ) lpad state op_repr op_code = let src1 = state . accu in let src2 = List . hd state . camlstack in let op_repr = if lpad . avoid_locals then RValue else op_repr in match op_repr with | RValue -> let state , instrs_flush = flush_accu lpad state in let state = { state with accu = real_accu } |> pop_camlstack in let instrs_op = [ Wbinary { op = op_code ; src1 ; src2 ; dest = real_accu } ] in ( state , instrs_flush @ instrs_op ) | _ -> let dest_name = new_local lpad op_repr in let dest = Local ( op_repr , dest_name ) in let state = { state with accu = dest } |> pop_camlstack in let instrs_op = [ Wbinary { op = op_code ; src1 ; src2 ; dest } ] in ( state , instrs_op )
let binary_effect lpad state op_code = let src1 = state . accu in let src2 = List . hd state . camlstack in let state = { state with accu = Const 0 } |> pop_camlstack in let instrs_op = [ Wbinaryeffect { op = op_code ; src1 ; src2 } ] in ( state , instrs_op )
let ternary_effect lpad state op_code = let src1 = state . accu in let src2 = List . hd state . camlstack in let src3 = List . hd ( List . tl state . camlstack ) in let state = { state with accu = Const 0 } |> pop_camlstack |> pop_camlstack in let instrs_op = [ Wternaryeffect { op = op_code ; src1 ; src2 ; src3 } ] in ( state , instrs_op )
let global_offset ident = assert ( Ident . global ident ) ; let name = Ident . name ident in int_of_string name
let make_label lpad label = if ISet . mem label lpad . loops then Loop label else Label label
let validate state = let d = state . camldepth in List . iteri ( fun i st -> match st with | RealStack pos -> assert ( pos = ( - d + i ) ) | _ -> assert false ) state . camlstack ; assert ( match state . accu with | RealAccu { no_function = true } -> false | RealAccu _ | Local _ | Invalid -> true | _ -> false ) ; assert ( state . realaccu = ISet . empty )
let update_state_table lpad state label = try let s = Hashtbl . find lpad . state_table label in assert ( s . camldepth = state . camldepth ) with | Not_found -> Hashtbl . add lpad . state_table label state
let norm_accu state = match state . accu with | RealAccu { no_function = true } -> { state with accu = real_accu } | _ -> state
let branch lpad state label = let state = norm_accu state in let instr_br = Wbranch { label = make_label lpad label } in try let dest_state = Hashtbl . find lpad . state_table label in validate dest_state ; let ( state , instrs1 ) = straighten_accu_for_branch lpad state in let ( state , instrs2 ) = straighten_stack lpad state in validate state ; assert ( state . camldepth = dest_state . camldepth ) ; let instrs = if state . accu = dest_state . accu || dest_state . accu = Invalid then instrs1 @ instrs2 @ [ instr_br ] else instrs1 @ instrs2 @ [ Wcopy { src = state . accu ; dest = dest_state . accu } ; instr_br ] in ( state , instrs ) with | Not_found -> let n = try Hashtbl . find lpad . indegree label with Not_found -> 0 in if n < 0 then ( let state , instrs1 = straighten_all lpad state in let state = if n = ( - 2 ) then { state with accu = Invalid } else state in Hashtbl . add lpad . state_table label state ; ( state , instrs1 @ [ instr_br ] ) ) else if n <= 1 then ( let ( state , instrs1 ) = straighten_accu_for_branch lpad state in Hashtbl . add lpad . state_table label state ; ( state , instrs1 @ [ instr_br ] ) ) else ( let ( state , instrs1 ) = straighten_accu_for_branch lpad state in let ( state , instrs2 ) = straighten_stack lpad state in Hashtbl . add lpad . state_table label state ; ( state , instrs1 @ instrs2 @ [ instr_br ] ) )
let transl_instr lpad state instr = match instr with | I . Klabel _ -> assert false | Kconst ( Lambda . Const_base ( Asttypes . Const_int k ) ) -> ( { state with accu = Const k } , [ ] ) | Kconst _ -> assert false | Kacc sp -> let state = if sp < state . camldepth then { state with accu = List . nth state . camlstack sp } else { state with accu = RealStack ( - state . camldepth + sp ) } in ( state , [ ] ) | Kpush -> let state = push_camlstack state . accu state in ( state , [ Wcomment ( sprintf " ( depth =% d ) " state . camldepth ) ] ) | Kpush_retaddr lab -> let state = push_camlstack ( Const 0 ) state in let state = push_camlstack ( Const 0 ) state in let state = push_camlstack ( Const 0 ) state in ( state , [ ] ) | Kpop num -> let state , instrs = pop_real_stack lpad state num in let state = popn_camlstack num state in ( state , instrs @ [ Wcomment ( sprintf " ( depth =% d ) " state . camldepth ) ] ) | Kassign sp -> let cd = state . camldepth in let state , instrs_flush = flush_real_stack_at lpad state ( - cd + sp ) in let state = { state with camlstack = set_camlstack ( - cd + sp ) ( RealStack ( - cd + sp ) ) state } in let instrs_copy = [ Wcopy { src = state . accu ; dest = RealStack ( - cd + sp ) } ] in ( state , instrs_flush @ instrs_copy ) | Kenvacc field -> let state , instrs_flush = flush_accu lpad state in let real_field = lpad . func_offset + field in if real_field < Array . length lpad . environment && lpad . environment . ( real_field ) <> Unknown then ( let efield = lpad . environment . ( real_field ) in let state = { state with accu = TracedGlobal ( Env 0 , [ field ] , efield ) } in ( state , instrs_flush ) ) else let accu = real_accu in let state = { state with accu } in let instrs_op = [ Wenv { field } ] in ( state , instrs_flush @ instrs_op ) | Kgetglobal ident -> let offset = global_offset ident in assert ( offset >= 0 ) ; let state , instrs_flush = flush_accu lpad state in ( match Hashtbl . find lpad . globals_table offset with | initvalue -> let accu = TracedGlobal ( Glb offset , [ ] , initvalue ) in let state = { state with accu } in ( state , instrs_flush ) | exception Not_found -> let accu = real_accu in let state = { state with accu } in let instrs_op = [ Wgetglobal { src = Global offset } ] in ( state , instrs_flush @ instrs_op ) ) | Knegint -> unary_operation lpad state RIntVal Pnegint | Kboolnot -> unary_operation lpad state RIntVal Pboolnot | Koffsetint offset -> let ( state , instrs1 ) = if lpad . avoid_locals then ( state , [ ] ) else localize_accu lpad state RIntVal in let ( state , instrs2 ) = unary_operation lpad state RIntVal ( Poffsetint offset ) in ( state , instrs1 @ instrs2 ) | Koffsetref offset -> unary_effect lpad state ( Poffsetref offset ) | Kisint -> unary_operation lpad state RInt Pisint | Ksetglobal ident -> let offset = global_offset ident in unary_effect lpad state ( Psetglobal ( Global offset ) ) | Kgetfield field -> ( match state . accu with | TracedGlobal ( glb , path , initvalue ) -> let new_path = path @ [ field ] in let new_initvalue = match initvalue with | Block b when field < Array . length b -> b . ( field ) | _ -> Unknown in let accu = TracedGlobal ( glb , new_path , new_initvalue ) in let state = { state with accu ; } in ( state , [ ] ) | _ -> unary_operation lpad state RValue ( Pgetfield field ) ) | Kvectlength -> unary_operation lpad state RIntVal Pvectlength | Kgetpubmet k -> let state = push_camlstack state . accu state in unary_operation lpad state RValue ( Pgetpubmet k ) | Kaddint -> binary_operation lpad state RIntVal Paddint | Ksubint -> binary_operation lpad state RIntVal Psubint | Kmulint -> binary_operation lpad state RIntUnclean Pmulint | Kdivint -> binary_operation lpad state RInt Pdivint | Kmodint -> binary_operation lpad state RInt Pmodint | Kandint -> binary_operation lpad state RIntVal Pandint | Korint -> binary_operation lpad state RIntVal Porint | Kxorint -> binary_operation lpad state RIntVal Pxorint | Klslint -> binary_operation lpad state RIntVal Plslint | Klsrint -> binary_operation lpad state RIntVal Plsrint | Kasrint -> binary_operation lpad state RIntVal Pasrint | Kintcomp cmp -> binary_operation lpad state RInt ( Pintcomp cmp ) | Kisout -> binary_operation lpad state RInt ( Puintcomp Clt ) | Ksetfield field -> binary_effect lpad state ( Psetfield field ) | Ksetfloatfield field -> binary_effect lpad state ( Psetfloatfield field ) | Kgetvectitem -> binary_operation lpad state RValue Pgetvectitem | Kgetstringchar -> binary_operation lpad state RInt Pgetstringchar | Kgetbyteschar -> binary_operation lpad state RInt Pgetbyteschar | Kgetmethod -> let state = push_camlstack ( List . hd state . camlstack ) state in binary_operation lpad state RValue Pgetmethod | Kgetdynmet -> let state = push_camlstack ( List . hd state . camlstack ) state in binary_operation lpad state RValue Pgetdynmet | Ksetvectitem -> ternary_effect lpad state Psetvectitem | Ksetbyteschar -> ternary_effect lpad state Psetbyteschar | Kgetfloatfield field -> let src1 = state . accu in let state , instrs_flush = flush_accu lpad state in let temp_name = new_local lpad RFloat in let temp = Local ( RFloat , temp_name ) in let descr = stack_descr state in let accu = real_accu_no_func in let instrs = instrs_flush @ [ Wunary { op = Pgetfloatfield field ; src1 ; dest = temp ; } ; Walloc { src = temp ; dest = accu ; descr } ] in let state = { state with accu } in ( state , instrs ) | Kmakeblock ( 0 , tag ) -> let state = { state with accu = Atom tag } in ( state , [ ] ) | Kmakeblock ( size , tag ) -> let state , instrs_flush = flush_accu lpad state in let src1 = state . accu in let src = src1 :: list_prefix ( size - 1 ) state . camlstack in let descr = stack_descr state in let accu = real_accu_no_func in let instrs = instrs_flush @ [ Wmakeblock { tag ; src ; descr } ] in let state = { state with accu } |> popn_camlstack ( size - 1 ) in ( state , instrs ) | Kmakefloatblock size -> assert ( size > 0 ) ; let state , instrs_flush = flush_accu lpad state in let src1 = state . accu in let src = src1 :: list_prefix ( size - 1 ) state . camlstack in let descr = stack_descr state in let instrs = instrs_flush @ [ Wmakefloatblock { src ; descr } ] in let accu = real_accu_no_func in let state = { state with accu } |> popn_camlstack ( size - 1 ) in ( state , instrs ) | Kccall ( name , num ) when num <= 5 -> let state , instrs_flush = flush_accu lpad state in let src1 = state . accu in let src = src1 :: list_prefix ( num - 1 ) state . camlstack in let descr = stack_descr state in let instrs = instrs_flush @ [ Wccall { name ; src ; descr } ] in let no_function = Hashtbl . mem Wc_prims . prims_non_func_result name in let state = { state with accu = RealAccu { no_function } } |> popn_camlstack ( num - 1 ) in ( state , instrs ) | Kccall ( name , num ) -> let state , instrs_str = straighten_all lpad state in let descr = stack_descr state in let depth = state . camldepth + 1 in let instrs = instrs_str @ [ Wcopy { src = real_accu ; dest = RealStack ( - depth ) } ; Wccall_vector { name ; numargs = num ; depth ; descr } ] in let no_function = Hashtbl . mem Wc_prims . prims_non_func_result name in let state = { state with accu = RealAccu { no_function } } |> popn_camlstack ( num - 1 ) in ( state , instrs ) | Kbranch label -> branch lpad state label | Kbranchif label -> let ( br_state , instrs ) = branch lpad state label in ( state , [ Wif { src = state . accu ; neg = false ; body = instrs } ] ) | Kbranchifnot label -> let ( br_state , instrs ) = branch lpad state label in ( state , [ Wif { src = state . accu ; neg = true ; body = instrs } ] ) | Kswitch ( labels_int , labels_blk ) -> let state = norm_accu state in let state , instrs_str = straighten_all lpad state in validate state ; Array . iter ( update_state_table lpad state ) labels_int ; Array . iter ( update_state_table lpad state ) labels_blk ; let labels_int = Array . map ( make_label lpad ) labels_int in let labels_blk = Array . map ( make_label lpad ) labels_blk in let src = state . accu in ( state , instrs_str @ [ Wswitch { labels_int ; labels_blk ; src } ] ) | Kapply num when num <= 3 -> let direct_opt = extract_directly_callable_function state . accu in let state = match direct_opt with | Some _ -> { state with accu = real_accu } | None -> state in let state , instrs_str = straighten_all lpad state in let cd = state . camldepth in let instrs_move = enum 0 num |> List . map ( fun k -> Wcopy { src = RealStack ( - cd + k ) ; dest = RealStack ( - cd + k - 3 ) } ) in let depth = cd + 3 in let instr_apply = match direct_opt with | Some ( global , path , funlabel , _ ) -> Wapply_direct { global ; path ; funlabel ; numargs = num ; depth } | None -> Wapply { numargs = num ; depth } in let instrs = instrs_str @ instrs_move @ [ Wcopy { src = Const 0 ; dest = RealStack ( - cd + num - 3 ) } ; Wcopy { src = Const 0 ; dest = RealStack ( - cd + num - 2 ) } ; Wcopy { src = Const 0 ; dest = RealStack ( - cd + num - 1 ) } ; instr_apply ] in let state = state |> popn_camlstack num in ( state , instrs ) | Kapply num -> let direct_opt = extract_directly_callable_function state . accu in let state = match direct_opt with | Some _ -> { state with accu = real_accu } | None -> state in let state , instrs_str = straighten_all lpad state in let depth = state . camldepth in let instr_apply = match direct_opt with | Some ( global , path , funlabel , _ ) -> Wapply_direct { global ; path ; funlabel ; numargs = num ; depth } | None -> Wapply { numargs = num ; depth } in let instrs = instrs_str @ [ instr_apply ] in let state = state |> popn_camlstack ( num + 3 ) in ( state , instrs ) | Kappterm ( num , slots ) -> let state , instrs_accu = straighten_accu lpad state in let state , instrs_stack = straighten_stack_multi lpad state ( enum ( - state . camldepth ) num ) in let instrs = instrs_accu @ instrs_stack @ [ Wappterm { numargs = num ; oldnumargs ( = slots - state . camldepth ) ; depth = state . camldepth } ] in ( state , instrs ) | Kreturn slots -> assert ( state . camldepth + state . arity = slots ) ; ( state , [ Wreturn { src = state . accu ; arity = state . arity } ] ) | Kgrab num -> ( { state with arity = num + 1 } , [ Wgrab { numargs = num } ] ) | Kclosure ( lab , num ) -> let state , instrs_flush = flush_accu lpad state in let src = if num = 0 then [ ] else state . accu :: list_prefix ( num - 1 ) state . camlstack in let descr = stack_descr state in let accu = real_accu in let instrs = instrs_flush @ [ Wclosurerec { src ; dest [ = accu , lab ] ; descr } ] in let state = { state with accu } |> popn_camlstack ( max ( num - 1 ) 0 ) in ( state , instrs ) | Kclosurerec ( funcs , num ) -> let state , instrs_flush = flush_accu lpad state in let descr = stack_descr state in let num_stack = max ( num - 1 ) 0 in let src = if num = 0 then [ ] else state . accu :: list_prefix num_stack state . camlstack in let state = state |> popn_camlstack num_stack in let start_dest = - state . camldepth - 1 in let dest = List . mapi ( fun i lab -> ( RealStack ( start_dest - i ) , lab ) ) funcs in let state = List . fold_left ( fun state ( store , _ ) -> push_camlstack store state ) state dest in let state = { state with accu = Const 0 } in let instrs = instrs_flush @ [ Wclosurerec { src ; dest ; descr } ] in ( state , instrs ) | Koffsetclosure offset -> let state , instrs_flush = flush_accu lpad state in let real_field = lpad . func_offset + offset in let n = Array . length lpad . environment in if n > 0 && real_field < Array . length lpad . environment && ( let _ = assert ( real_field >= 0 ) in true ) && Wc_traceglobals . is_function lpad . environment . ( real_field ) then ( let efield = Wc_traceglobals . FuncInEnv { func_offset = real_field ; env = lpad . environment } in let state = { state with accu = TracedGlobal ( Env offset , [ ] , efield ) } in ( state , instrs_flush ) ) else let accu = real_accu in let state = { state with accu } in let instrs = instrs_flush @ [ Wcopyenv { offset } ] in ( state , instrs ) | Krestart -> ( state , [ ] ) | Kpushtrap _ | Kpoptrap -> ( state , [ ] ) | Kraise kind -> ( state , [ Wraise { src = state . accu ; kind } ] ) | Kstop -> ( state , [ Wstop ] ) | Kcheck_signals | Kevent _ -> ( state , [ ] ) | Kstrictbranchif _ -> assert false | Kstrictbranchifnot _ -> assert false
let local_branch_labels = function | I . Kbranch l -> [ l ] | Kbranchif l -> [ l ] | Kbranchifnot l -> [ l ] | Kswitch ( la1 , la2 ) -> Array . to_list la1 @ Array . to_list la2 | _ -> [ ]
let transl_fblock lpad fblock = let open Wc_control in let indegree = Hashtbl . create 7 in let state_table = Hashtbl . create 7 in let lpad = { lpad with indegree ; state_table } in let incr_indegree lab = let n = try Hashtbl . find indegree lab with Not_found -> 0 in if n >= 0 then Hashtbl . replace indegree lab ( n + 1 ) in let disable_indegree lab = Hashtbl . replace indegree lab ( - 1 ) in let loop_indegree lab = Hashtbl . replace indegree lab ( - 2 ) in let rec count_indegree block = ( match block . loop_label with | Some lab -> loop_indegree lab | None -> ( ) ) ; Array . iter ( function | Block b -> count_indegree b | Trap { catchlabel } -> incr_indegree catchlabel | Simple i -> ( match i with | ( I . Kbranch lab | Kbranchif lab | Kbranchifnot lab ) -> incr_indegree lab | Kswitch ( la1 , la2 ) -> Array . iter disable_indegree la1 ; Array . iter disable_indegree la2 ; | _ -> ( ) ) | Label _ | TryReturn | NextMain _ -> ( ) ) block . instructions in let get_state label = try Hashtbl . find state_table label with Not_found -> empty_state in let rec transl_block block loops = let state = empty_state in let upd_loops = match block . loop_label with | Some lab -> ISet . add lab loops | _ -> loops in let state , instrs_rev = Array . fold_left ( fun ( state , acc ) instr -> match instr with | Label label -> let state = get_state label in let comment = Wcomment ( sprintf " Label % d ( depth =% d ) " label state . camldepth ) in ( state , comment :: acc ) | Simple i -> lpad . loops <- upd_loops ; let next_state , instrs = transl_instr lpad state i in let comment = Wcomment ( " " *** ^ Wc_util . string_of_kinstruction i ) in ( next_state , List . rev_append ( comment :: instrs ) acc ) | Trap { trylabel ; catchlabel ; poplabel } -> let state , instrs_str = straighten_all lpad state in let accu = real_accu in let state = { state with accu } in let instrs = [ Wcomment ( sprintf " *** Trap ( try =% d , catch =% d ) " trylabel catchlabel ) ] @ instrs_str @ [ Wtrap { trylabel ; catchlabel ; depth = state . camldepth } ; ( match poplabel with | None -> Wunreachable | Some pop -> Wbranch { label = Label pop } ) ] in update_state_table lpad state catchlabel ; Option . iter ( update_state_table lpad state ) poplabel ; ( state , List . rev_append instrs acc ) | TryReturn -> let instrs = [ Wcomment " *** TryReturn " ; Wtryreturn { src = state . accu } ] in ( state , List . rev_append instrs acc ) | Block inner -> let instrs = transl_block inner upd_loops in ( state , List . rev_append instrs acc ) | NextMain label -> let instrs = [ Wnextmain { label } ] in ( state , List . rev_append instrs acc ) ) ( state , [ ] ) block . instructions in let instrs = List . rev instrs_rev in match block . loop_label , block . break_label with | Some _ , Some _ -> assert false | Some label , None -> [ Wblock { label = Loop label ; body = instrs } ] | None , Some label -> [ Wblock { label = Label label ; body = instrs } ] | None , None -> instrs in count_indegree fblock . block ; transl_block fblock . block ISet . empty
let string_of_raise_kind = function | Lambda . Raise_regular -> " regular " | Raise_reraise -> " reraise " | Raise_notrace -> " notrace "
let string_of_int_comparison = function | Lambda . Ceq -> " eq " | Cne -> " ne " | Clt -> " lt " | Cgt -> " gt " | Cle -> " le " | Cge -> " ge "
let string_of_kinstruction = function | I . Klabel label -> sprintf " Klabel ( label % d ) " label | Kacc k -> sprintf " Kacc ( % d ) " k | Kenvacc k -> sprintf " Kenvacc ( % d ) " k | Kpush -> " Kpush " | Kpop k -> sprintf " Kpop ( % d ) " k | Kassign k -> sprintf " Kassign ( % d ) " k | Kpush_retaddr label -> sprintf " Kpush_retaddr ( label % d ) " label | Kapply k -> sprintf " Kapply ( % d ) " k | Kappterm ( k1 , k2 ) -> sprintf " Kappterm ( % d , % d ) " k1 k2 | Kreturn k -> sprintf " Kreturn ( % d ) " k | Krestart -> " Krestart " | Kgrab k -> sprintf " Kgrab ( % d ) " k | Kclosure ( label , k ) -> sprintf " Kclosure ( label % d , % d ) " label k | Kclosurerec ( labels , k ) -> let s = List . map ( sprintf " label % d " ) labels |> String . concat " , " in sprintf " Kclosurerec ( % s ; % d ) " s k | Koffsetclosure k -> sprintf " Koffsetclosure ( % d ) " k | Kgetglobal id -> sprintf " Kgetglobal ( % s ) " ( Ident . name id ) | Ksetglobal id -> sprintf " Ksetglobal ( % s ) " ( Ident . name id ) | Kconst ( Lambda . Const_base ( Asttypes . Const_int k ) ) -> sprintf " Kconst ( % d ) " k | Kconst _ -> " Kconst ( undecodable ) " | Kmakeblock ( k1 , k2 ) -> sprintf " Kmakeblock ( % d , % d ) " k1 k2 | Kmakefloatblock k -> sprintf " Kmakefloatblock ( % d ) " k | Kgetfield k -> sprintf " Kgetfield ( % d ) " k | Ksetfield k -> sprintf " Ksetfield ( % d ) " k | Kgetfloatfield k -> sprintf " Kgetfloatfield ( % d ) " k | Ksetfloatfield k -> sprintf " Ksetfloatfield ( % d ) " k | Kvectlength -> " Kvectlength " | Kgetvectitem -> " Kgetvectitem " | Ksetvectitem -> " Ksetvectitem " | Kgetstringchar -> " Kgetstringchar " | Kgetbyteschar -> " Kgetbyteschar " | Ksetbyteschar -> " Ksetbyteschar " | Kbranch label -> sprintf " Kbranch ( label % d ) " label | Kbranchif label -> sprintf " Kbranchif ( label % d ) " label | Kbranchifnot label -> sprintf " Kbranchifnot ( label % d ) " label | Kstrictbranchif _ -> assert false | Kstrictbranchifnot _ -> assert false | Kswitch ( labels1 , labels2 ) -> let s1 = Array . to_list labels1 |> List . map ( sprintf " label % d " ) |> String . concat " , " in let s2 = Array . to_list labels2 |> List . map ( sprintf " label % d " ) |> String . concat " , " in sprintf " Kswitch ( % s ; % s ) " s1 s2 | Kboolnot -> " Kboolnot " | Kpushtrap label -> sprintf " Kpushtrap ( label % d ) " label | Kpoptrap -> " Kpoptrap " | Kraise kind -> sprintf " Kraise ( % s ) " ( string_of_raise_kind kind ) | Kcheck_signals -> " Kcheck_signals " | Kccall ( name , k ) -> sprintf " Kccall ( % s , % d ) " name k | Knegint -> " Knegint " | Kaddint -> " Kaddint " | Ksubint -> " Ksubint " | Kmulint -> " Kmulint " | Kdivint -> " Kdivint " | Kmodint -> " Kmodint " | Kandint -> " Kandint " | Korint -> " Korint " | Kxorint -> " Kxorint " | Klslint -> " Klslint " | Klsrint -> " Klsrint " | Kasrint -> " Kasrint " | Kintcomp cmp -> sprintf " Kintcomp ( % s ) " ( string_of_int_comparison cmp ) | Koffsetint k -> sprintf " Koffsetint ( % d ) " k | Koffsetref k -> sprintf " Koffsetref ( % d ) " k | Kisint -> " Kistin " | Kisout -> " Kisout " | Kgetmethod -> " Kgetmethod " | Kgetpubmet k -> sprintf " Kgetpubmet ( % d ) " k | Kgetdynmet -> " Kgetdynmet " | Kevent _ -> " Kevent " | Kstop -> " Kstop "
let hexdigits = [ | ' 0 ' ; ' 1 ' ; ' 2 ' ; ' 3 ' ; ' 4 ' ; ' 5 ' ; ' 6 ' ; ' 7 ' ; ' 8 ' ; ' 9 ' ; ' a ' ; ' b ' ; ' c ' ; ' d ' ; ' e ' ; ' f ' ] |
let rec enum k n = if n > 0 then k :: enum ( k + 1 ) ( n - 1 ) else [ ]
let rec list_prefix n l = if n = 0 then [ ] else match l with | x :: l ' -> x :: ( list_prefix ( n - 1 ) l ' ) | [ ] -> assert false
let create l = if not ( 0 <= l && l <= Obj . Ephemeron . max_ephe_length ) then invalid_arg ( " Weak . create " ) ; create l
let length x = Obj . size ( Obj . repr x ) - additional_values
let raise_if_invalid_offset e o msg = if not ( 0 <= o && o < length e ) then invalid_arg ( msg )
let set e o x = raise_if_invalid_offset e o " Weak . set " ; match x with | None -> unset e o | Some x -> set ' e o x
let get e o = raise_if_invalid_offset e o " Weak . get " ; get e o
let get_copy e o = raise_if_invalid_offset e o " Weak . get_copy " ; get_copy e o
let check e o = raise_if_invalid_offset e o " Weak . check " ; check e o
let blit e1 o1 e2 o2 l = if l < 0 || o1 < 0 || o1 > length e1 - l || o2 < 0 || o2 > length e2 - l then invalid_arg " Weak . blit " else if l <> 0 then blit e1 o1 e2 o2 l
let fill ar ofs len x = if ofs < 0 || len < 0 || ofs > length ar - len then raise ( Invalid_argument " Weak . fill " ) else begin for i = ofs to ( ofs + len - 1 ) do set ar i x done end