123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342(* Js_of_ocaml compiler
* http://www.ocsigen.org/js_of_ocaml/
* Copyright (C) 2010 Jérôme Vouillon
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)open!StdlibopenCodeletdebug_tc=Debug.find"gen_tc"typeclosure_info={f_name:Code.Var.t;args:Code.Var.tlist;cont:Code.cont;tc:Code.Addr.Set.tCode.Var.Map.t;pos:int}moduleSCC=Strongly_connected_components.Make(Var)letadd_multikvmap=letset=tryVar.Map.findkmapwithNot_found->Addr.Set.emptyinVar.Map.addk(Addr.Set.addvset)mapletreccollect_applypcblocksvisitedtc=ifAddr.Set.mempcvisitedthenvisited,tcelseletvisited=Addr.Set.addpcvisitedinletblock=Addr.Map.findpcblocksinlettc_opt=matchblock.branchwith|Returnx->(matchList.lastblock.bodywith|Some(Let(y,Apply{f;exact=true;_}))whenCode.Var.comparexy=0->Some(add_multifpctc)|None->None|Some_->None)|_->Noneinmatchtc_optwith|Sometc->visited,tc|None->Code.fold_childrenblockspc(funpc(visited,tc)->collect_applypcblocksvisitedtc)(visited,tc)letreccollect_closuresblockslpos=matchlwith|Let(f_name,Closure(args,((pc,_)ascont)))::rem->let_,tc=collect_applypcblocksAddr.Set.emptyVar.Map.emptyinletl,rem=collect_closuresblocksrem(succpos)in{f_name;args;cont;tc;pos}::l,rem|rem->[],remletgroup_closuresclosures_map=letnames=Var.Map.fold(fun_xnames->Var.Set.addx.f_namenames)closures_mapVar.Set.emptyinletgraph=Var.Map.fold(fun_xgraph->letcalls=Var.Map.fold(funx_tc->Var.Set.addxtc)x.tcVar.Set.emptyinVar.Map.addx.f_name(Var.Set.internamescalls)graph)closures_mapVar.Map.emptyinSCC.connected_components_sorted_from_roots_to_leafgraph|>Array.to_listtypew=|Oneof{name:Code.Var.t;code:Code.instr}|Wrapperof{name:Code.Var.t;code:Code.instr;wrapper:Code.instr}moduleTrampoline=structletdirect_call_block~counter~x~f~args=letreturn=Code.Var.forkxinmatchcounterwith|None->{params=[];body=[Let(return,Apply{f;args;exact=true})];branch=Returnreturn}|Somecounter->letcounter_plus_1=Code.Var.forkcounterin{params=[];body=[Let(counter_plus_1,Prim(Extern"%int_add",[Pvcounter;Pc(IntTargetint.one)]));Let(return,Apply{f;args=counter_plus_1::args;exact=true})];branch=Returnreturn}letbounce_call_block~x~f~args=letreturn=Code.Var.forkxinletnew_args=Code.Var.fresh()in{params=[];body=[Let(new_args,Prim(Extern"%js_array",Pc(IntTargetint.zero)::List.mapargs~f:(funx->Pvx)));Let(return,Prim(Extern"caml_trampoline_return",[Pvf;Pvnew_args]))];branch=Returnreturn}letwrapper_blockf~args~counterloc=letresult1=Code.Var.fresh()inletresult2=Code.Var.fresh()inletblock={params=[];body=(matchcounterwith|None->[Eventloc;Let(result1,Apply{f;args;exact=true});EventParse_info.zero;Let(result2,Prim(Extern"caml_trampoline",[Pvresult1]))]|Somecounter->[Eventloc;Let(counter,Constant(IntTargetint.zero));Let(result1,Apply{f;args=counter::args;exact=true});EventParse_info.zero;Let(result2,Prim(Extern"caml_trampoline",[Pvresult1]))]);branch=Returnresult2}inblockletwrapper_closurepcargs=Closure(args,(pc,[]))letffree_pcblocksclosures_mapcomponent=matchcomponentwith|SCC.No_loopid->letci=Var.Map.findidclosures_mapinletinstr=Let(ci.f_name,Closure(ci.args,ci.cont))infree_pc,blocks,[One{name=ci.f_name;code=instr}]|SCC.Has_loopall->ifdebug_tc()then(Format.eprintf"Detect cycles of size (%d).\n%!"(List.lengthall);Format.eprintf"%s\n%!"(String.concat~sep:", "(List.mapall~f:(funx->Var.to_stringx))));lettailcall_max_depth=Config.Param.tailcall_max_depth()inletall=List.mapall~f:(funid->((iftailcall_max_depth=0thenNoneelseSome(Code.Var.fresh_n"counter")),Var.Map.findidclosures_map))inletblocks,free_pc,closures=List.fold_leftall~init:(blocks,free_pc,[])~f:(fun(blocks,free_pc,closures)(counter,ci)->ifdebug_tc()thenFormat.eprintf"Rewriting for %s\n%!"(Var.to_stringci.f_name);letnew_f=Code.Var.forkci.f_nameinletnew_args=List.mapci.args~f:Code.Var.forkinletwrapper_pc=free_pcinletfree_pc=free_pc+1inletnew_counter=Option.mapcounter~f:Code.Var.forkinletstart_loc=letblock=Addr.Map.find(fstci.cont)blocksinmatchblock.bodywith|Eventloc::_->loc|_->Parse_info.zeroinletwrapper_block=wrapper_blocknew_f~args:new_args~counter:new_counterstart_locinletblocks=Addr.Map.addwrapper_pcwrapper_blockblocksinletinstr_wrapper=Let(ci.f_name,wrapper_closurewrapper_pcnew_args)inletinstr_real=matchcounterwith|None->Let(new_f,Closure(ci.args,ci.cont))|Somecounter->Let(new_f,Closure(counter::ci.args,ci.cont))inletcounter_and_pc=List.fold_leftall~init:[]~f:(funacc(counter,ci2)->tryletpcs=Addr.Set.elements(Var.Map.findci.f_nameci2.tc)inList.mappcs~f:(funx->counter,x)@accwithNot_found->acc)inletblocks,free_pc=List.fold_leftcounter_and_pc~init:(blocks,free_pc)~f:(fun(blocks,free_pc)(counter,pc)->ifdebug_tc()thenFormat.eprintf"Rewriting tc in %d\n%!"pc;letblock=Addr.Map.findpcblocksinletdirect_call_pc=free_pcinletbounce_call_pc=free_pc+1inletfree_pc=free_pc+2inmatchList.revblock.bodywith|Let(x,Apply{f;args;exact=true})::rem_rev->assert(Var.equalfci.f_name);letblocks=Addr.Map.adddirect_call_pc(direct_call_block~counter~x~f:new_f~args)blocksinletblocks=Addr.Map.addbounce_call_pc(bounce_call_block~x~f:new_f~args)blocksinletblock=matchcounterwith|None->letbranch=Branch(bounce_call_pc,[])in{blockwithbody=List.revrem_rev;branch}|Somecounter->letdirect=Code.Var.fresh()inletbranch=Cond(direct,(direct_call_pc,[]),(bounce_call_pc,[]))inletlast=Let(direct,Prim(Lt,[Pvcounter;Pc(Int(Targetint.of_int_exntailcall_max_depth))]))in{blockwithbody=List.rev(last::rem_rev);branch}inletblocks=Addr.Map.removepcblocksinAddr.Map.addpcblockblocks,free_pc|_->assertfalse)in(blocks,free_pc,Wrapper{name=ci.f_name;code=instr_real;wrapper=instr_wrapper}::closures))infree_pc,blocks,closuresendletrecrewrite_closuresfree_pcblocksbody:int*_*_list=matchbodywith|Let(_,Closure_)::_->letclosures,rem=collect_closuresblocksbody0inletclosures_map=List.fold_leftclosures~init:Var.Map.empty~f:(funclosures_mapx->Var.Map.addx.f_namexclosures_map)inletcomponents=group_closuresclosures_mapinletfree_pc,blocks,closures=List.fold_leftcomponents~init:(free_pc,blocks,[])~f:(fun(free_pc,blocks,acc)component->letfree_pc,blocks,closures=Trampoline.ffree_pcblocksclosures_mapcomponentinletintrs=closures::accinfree_pc,blocks,intrs)inletclosures=letpos_of_varx=(Var.Map.findxclosures_map).posinletpos=function|One{name;_}->pos_of_varname|Wrapper{name;_}->pos_of_varnameinList.flattenclosures|>List.sort~cmp:(funab->compare(posa)(posb))|>List.concat_map~f:(function|One{code;_}->[code]|Wrapper{code;wrapper;_}->[code;wrapper])inletfree_pc,blocks,rem=rewrite_closuresfree_pcblocksreminfree_pc,blocks,closures@rem|i::rem->letfree_pc,blocks,rem=rewrite_closuresfree_pcblocksreminfree_pc,blocks,i::rem|[]->free_pc,blocks,[]letfp:Code.program=Code.invariantp;letblocks,free_pc=Addr.Map.fold(funpc_(blocks,free_pc)->(* make sure we have the latest version *)letblock=Addr.Map.findpcblocksinletfree_pc,blocks,body=rewrite_closuresfree_pcblocksblock.bodyinAddr.Map.addpc{blockwithbody}blocks,free_pc)p.blocks(p.blocks,p.free_pc)in(* Code.invariant (pc, blocks, free_pc); *)letp={pwithblocks;free_pc}inCode.invariantp;pletfp=assert(matchConfig.effects()with|`Disabled|`Jspi->true|`Cps|`Double_translation->false);letopenConfig.Paraminmatchtailcall_optim()with|TcNone->p|TcTrampoline->lett=Timer.make()inletp'=fpinifDebug.find"times"()thenFormat.eprintf" generate closures: %a@."Timer.printt;p'