12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125(* 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!StdlibopenCodeopenInstrletdebug_parser=Debug.find"parser"letdebug_sourcemap=Debug.find"sourcemap"lettimes=Debug.find"times"typebytecode=stringletpredefined_exceptions=Runtimedef.builtin_exceptions|>Array.to_list|>List.mapi~f:(funiname->i,name)letnew_closure_repr=Ocaml_version.compareOcaml_version.current[4;12]>=0(* Read and manipulate debug section *)moduleDebug:sigtypettypeposition=|Before|Aftervalnames:t->boolvalenabled:t->boolvalis_empty:t->boolvaldbg_section_needed:t->boolvalpropagate:Code.Var.tlist->Code.Var.tlist->unitvalfind:t->Code.Addr.t->(int*Ident.t)list*Env.summaryvalfind_rec:t->Code.Addr.t->(int*Ident.t)listvalfind_loc:t->position:position->Code.Addr.t->Parse_info.toptionvalfind_locs:t->int->(stringoption*Instruct.debug_event)listvalevent_location:position:position->source:stringoption->event:Instruct.debug_event->Parse_info.tvalread_event:paths:stringlist->crcs:(string,stringoption)Hashtbl.t->orig:int->t->Instruct.debug_event->unitvalread:t->crcs:(string*stringoption)list->includes:stringlist->in_channel->unitvalread_event_list:t->crcs:(string*stringoption)list->includes:stringlist->orig:int->in_channel->unitvalcreate:include_cmis:bool->bool->tvalpaths:t->units:StringSet.t->StringSet.tend=structopenInstructtypepath=stringtypeml_unit={module_name:string;crc:stringoption;paths:stringlist;source:pathoption}[@@ocaml.warning"-unused-field"]typeevent_and_source={event:debug_event;source:pathoption}moduleInt_table=Hashtbl.Make(Int)typet={events_by_pc:event_and_sourceInt_table.t;units:(string*stringoption,ml_unit)Hashtbl.t;names:bool;enabled:bool;include_cmis:bool}typeposition=|Before|Afterletnamest=t.namesletenabledt=t.enabledletdbg_section_neededt=t.names||t.enabled||t.include_cmisletrelocate_eventorigev=ev.ev_pos<-(orig+ev.ev_pos)/4letcreate~include_cmisenabled=letnames=enabled||Config.Flag.pretty()in{events_by_pc=Int_table.create17;units=Hashtbl.create17;names;enabled;include_cmis}letis_emptyt=Int_table.lengtht.events_by_pc=0letfind_ml_in_pathspathsname=letuname=String.uncapitalize_asciinameinmatchFs.find_in_pathpaths(uname^".ml")with|Some_asx->x|None->Fs.find_in_pathpaths(name^".ml")letread_event~paths~crcs~orig{events_by_pc;units;names;enabled;include_cmis=_}ev=letpos_fname=matchev.ev_loc.Location.loc_start.Lexing.pos_fnamewith|"_none_"->None|x->Somexinletev_module=ev.ev_moduleinletunit=tryHashtbl.findunits(ev_module,pos_fname)withNot_found->letcrc=tryHashtbl.findcrcsev_modulewithNot_found->Noneinletsource:pathoption=(* First search the source based on [pos_fname] because the
filename of the source might be unreleased to the
module name. (e.g. pos_fname = list.ml, module = Stdlib__list) *)letfrom_pos_fname=matchpos_fnamewith|None->None|Somepos_fname->(matchFs.find_in_pathpathspos_fnamewith|Some_asx->x|None->Fs.find_in_pathpaths(Filename.basenamepos_fname))inmatchfrom_pos_fnamewith|None->find_ml_in_pathspathsev_module|Some_asx->xinletsource=matchsourcewith|None->None|Somesource->Some(Fs.absolute_pathsource)inifdebug_sourcemap()thenFormat.eprintf"module:%s - source:%s - name:%s\n%!"ev_module(matchsourcewith|None->"NONE"|Somex->x)(matchpos_fnamewith|None->"NONE"|Somex->x);letu={module_name=ev_module;crc;source;paths}inHashtbl.addunits(ev_module,pos_fname)u;uinrelocate_eventorigev;ifenabled||namesthenInt_table.addevents_by_pcev.ev_pos{event=ev;source=unit.source};()letread_event_list=letrewrite_pathpath=ifFilename.is_relativepaththenpathelsematchBuild_path_prefix_map.get_build_path_prefix_map()with|Somemap->Build_path_prefix_map.rewrite(Build_path_prefix_map.flipmap)path|None->pathinletread_pathsic:stringlist=List.map(input_valueic)~f:rewrite_pathinfundebug~crcs~includes~origic->letcrcs=lett=Hashtbl.create17inList.itercrcs~f:(fun(m,crc)->Hashtbl.addtmcrc);tinletevl:debug_eventlist=input_valueicinletpaths=read_pathsic@includesinList.iterevl~f:(read_event~paths~crcs~origdebug)letreadt~crcs~includesic=letlen=input_binary_inticinfor_i=0tolen-1doletorig=input_binary_inticinread_event_listt~crcs~includes~origicdoneletfind{events_by_pc;_}pc=trylet{event;_}=Int_table.findevents_by_pcpcinletl=Ident.fold_name(funidentiacc->(event.ev_stacksize-i,ident)::acc)event.ev_compenv.ce_stack[]|>List.sort~cmp:(fun(i,_)(j,_)->compareij)inl,event.ev_typenvwithNot_found->[],Env.Env_emptyletfind_rec{events_by_pc;_}pc=trylet{event;_}=Int_table.findevents_by_pcpcinletenv=event.ev_compenvinletnames=Ident.fold_name(funidentiacc->((ifnew_closure_reprtheni/3elsei/2),ident)::acc)env.ce_rec[]inList.sortnames~cmp:(fun(i,_)(j,_)->compareij)withNot_found->[][@@ifocaml_version<(5,2,0)]letfind_rec{events_by_pc;_}pc=trylet{event;_}=Int_table.findevents_by_pcpcinletenv=event.ev_compenvinletnames=matchenv.ce_closurewith|Not_in_closure->raiseNot_found|In_closure{entries;_}->Ident.fold_name(funidententacc->matchentwith|Functioni->(i/3,ident)::acc|Free_variable_->acc)entries[]inList.sortnames~cmp:(fun(i,_)(j,_)->compareij)withNot_found->[][@@ifocaml_version>=(5,2,0)]letdummy_location(loc:Location.t)=loc.loc_start.pos_cnum=-1||loc.loc_end.pos_cnum=-1(* We can have several events at the same location when a function
application is followed by a branch target, typically due to some
code like [if ... then f(); ...] : the event after the function
application, and the event at the beginning of the continuation.
Both events are interesting. They are returned by this function
in the expected order: first after the function call, then before
the continuation. *)letfind_locs{events_by_pc;_}pc=List.filter_map(Int_table.find_allevents_by_pcpc)~f:(fun{event;source}->ifdummy_locationevent.ev_locthenNoneelseSome(source,event))letevent_location~position~source~event=letpos=matchpositionwith|After->event.ev_loc.Location.loc_end|Before->event.ev_loc.Location.loc_startinParse_info.t_of_position~src:sourceposletfind_loct~positionpc=matchfind_locstpcwith|[]->None|(source,event)::_->Some(event_location~position~source~event)letrecpropagatel1l2=matchl1,l2with|v1::r1,v2::r2->Var.propagate_namev1v2;propagater1r2|[],[]->()|_->assertfalseletpathst~units=letpaths=Hashtbl.fold(fun_uacc->ifStringSet.memu.module_nameunitsthenu.paths::accelseacc)t.units[]inStringSet.of_list(List.concatpaths)end(* Block analysis *)(* Detect each block *)moduleBlocks:sigtypetvalanalyse:bytecode->tvalnext:t->int->intvalis_empty:t->boolend=structtypet=intarrayletaddblockspc=Addr.Set.addpcblocksletrecscanblockscodepclen=ifpc<lenthenmatch(get_instr_exncodepc).kindwith|KNullary->scanblockscode(pc+1)len|KUnary->scanblockscode(pc+2)len|KBinary->scanblockscode(pc+3)len|KNullaryCall->scanblockscode(pc+1)len|KUnaryCall->scanblockscode(pc+2)len|KBinaryCall->scanblockscode(pc+3)len|KJump->letoffset=getscode(pc+1)inletblocks=Addr.Set.add(pc+offset+1)blocksinscanblockscode(pc+2)len|KCond_jump->letoffset=getscode(pc+1)inletblocks=Addr.Set.add(pc+offset+1)blocksinscanblockscode(pc+2)len|KCmp_jump->letoffset=getscode(pc+2)inletblocks=Addr.Set.add(pc+offset+2)blocksinscanblockscode(pc+3)len|KSwitch->letsz=getucode(pc+1)inletblocks=refblocksinfori=0to(szland0xffff)+(szlsr16)-1doletoffset=getscode(pc+2+i)inblocks:=Addr.Set.add(pc+offset+2)!blocksdone;scan!blockscode(pc+2+(szland0xffff)+(szlsr16))len|KClosurerec->letnfuncs=getucode(pc+1)inscanblockscode(pc+nfuncs+3)len|KClosure->scanblockscode(pc+3)len|KStopn->scanblockscode(pc+n+1)len|K_will_not_happen->assertfalseelse(assert(pc=len);blocks)(* invariant: a.(i) <= x < a.(j) *)letrecfindaijx=assert(i<j);ifi+1=jthena.(j)elseletk=(i+j)/2inifa.(k)<=xthenfindakjxelsefindaikxletnextblockspc=findblocks0(Array.lengthblocks-1)pcletis_emptyx=Array.lengthx<=1letanalysecode=letblocks=Addr.Set.emptyinletlen=String.lengthcode/4inletblocks=addblocks0inletblocks=addblocksleninletblocks=scanblockscode0leninArray.of_list(Addr.Set.elementsblocks)end(* Parse constants *)moduleConstants:sigvalparse:Obj.t->Code.constantvalinlined:Code.constant->boolend=struct(* In order to check that two custom objects share the same kind, we
compare their identifier. The identifier is currently extracted
from the marshaled value. *)letident_of_customx=(* Make sure tags are equal to custom_tag.
Note that in javascript [0l] and [0n] are not encoded as custom blocks. *)ifObj.tagx<>Obj.custom_tagthenNoneelsetryletbin=Marshal.to_stringx[]inmatchChar.codebin.[20]with|0x12|0x18|0x19->letlast=String.index_frombin21'\000'inletname=String.subbin~pos:21~len:(last-21)inSomename|_->assertfalsewith_->assertfalseletsame_identxy=matchywith|Somey->String.equalxy|None->falseletident_32=ident_of_custom(Obj.repr0l)letident_64=ident_of_custom(Obj.repr0L)letident_native=ident_of_custom(Obj.repr0n)letrecparsex=ifObj.is_blockxthenlettag=Obj.tagxiniftag=Obj.string_tagthenString(Obj.magicx:string)elseiftag=Obj.double_tagthenFloat(Obj.magicx:float)elseiftag=Obj.double_array_tagthenFloat_array(Array.init(Obj.sizex)~f:(funi->Obj.double_fieldxi))elseiftag=Obj.custom_tagthenmatchident_of_customxwith|Somenamewhensame_identnameident_32->(leti:int32=Obj.magicxinmatchConfig.target()with|`JavaScript->Int(Targetint.of_int32_warning_on_overflowi)|`Wasm->Int32i)|Somenamewhensame_identnameident_native->(leti:nativeint=Obj.magicxinmatchConfig.target()with|`JavaScript->Int(Targetint.of_nativeint_warning_on_overflowi)|`Wasm->NativeInt(Int32.of_nativeint_warning_on_overflowi))|Somenamewhensame_identnameident_64->Int64(Obj.magicx:int64)|Somename->failwith(Printf.sprintf"parse_bytecode: Don't know what to do with custom block (%s)"name)|None->assertfalseelseiftag<Obj.no_scan_tagthenTuple(tag,Array.init(Obj.sizex)~f:(funi->parse(Obj.fieldxi)),Unknown)elseassertfalseelseleti:int=Obj.magicxinInt(Targetint.of_int_warning_on_overflowi)letinlined=function|String_|NativeString_->false|Float_->true|Float_array_->false|Int64_->false|Tuple_->false|Int_->true|Int32_|NativeInt_->falseendletconst32i=Constant(Int(Targetint.of_int32_exni))letconsti=Constant(Int(Targetint.of_int_exni))(* Globals *)typeglobals={mutablevars:Var.toptionarray;mutableis_const:boolarray;mutableis_exported:boolarray;mutablenamed_value:stringoptionarray;mutableoverride:(Var.t->Code.instrlist->Var.t*Code.instrlist)optionarray;constants:Code.constantarray;primitives:stringarray}letmake_globalssizeconstantsprimitives={vars=Array.makesizeNone;is_const=Array.makesizefalse;is_exported=Array.makesizefalse;named_value=Array.makesizeNone;override=Array.makesizeNone;constants;primitives}letresize_arrayalendef=letb=Array.makelendefinArray.blit~src:a~src_pos:0~dst:b~dst_pos:0~len:(Array.lengtha);bletresize_globalsgsize=g.vars<-resize_arrayg.varssizeNone;g.is_const<-resize_arrayg.is_constsizefalse;g.is_exported<-resize_arrayg.is_exportedsizetrue;g.named_value<-resize_arrayg.named_valuesizeNone;g.override<-resize_arrayg.overridesizeNone(* State of the VM *)moduleState=structtypeelt=|VarofVar.t|Dummyofstring|Unsetletelt_to_vare=matchewith|Varx->x|_->assertfalseletprint_eltfv=matchvwith|Varx->Format.fprintff"%a"Var.printx|Dummy_->Format.fprintff"٭"|Unset->Format.fprintff"∅"typehandler={stack:eltlist}typet={accu:elt;stack:eltlist;env:eltarray;env_offset:int;handlers:handlerlist;globals:globals}letfresh_varstate=letx=Var.fresh()inx,{statewithaccu=Varx}letglobalsst=st.globalsletsize_globalsstsize=ifsize>Array.lengthst.globals.varsthenresize_globalsst.globalssizeletreclist_startnl=ifn=0then[]elsematchlwith|[]->assertfalse|v::r->v::list_start(n-1)rletrecst_popnst=ifn=0thenstelsematchstwith|[]->assertfalse|_::r->st_pop(n-1)rletpushst={stwithstack=st.accu::st.stack}letpopnst={stwithstack=st_popnst.stack}letaccnst={stwithaccu=List.nthst.stackn}letenv_accnst={stwithaccu=st.env.(st.env_offset+n)}letaccust=elt_to_varst.acculetstack_varsst=List.fold_left(st.accu::st.stack)~init:[]~f:(funle->matchewith|Varx->x::l|Dummy_|Unset->l)letset_accustx={stwithaccu=Varx}letclear_accust={stwithaccu=Unset}letpeeknst=elt_to_var(List.nthst.stackn)letgrabnst=List.map(list_startnst.stack)~f:elt_to_var,popnstletrecst_assignsnx=matchswith|[]->assertfalse|y::rem->ifn=0thenx::remelsey::st_assignrem(n-1)xletassignstn={stwithstack=st_assignst.stacknst.accu}letstart_functionstateenvoffset={statewithaccu=Unset;stack=[];env;env_offset=offset;handlers=[]}letstart_block_current_pcstate=letstack=List.fold_rightstate.stack~init:[]~f:(funestack->matchewith|Dummyx->Dummyx::stack|Unset->Unset::stack|Varx->lety=Var.forkxinVary::stack)inletstate={statewithstack}inmatchstate.accuwith|Dummy_|Unset->state|Varx->lety,state=fresh_varstateinVar.propagate_namexy;stateletpush_handlerstate={statewithhandlers={stack=state.stack}::state.handlers}letpop_handlerstate={statewithhandlers=List.tlstate.handlers}letinitialg={accu=Unset;stack=[];env=[||];env_offset=0;handlers=[];globals=g}letrecprint_stackfl=matchlwith|[]->()|v::r->Format.fprintff"%a %a"print_eltvprint_stackrletprint_envfe=Array.iterie~f:(funiv->ifi>0thenFormat.fprintff" ";Format.fprintff"%a"print_eltv)letprintst=Format.eprintf"{ %a | %a | (%d) %a }@."print_eltst.accuprint_stackst.stackst.env_offsetprint_envst.envletrecname_recdebugilssummary=matchl,swith|[],_->()|(j,ident)::lrem,Varv::sremwheni=j->Var.namev(Ident.nameident);name_recdebug(i+1)lremsremsummary|(j,_)::_,_::sremwheni<j->name_recdebug(i+1)lsremsummary|_->assertfalseletname_varsstdebugpc=ifDebug.namesdebugthenletl,summary=Debug.finddebugpcinname_recdebug0lst.stacksummaryletrecmake_stackistate=ifi=0then[],stateelseletx,state=fresh_varstateinletparams,state=make_stack(predi)(pushstate)inifdebug_parser()thenifi>1thenFormat.printf", ";ifdebug_parser()thenFormat.printf"%a"Var.printx;x::params,stateendletprimitive_namestatei=letg=State.globalsstateinassert(i>=0&&i<=Array.lengthg.primitives);letprim=g.primitives.(i)inPrimitive.add_externalprim;primletaccess_globalgi=matchg.vars.(i)with|Somex->x|None->g.is_const.(i)<-true;letx=Var.fresh()ing.vars.(i)<-Somex;xletregister_global?(force=false)girem=matchg.is_exported.(i),force,Config.target()with|true,_,`Wasm->(* Register a compilation unit (Wasm) *)assert(notforce);letname=matchg.named_value.(i)with|None->assertfalse|Somename->nameinCode.Var.name(access_globalgi)name;Let(Var.fresh(),Prim(Extern"caml_set_global",[Pc(Stringname);Pv(access_globalgi)]))::rem|true,_,(`JavaScriptastarget)|false,true,((`Wasm|`JavaScript)astarget)->(* Register an exception (if force = true), or a compilation unit
(Javascript) *)letargs=matchg.named_value.(i)with|None->[]|Somename->Code.Var.name(access_globalgi)name;[Pc(matchtargetwith|`JavaScript->NativeString(Native_string.of_stringname)|`Wasm->Stringname)]inLet(Var.fresh(),Prim(Extern"caml_register_global",Pc(Int(Targetint.of_int_exni))::Pv(access_globalgi)::args))::rem|false,false,(`JavaScript|`Wasm)->remletget_globalstateinstrsi=State.size_globalsstate(i+1);letg=State.globalsstateinmatchg.vars.(i)with|Somex->(* Registered global *)ifdebug_parser()thenFormat.printf"(global access %a)@."Var.printx;x,State.set_accustatex,instrs|None->(ifi<Array.lengthg.constants&&Constants.inlinedg.constants.(i)then(* Inlined constant *)letx,state=State.fresh_varstateinletcst=g.constants.(i)inx,state,Let(x,Constantcst)::instrselsematchi<Array.lengthg.constants,Config.target()with|true,_|false,`JavaScript->(* Non-inlined constant, and reference to another compilation
units in case of separate compilation (JavaScript).
Some code is generated in a prelude to store the relevant
module in variable [x]. *)g.is_const.(i)<-true;letx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = CONST(%d)@."Var.printxi;g.vars.(i)<-Somex;x,state,instrs|false,`Wasm->((* Reference to another compilation units in case of separate
compilation (Wasm).
The toplevel module is available in an imported global
variables. *)matchg.named_value.(i)with|None->assertfalse|Somename->letx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = get_global(%s)@."Var.printxname;(x,state,Let(x,Prim(Extern"caml_get_global",[Pc(Stringname)]))::instrs)))lettagged_blocks=refAddr.Map.emptyletcompiled_blocks:(_*instrlist*last)Addr.Map.tref=refAddr.Map.emptyletmethod_cache_id=ref1letclo_offset_3=ifnew_closure_reprthen3else2typecompile_info={blocks:Blocks.t;code:string;limit:int;debug:Debug.t}letstring_of_addrdebug_dataaddr=List.map(Debug.find_locsdebug_dataaddr)~f:(fun(src,{Instruct.ev_loc=loc;ev_kind=kind;_})->letpos(p:Lexing.position)=Printf.sprintf"%d:%d"p.pos_lnum(p.pos_cnum-p.pos_bol)inletfile=matchsrcwith|None->"<unknown>"|Somefile->fileinletkind=matchkindwith|Event_before->"(before)"|Event_after_->"(after)"|Event_pseudo->"(pseudo)"inPrintf.sprintf"%s:%s-%s %s"file(posloc.loc_start)(posloc.loc_end)kind)letreccompile_blockblocksdebug_datacodepcstate:unit=matchAddr.Map.find_optpc!tagged_blockswith|Someold_state->((* Check that the shape of the stack is compatible with the one used to compile the block *)letreccheck(xs:State.eltlist)(ys:State.eltlist)=matchxs,yswith|Var_::xs,Var_::ys->checkxsys|Dummy_::xs,Dummy_::ys->checkxsys|Unset::_,_->assertfalse|_,Unset::_->assertfalse|[],[]->()|Var_::_,Dummy_::_->assertfalse|Dummy_::_,Var_::_->assertfalse|_::_,[]->assertfalse|[],_::_->assertfalseincheckold_state.State.stackstate.State.stack;matchold_state.State.accu,state.State.accuwith|Dummy_,Dummy_->()|Var_,Var_->()|Unset,Unset->()|Var_,Dummy_->assertfalse|Dummy_,Var_->assertfalse|Unset,_->assertfalse|_,Unset->assertfalse)|None->(letlimit=Blocks.nextblockspcinassert(limit>pc);ifdebug_parser()thenFormat.eprintf"Compiling from %d to %d@."pc(limit-1);letstate=State.start_blockpcstateintagged_blocks:=Addr.Map.addpcstate!tagged_blocks;letinstr,last,state'=compile{blocks;code;limit;debug=debug_data}pcstate[]inassert(not(Addr.Map.mempc!compiled_blocks));(* When jumping to a block that was already visited and the
[accu] was [Unset] for that block, we make the current accu
[Unset] *)letadjust_statepc=matchstate',Addr.Map.find_optpc!tagged_blockswith|_,None->state'|{State.accu=Var_;_},Some{State.accu=Unset;_}->State.clear_accustate'|_,_->state'inletmk_contpc=letstate=adjust_statepcinpc,State.stack_varsstateinletlast=matchlastwith|Branch(pc,_)->Branch(mk_contpc)|Cond(x,(pc1,_),(pc2,_))->Cond(x,mk_contpc1,mk_contpc2)|Poptrap(pc,_)->Poptrap(mk_contpc)|Switch(x,a)->Switch(x,Array.mapa~f:(fun(pc,_)->mk_contpc))|Raise_|Return_|Stop->last|Pushtrap_->assertfalseincompiled_blocks:=Addr.Map.addpc(state,List.revinstr,last)!compiled_blocks;matchlastwith|Branch(pc',_)->compile_blockblocksdebug_datacodepc'(adjust_statepc')|Cond(_,(pc1,_),(pc2,_))->compile_blockblocksdebug_datacodepc1(adjust_statepc1);compile_blockblocksdebug_datacodepc2(adjust_statepc2)|Poptrap(_,_)->()|Switch(_,_)->()|Raise_|Return_|Stop->()|Pushtrap_->assertfalse)andcompileinfospcstate(instrs:instrlist)=ifdebug_parser()thenState.printstate;assert(pc<=infos.limit);ifdebug_parser()thenList.iter(string_of_addrinfos.debugpc)~f:(funs->Format.eprintf"@@@@ %s @@@@@."s);letinstrs=letpush_eventpositionsourceeventinstrs=matchinstrswith|Event_::instrs|instrs->Event(Debug.event_location~position~source~event)::instrsinList.fold_left(Debug.find_locsinfos.debugpc)~init:instrs~f:(funinstrs(source,event)->matchevent,instrswith|{Instruct.ev_kind=Event_pseudo;ev_info=Event_other;_},_->(* Ignore allocation events (not very interesting) *)ifdebug_parser()thenFormat.eprintf"Ignored allocation event@.";instrs|({ev_kind=Event_pseudo|Event_after_;ev_info=Event_return_;_},(Let(_,(Apply_|Prim_))asi)::rem)->(* Event after a call. If it is followed by another event,
it may have been weaken to a pseudo-event but was kept
for stack traces *)ifdebug_parser()thenFormat.eprintf"Added event across call@.";push_eventAftersourceevent(i::push_eventBeforesourceeventrem)|{ev_kind=Event_pseudo;ev_info=Event_function;_},[]->(* At beginning of function *)ifdebug_parser()thenFormat.eprintf"Added event at function start@.";push_eventBeforesourceeventinstrs|{ev_kind=Event_after_|Event_pseudo;ev_info=Event_return_;_},_->ifdebug_parser()thenFormat.eprintf"Ignored useless event (beginning of a block after a call)@.";instrs|{ev_kind=Event_after_;ev_info=Event_other;_},_->ifdebug_parser()thenFormat.eprintf"Ignored useless event (before a raise)@.";(* We already have an event for the exception. The
compiler add these events for stack traces. *)instrs|{ev_kind=Event_before;ev_info=Event_other;_},_|{ev_kind=Event_before|Event_pseudo;ev_info=Event_function;_},_->ifdebug_parser()thenFormat.eprintf"added event@.";push_eventBeforesourceeventinstrs|{ev_kind=Event_after_;ev_info=Event_function;_},_|{ev_kind=Event_before;ev_info=Event_return_;_},_->(* Nonsensical events *)assertfalse)inifpc=infos.limitthenif(* stop if we reach end_of_code (ie when compiling cmo) *)pc=String.lengthinfos.code/4then(ifdebug_parser()thenFormat.eprintf"Stop@.";instrs,Stop,state)else(State.name_varsstateinfos.debugpc;ifdebug_parser()thenFormat.eprintf"Branch %d (%a) @."pcPrint.var_list(State.stack_varsstate);instrs,Branch(pc,[]),state)else(ifdebug_parser()thenFormat.eprintf"%4d "pc;State.name_varsstateinfos.debugpc;letcode=infos.codeinletinstr=get_instr_exncodepcinifdebug_parser()thenFormat.eprintf"%08x %s@."instr.opcodeinstr.name;matchinstr.Instr.codewith|ACC0->compileinfos(pc+1)(State.acc0state)instrs|ACC1->compileinfos(pc+1)(State.acc1state)instrs|ACC2->compileinfos(pc+1)(State.acc2state)instrs|ACC3->compileinfos(pc+1)(State.acc3state)instrs|ACC4->compileinfos(pc+1)(State.acc4state)instrs|ACC5->compileinfos(pc+1)(State.acc5state)instrs|ACC6->compileinfos(pc+1)(State.acc6state)instrs|ACC7->compileinfos(pc+1)(State.acc7state)instrs|ACC->letn=getucode(pc+1)incompileinfos(pc+2)(State.accnstate)instrs|PUSH->compileinfos(pc+1)(State.pushstate)instrs|PUSHACC0->compileinfos(pc+1)(State.acc0(State.pushstate))instrs|PUSHACC1->compileinfos(pc+1)(State.acc1(State.pushstate))instrs|PUSHACC2->compileinfos(pc+1)(State.acc2(State.pushstate))instrs|PUSHACC3->compileinfos(pc+1)(State.acc3(State.pushstate))instrs|PUSHACC4->compileinfos(pc+1)(State.acc4(State.pushstate))instrs|PUSHACC5->compileinfos(pc+1)(State.acc5(State.pushstate))instrs|PUSHACC6->compileinfos(pc+1)(State.acc6(State.pushstate))instrs|PUSHACC7->compileinfos(pc+1)(State.acc7(State.pushstate))instrs|PUSHACC->letn=getucode(pc+1)incompileinfos(pc+2)(State.accn(State.pushstate))instrs|POP->letn=getucode(pc+1)incompileinfos(pc+2)(State.popnstate)instrs|ASSIGN->letn=getucode(pc+1)inletaccu=State.accustateinletstate=State.assignstateninletstack_size=List.lengthstate.stackinletx,state=State.fresh_varstateinletinstrs=(* If the assigned variable is used in an exception handler,
we register that from now on the parameter [dest] should
be bound to the value of [accu] when entering the
exception handler.
For the optimization phases, [Assign (dest, acccu)] is
interpreted as: [accu] is a possible value for parameter
[dest]. For code generation, this is implemented as an
assignment.
For this to make sense, the intermediate code generated
for [PUSHTRAP] is such that [dest] is in scope at this
point but is only used in the exception handler.
*)List.fold_leftstate.handlers~init:(Let(x,const0)::instrs)~f:(funacc(handler:State.handler)->lethandler_stack_size=List.lengthhandler.stackinletdiff=stack_size-handler_stack_sizeinifn>=diffthenletdest=State.elt_to_var(List.nthhandler.stack(n-diff))inAssign(dest,accu)::accelseacc)inifdebug_parser()thenFormat.printf"%a = 0@."Var.printx;compileinfos(pc+2)stateinstrs|ENVACC1->compileinfos(pc+1)(State.env_acc1state)instrs|ENVACC2->compileinfos(pc+1)(State.env_acc2state)instrs|ENVACC3->compileinfos(pc+1)(State.env_acc3state)instrs|ENVACC4->compileinfos(pc+1)(State.env_acc4state)instrs|ENVACC->letn=getucode(pc+1)incompileinfos(pc+2)(State.env_accnstate)instrs|PUSHENVACC1->compileinfos(pc+1)(State.env_acc1(State.pushstate))instrs|PUSHENVACC2->compileinfos(pc+1)(State.env_acc2(State.pushstate))instrs|PUSHENVACC3->compileinfos(pc+1)(State.env_acc3(State.pushstate))instrs|PUSHENVACC4->compileinfos(pc+1)(State.env_acc4(State.pushstate))instrs|PUSHENVACC->letn=getucode(pc+1)incompileinfos(pc+2)(State.env_accn(State.pushstate))instrs|PUSH_RETADDR->compileinfos(pc+2){statewithState.stack=(* See interp.c *)State.Dummy"push_retaddr(retaddr)"::State.Dummy"push_retaddr(env)"::State.Dummy"push_retaddr(extra_args)"::state.State.stack}instrs|APPLY->letn=getucode(pc+1)inletf=State.accustateinletx,state=State.fresh_varstateinletargs,state=State.grabnstateinifdebug_parser()then(Format.printf"%a = %a("Var.printxVar.printf;fori=0ton-1doifi>0thenFormat.printf", ";Format.printf"%a"Var.print(List.nthargsi)done;Format.printf")@.");compileinfos(pc+2)(State.pop3state)(Let(x,Apply{f;args;exact=false})::instrs)|APPLY1->letf=State.accustateinletx,state=State.fresh_varstateinlety=State.peek0stateinifdebug_parser()thenFormat.printf"%a = %a(%a)@."Var.printxVar.printfVar.printy;compileinfos(pc+1)(State.pop1state)(Let(x,Apply{f;args=[y];exact=false})::instrs)|APPLY2->letf=State.accustateinletx,state=State.fresh_varstateinlety=State.peek0stateinletz=State.peek1stateinifdebug_parser()thenFormat.printf"%a = %a(%a, %a)@."Var.printxVar.printfVar.printyVar.printz;compileinfos(pc+1)(State.pop2state)(Let(x,Apply{f;args=[y;z];exact=false})::instrs)|APPLY3->letf=State.accustateinletx,state=State.fresh_varstateinlety=State.peek0stateinletz=State.peek1stateinlett=State.peek2stateinifdebug_parser()thenFormat.printf"%a = %a(%a, %a, %a)@."Var.printxVar.printfVar.printyVar.printzVar.printt;compileinfos(pc+1)(State.pop3state)(Let(x,Apply{f;args=[y;z;t];exact=false})::instrs)|APPTERM->letn=getucode(pc+1)inletf=State.accustateinletl,state=State.grabnstateinifdebug_parser()then(Format.printf"return %a("Var.printf;fori=0ton-1doifi>0thenFormat.printf", ";Format.printf"%a"Var.print(List.nthli)done;Format.printf")@.");letx,state=State.fresh_varstateinLet(x,Apply{f;args=l;exact=false})::instrs,Returnx,state|APPTERM1->letf=State.accustateinletx=State.peek0stateinifdebug_parser()thenFormat.printf"return %a(%a)@."Var.printfVar.printx;lety,state=State.fresh_varstateinLet(y,Apply{f;args=[x];exact=false})::instrs,Returny,state|APPTERM2->letf=State.accustateinletx=State.peek0stateinlety=State.peek1stateinifdebug_parser()thenFormat.printf"return %a(%a, %a)@."Var.printfVar.printxVar.printy;letz,state=State.fresh_varstateinLet(z,Apply{f;args=[x;y];exact=false})::instrs,Returnz,state|APPTERM3->letf=State.accustateinletx=State.peek0stateinlety=State.peek1stateinletz=State.peek2stateinifdebug_parser()thenFormat.printf"return %a(%a, %a, %a)@."Var.printfVar.printxVar.printyVar.printz;lett,state=State.fresh_varstateinLet(t,Apply{f;args=[x;y;z];exact=false})::instrs,Returnt,state|RETURN->letx=State.accustateinifdebug_parser()thenFormat.printf"return %a@."Var.printx;instrs,Returnx,state|RESTART->assertfalse|GRAB->assertfalse|CLOSURE->letnvars=getucode(pc+1)inletaddr=pc+getscode(pc+2)+2inletstate=ifnvars>0thenState.pushstateelsestateinletvals,state=State.grabnvarsstateinletx,state=State.fresh_varstateinletenv=List.mapvals~f:(funx->State.Varx)inletenv=letcode=State.Dummy"closure(code)"inletclosure_info=State.Dummy"closure(info)"inifnew_closure_reprthencode::closure_info::envelsecode::envinletenv=Array.of_listenvinifdebug_parser()thenFormat.printf"fun %a ("Var.printx;letnparams,addr=match(get_instr_exncodeaddr).Instr.codewith|GRAB->getucode(addr+1)+1,addr+2|_->1,addrinletstate'=State.start_functionstateenv0inletparams,state'=State.make_stacknparamsstate'inifdebug_parser()thenFormat.printf") {@.";letstate'=State.clear_accustate'incompile_blockinfos.blocksinfos.debugcodeaddrstate';ifdebug_parser()thenFormat.printf"}@.";letargs=State.stack_varsstate'inletstate'',_,_=Addr.Map.findaddr!compiled_blocksinDebug.propagate(State.stack_varsstate'')args;compileinfos(pc+3)state(Let(x,Closure(List.revparams,(addr,args)))::instrs)|CLOSUREREC->letnfuncs=getucode(pc+1)inletnvars=getucode(pc+2)inletstate=ifnvars>0thenState.pushstateelsestateinletvals,state=State.grabnvarsstateinletstate=refstateinletvars=ref[]inletrec_names=ref(Debug.find_recinfos.debug(pc+3+getscode(pc+3)))infori=0tonfuncs-1doletx,st=State.fresh_var!statein(match!rec_nameswith|(j,ident)::rest->assert(j=i);Var.namex(Ident.nameident);rec_names:=rest|[]->());vars:=(i,x)::!vars;state:=State.pushstdone;letenv=ref(List.mapvals~f:(funx->State.Varx))inList.iter!vars~f:(fun(i,x)->letcode=State.Varxinletclosure_info=State.Dummy"closurerec(info)"inifnew_closure_reprthenenv:=code::closure_info::!envelseenv:=code::!env;ifi>0thenletinfix_tag=State.Dummy"closurerec(infix_tag)"inenv:=infix_tag::!env);letenv=Array.of_list!envinletstate=!stateinletinstrs=List.fold_left(List.rev!vars)~init:instrs~f:(funinstr(i,x)->letaddr=pc+3+getscode(pc+3+i)inifdebug_parser()thenFormat.printf"fun %a ("Var.printx;letnparams,addr=match(get_instr_exncodeaddr).Instr.codewith|GRAB->getucode(addr+1)+1,addr+2|_->1,addrinletoffset=i*clo_offset_3inletstate'=State.start_functionstateenvoffsetinletparams,state'=State.make_stacknparamsstate'inifdebug_parser()thenFormat.printf") {@.";letstate'=State.clear_accustate'incompile_blockinfos.blocksinfos.debugcodeaddrstate';ifdebug_parser()thenFormat.printf"}@.";letargs=State.stack_varsstate'inletstate'',_,_=Addr.Map.findaddr!compiled_blocksinDebug.propagate(State.stack_varsstate'')args;Let(x,Closure(List.revparams,(addr,args)))::instr)incompileinfos(pc+3+nfuncs)(State.acc(nfuncs-1)state)instrs|OFFSETCLOSUREM3->compileinfos(pc+1)(State.env_acc(-clo_offset_3)state)instrs|OFFSETCLOSURE0->compileinfos(pc+1)(State.env_acc0state)instrs|OFFSETCLOSURE3->compileinfos(pc+1)(State.env_accclo_offset_3state)instrs|OFFSETCLOSURE->letn=getscode(pc+1)incompileinfos(pc+2)(State.env_accnstate)instrs|PUSHOFFSETCLOSUREM3->letstate=State.pushstateincompileinfos(pc+1)(State.env_acc(-clo_offset_3)state)instrs|PUSHOFFSETCLOSURE0->letstate=State.pushstateincompileinfos(pc+1)(State.env_acc0state)instrs|PUSHOFFSETCLOSURE3->letstate=State.pushstateincompileinfos(pc+1)(State.env_accclo_offset_3state)instrs|PUSHOFFSETCLOSURE->letstate=State.pushstateinletn=getscode(pc+1)incompileinfos(pc+2)(State.env_accnstate)instrs|GETGLOBAL->leti=getucode(pc+1)inlet_,state,instrs=get_globalstateinstrsiincompileinfos(pc+2)stateinstrs|PUSHGETGLOBAL->letstate=State.pushstateinleti=getucode(pc+1)inlet_,state,instrs=get_globalstateinstrsiincompileinfos(pc+2)stateinstrs|GETGLOBALFIELD->leti=getucode(pc+1)inletx,state,instrs=get_globalstateinstrsiinletj=getucode(pc+2)inlety,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a[%d]@."Var.printyVar.printxj;compileinfos(pc+3)state(Let(y,Field(x,j,Non_float))::instrs)|PUSHGETGLOBALFIELD->letstate=State.pushstateinleti=getucode(pc+1)inletx,state,instrs=get_globalstateinstrsiinletj=getucode(pc+2)inlety,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a[%d]@."Var.printyVar.printxj;compileinfos(pc+3)state(Let(y,Field(x,j,Non_float))::instrs)|SETGLOBAL->leti=getucode(pc+1)inState.size_globalsstate(i+1);lety=State.accustateinletg=State.globalsstateinassert(Option.is_noneg.vars.(i));ifdebug_parser()thenFormat.printf"(global %d) = %a@."iVar.printy;letinstrs=matchg.override.(i)with|Somef->letv,instrs=fyinstrsing.vars.(i)<-Somev;instrs|None->g.vars.(i)<-Somey;instrsinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = 0@."Var.printx;letinstrs=register_globalgiinstrsincompileinfos(pc+2)state(Let(x,const0)::instrs)|ATOM0->letx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = ATOM(0)@."Var.printx;compileinfos(pc+1)state(Let(x,Block(0,[||],Unknown,Maybe_mutable))::instrs)|ATOM->leti=getucode(pc+1)inletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = ATOM(%d)@."Var.printxi;compileinfos(pc+2)state(Let(x,Block(i,[||],Unknown,Maybe_mutable))::instrs)|PUSHATOM0->letstate=State.pushstateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = ATOM(0)@."Var.printx;compileinfos(pc+1)state(Let(x,Block(0,[||],Unknown,Maybe_mutable))::instrs)|PUSHATOM->letstate=State.pushstateinleti=getucode(pc+1)inletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = ATOM(%d)@."Var.printxi;compileinfos(pc+2)state(Let(x,Block(i,[||],Unknown,Maybe_mutable))::instrs)|MAKEBLOCK->letsize=getucode(pc+1)inlettag=getucode(pc+2)inletstate=State.pushstateinletx,state=State.fresh_varstateinletcontents,state=State.grabsizestateinifdebug_parser()then(Format.printf"%a = { "Var.printx;fori=0tosize-1doFormat.printf"%d = %a; "iVar.print(List.nthcontentsi)done;Format.printf"}@.");compileinfos(pc+3)state(Let(x,Block(tag,Array.of_listcontents,Unknown,Maybe_mutable))::instrs)|MAKEBLOCK1->lettag=getucode(pc+1)inlety=State.accustateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = { 0 = %a; }@."Var.printxVar.printy;compileinfos(pc+2)state(Let(x,Block(tag,[|y|],Unknown,Maybe_mutable))::instrs)|MAKEBLOCK2->lettag=getucode(pc+1)inlety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = { 0 = %a; 1 = %a; }@."Var.printxVar.printyVar.printz;compileinfos(pc+2)(State.pop1state)(Let(x,Block(tag,[|y;z|],Unknown,Maybe_mutable))::instrs)|MAKEBLOCK3->lettag=getucode(pc+1)inlety=State.accustateinletz=State.peek0stateinlett=State.peek1stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = { 0 = %a; 1 = %a; 2 = %a }@."Var.printxVar.printyVar.printzVar.printt;compileinfos(pc+2)(State.pop2state)(Let(x,Block(tag,[|y;z;t|],Unknown,Maybe_mutable))::instrs)|MAKEFLOATBLOCK->letsize=getucode(pc+1)inletstate=State.pushstateinletx,state=State.fresh_varstateinletcontents,state=State.grabsizestateinifdebug_parser()then(Format.printf"%a = { "Var.printx;fori=0tosize-1doFormat.printf"%d = %a; "iVar.print(List.nthcontentsi)done;Format.printf"}@.");compileinfos(pc+2)state(Let(x,Block(254,Array.of_listcontents,Unknown,Maybe_mutable))::instrs)|GETFIELD0->lety=State.accustateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a[0]@."Var.printxVar.printy;compileinfos(pc+1)state(Let(x,Field(y,0,Non_float))::instrs)|GETFIELD1->lety=State.accustateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a[1]@."Var.printxVar.printy;compileinfos(pc+1)state(Let(x,Field(y,1,Non_float))::instrs)|GETFIELD2->lety=State.accustateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a[2]@."Var.printxVar.printy;compileinfos(pc+1)state(Let(x,Field(y,2,Non_float))::instrs)|GETFIELD3->lety=State.accustateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a[3]@."Var.printxVar.printy;compileinfos(pc+1)state(Let(x,Field(y,3,Non_float))::instrs)|GETFIELD->lety=State.accustateinletn=getucode(pc+1)inletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a[%d]@."Var.printxVar.printyn;compileinfos(pc+2)state(Let(x,Field(y,n,Non_float))::instrs)|GETFLOATFIELD->lety=State.accustateinletn=getucode(pc+1)inletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = FLOAT{%a[%d]}@."Var.printxVar.printyn;compileinfos(pc+2)state(Let(x,Field(y,n,Float))::instrs)|SETFIELD0->lety=State.accustateinletz=State.peek0stateinifdebug_parser()thenFormat.printf"%a[0] = %a@."Var.printyVar.printz;letx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = 0@."Var.printx;compileinfos(pc+1)(State.pop1state)(Let(x,const0)::Set_field(y,0,Non_float,z)::instrs)|SETFIELD1->lety=State.accustateinletz=State.peek0stateinifdebug_parser()thenFormat.printf"%a[1] = %a@."Var.printyVar.printz;letx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = 0@."Var.printx;compileinfos(pc+1)(State.pop1state)(Let(x,const0)::Set_field(y,1,Non_float,z)::instrs)|SETFIELD2->lety=State.accustateinletz=State.peek0stateinifdebug_parser()thenFormat.printf"%a[2] = %a@."Var.printyVar.printz;letx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = 0@."Var.printx;compileinfos(pc+1)(State.pop1state)(Let(x,const0)::Set_field(y,2,Non_float,z)::instrs)|SETFIELD3->lety=State.accustateinletz=State.peek0stateinifdebug_parser()thenFormat.printf"%a[3] = %a@."Var.printyVar.printz;letx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = 0@."Var.printx;compileinfos(pc+1)(State.pop1state)(Let(x,const0)::Set_field(y,3,Non_float,z)::instrs)|SETFIELD->lety=State.accustateinletz=State.peek0stateinletn=getucode(pc+1)inifdebug_parser()thenFormat.printf"%a[%d] = %a@."Var.printynVar.printz;letx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = 0@."Var.printx;compileinfos(pc+2)(State.pop1state)(Let(x,const0)::Set_field(y,n,Non_float,z)::instrs)|SETFLOATFIELD->lety=State.accustateinletz=State.peek0stateinletn=getucode(pc+1)inifdebug_parser()thenFormat.printf"FLOAT{%a[%d]} = %a@."Var.printynVar.printz;letx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = 0@."Var.printx;compileinfos(pc+2)(State.pop1state)(Let(x,const0)::Set_field(y,n,Float,z)::instrs)|VECTLENGTH->lety=State.accustateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a.length@."Var.printxVar.printy;compileinfos(pc+1)state(Let(x,Prim(Vectlength,[Pvy]))::instrs)|GETVECTITEM->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a[%a]@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Array_get,[Pvy;Pvz]))::instrs)|SETVECTITEM->ifdebug_parser()thenFormat.printf"%a[%a] = %a@."Var.print(State.accustate)Var.print(State.peek0state)Var.print(State.peek1state);letinstrs=Array_set(State.accustate,State.peek0state,State.peek1state)::instrsinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = 0@."Var.printx;compileinfos(pc+1)(State.pop2state)(Let(x,const0)::instrs)|GETSTRINGCHAR->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a[%a]@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Extern"caml_string_unsafe_get",[Pvy;Pvz]))::instrs)|GETBYTESCHAR->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a[%a]@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Extern"caml_bytes_unsafe_get",[Pvy;Pvz]))::instrs)|SETBYTESCHAR->ifdebug_parser()thenFormat.printf"%a[%a] = %a@."Var.print(State.accustate)Var.print(State.peek0state)Var.print(State.peek1state);letx=State.accustateinlety=State.peek0stateinletz=State.peek1stateinlett,state=State.fresh_varstateinletinstrs=Let(t,Prim(Extern"caml_bytes_unsafe_set",[Pvx;Pvy;Pvz]))::instrsinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = 0@."Var.printx;compileinfos(pc+1)(State.pop2state)(Let(x,const0)::instrs)|BRANCH->letoffset=getscode(pc+1)inifdebug_parser()thenFormat.printf"... (branch)@.";instrs,Branch(pc+offset+1,[]),state|BRANCHIF->letoffset=getscode(pc+1)inletx=State.accustateininstrs,Cond(x,(pc+offset+1,[]),(pc+2,[])),state|BRANCHIFNOT->letoffset=getscode(pc+1)inletx=State.accustateininstrs,Cond(x,(pc+2,[]),(pc+offset+1,[])),state|SWITCH->(ifdebug_parser()thenFormat.printf"switch ...@.";letsz=getucode(pc+1)inletx=State.accustateinletisize=szland0XFFFFinletbsize=szlsr16inletbase=pc+2inletit=Array.initisize~f:(funi->base+getscode(base+i))inletbt=Array.initbsize~f:(funi->base+getscode(base+isize+i))inArray.iterit~f:(funpc'->compile_blockinfos.blocksinfos.debugcodepc'state);Array.iterbt~f:(funpc'->compile_blockinfos.blocksinfos.debugcodepc'state);matchisize,bsizewith|_,0->instrs,Switch(x,Array.mapit~f:(funpc->pc,[])),state|0,_->letx_tag=Var.fresh()inletinstrs=Let(x_tag,Prim(Extern"%direct_obj_tag",[Pvx]))::instrsininstrs,Switch(x_tag,Array.mapbt~f:(funpc->pc,[])),state|_,_->letisint_branch=pc+1inletisblock_branch=pc+2inlet()=tagged_blocks:=Addr.Map.addisint_branchstate!tagged_blocks;leti_state=State.start_blockisint_branchstateinleti_args=State.stack_varsi_stateincompiled_blocks:=Addr.Map.addisint_branch(i_state,[],Switch(x,Array.mapit~f:(funpc->pc,i_args)))!compiled_blocksinlet()=tagged_blocks:=Addr.Map.addisblock_branchstate!tagged_blocks;letx_tag=Var.fresh()inletb_state=State.start_blockisblock_branchstateinletb_args=State.stack_varsb_stateinletinstrs=[Let(x_tag,Prim(Extern"%direct_obj_tag",[Pvx]))]incompiled_blocks:=Addr.Map.addisblock_branch(b_state,instrs,Switch(x_tag,Array.mapbt~f:(funpc->pc,b_args)))!compiled_blocksinletisint_var=Var.fresh()inletinstrs=Let(isint_var,Prim(IsInt,[Pvx]))::instrsininstrs,Cond(isint_var,(isint_branch,[]),(isblock_branch,[])),state)|BOOLNOT->lety=State.accustateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = !%a@."Var.printxVar.printy;compileinfos(pc+1)state(Let(x,Prim(Not,[Pvy]))::instrs)|PUSHTRAP->(* We insert an intermediate block that binds the handler's
context, so that it is also in the scope of the body. Then,
when a mutable variable is assigned in the body, we can
update this context. *)letinterm_addr=pc+1inlethandler_ctx_state=State.start_blockinterm_addrstateinletbody_addr=pc+2inlethandler_addr=pc+1+getscode(pc+1)inletx,handler_state=State.fresh_varhandler_ctx_stateintagged_blocks:=Addr.Map.addinterm_addrstate!tagged_blocks;compiled_blocks:=Addr.Map.addinterm_addr(handler_ctx_state,[],Pushtrap((body_addr,State.stack_varsstate),x,(handler_addr,State.stack_varshandler_state)))!compiled_blocks;compile_blockinfos.blocksinfos.debugcodehandler_addrhandler_state;compile_blockinfos.blocksinfos.debugcodebody_addr{(State.push_handlerhandler_ctx_state)withState.stack=(* See interp.c *)State.Dummy"pushtrap(pc)"::State.Dummy"pushtrap(sp_off)"::State.Dummy"pushtrap(env)"::State.Dummy"pushtrap(extra_args)"::state.State.stack};instrs,Branch(interm_addr,[]),state|POPTRAP->letaddr=pc+1incompile_blockinfos.blocksinfos.debugcodeaddr(State.pop4(State.pop_handlerstate));instrs,Poptrap(addr,[]),state|RERAISE|RAISE_NOTRACE|RAISE->letkind=matchinstr.Instr.codewith|RERAISE->`Reraise|RAISE_NOTRACE->`Notrace|RAISE->`Normal|_->assertfalseinifdebug_parser()thenFormat.printf"throw(%a)@."Var.print(State.accustate);instrs,Raise(State.accustate,kind),state|CHECK_SIGNALS->compileinfos(pc+1)stateinstrs|C_CALL1->letprim=primitive_namestate(getucode(pc+1))inifString.equal(Primitive.resolveprim)"%identity"then(* This is a no-op *)compileinfos(pc+2)stateinstrselselety=State.accustateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = ccall \"%s\" (%a)@."Var.printxprimVar.printy;compileinfos(pc+2)state(Let(x,Prim(Externprim,[Pvy]))::instrs)|C_CALL2->letprim=primitive_namestate(getucode(pc+1))inlety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = ccall \"%s\" (%a, %a)@."Var.printxprimVar.printyVar.printz;compileinfos(pc+2)(State.pop1state)(Let(x,Prim(Externprim,[Pvy;Pvz]))::instrs)|C_CALL3->letprim=primitive_namestate(getucode(pc+1))inlety=State.accustateinletz=State.peek0stateinlett=State.peek1stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = ccall \"%s\" (%a, %a, %a)@."Var.printxprimVar.printyVar.printzVar.printt;compileinfos(pc+2)(State.pop2state)(Let(x,Prim(Externprim,[Pvy;Pvz;Pvt]))::instrs)|C_CALL4->letnargs=4inletprim=primitive_namestate(getucode(pc+1))inletstate=State.pushstateinletx,state=State.fresh_varstateinletargs,state=State.grabnargsstateinifdebug_parser()then(Format.printf"%a = ccall \"%s\" ("Var.printxprim;fori=0tonargs-1doifi>0thenFormat.printf", ";Format.printf"%a"Var.print(List.nthargsi)done;Format.printf")@.");compileinfos(pc+2)state(Let(x,Prim(Externprim,List.mapargs~f:(funx->Pvx)))::instrs)|C_CALL5->letnargs=5inletprim=primitive_namestate(getucode(pc+1))inletstate=State.pushstateinletx,state=State.fresh_varstateinletargs,state=State.grabnargsstateinifdebug_parser()then(Format.printf"%a = ccall \"%s\" ("Var.printxprim;fori=0tonargs-1doifi>0thenFormat.printf", ";Format.printf"%a"Var.print(List.nthargsi)done;Format.printf")@.");compileinfos(pc+2)state(Let(x,Prim(Externprim,List.mapargs~f:(funx->Pvx)))::instrs)|C_CALLN->letnargs=getucode(pc+1)inletprim=primitive_namestate(getucode(pc+2))inletstate=State.pushstateinletx,state=State.fresh_varstateinletargs,state=State.grabnargsstateinifdebug_parser()then(Format.printf"%a = ccall \"%s\" ("Var.printxprim;fori=0tonargs-1doifi>0thenFormat.printf", ";Format.printf"%a"Var.print(List.nthargsi)done;Format.printf")@.");compileinfos(pc+3)state(Let(x,Prim(Externprim,List.mapargs~f:(funx->Pvx)))::instrs)|(CONST0|CONST1|CONST2|CONST3)ascc->letx,state=State.fresh_varstateinletn=matchccwith|CONST0->0|CONST1->1|CONST2->2|CONST3->3|_->assertfalseinifdebug_parser()thenFormat.printf"%a = %d@."Var.printxn;compileinfos(pc+1)state(Let(x,constn)::instrs)|CONSTINT->letn=gets32code(pc+1)inletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %ld@."Var.printxn;compileinfos(pc+2)state(Let(x,const32n)::instrs)|(PUSHCONST0|PUSHCONST1|PUSHCONST2|PUSHCONST3)ascc->letstate=State.pushstateinletx,state=State.fresh_varstateinletn=matchccwith|PUSHCONST0->0|PUSHCONST1->1|PUSHCONST2->2|PUSHCONST3->3|_->assertfalseinifdebug_parser()thenFormat.printf"%a = %d@."Var.printxn;compileinfos(pc+1)state(Let(x,constn)::instrs)|PUSHCONSTINT->letstate=State.pushstateinletn=gets32code(pc+1)inletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %ld@."Var.printxn;compileinfos(pc+2)state(Let(x,const32n)::instrs)|NEGINT->lety=State.accustateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = -%a@."Var.printxVar.printy;compileinfos(pc+1)state(Let(x,Prim(Extern"%int_neg",[Pvy]))::instrs)|ADDINT->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a + %a@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Extern"%int_add",[Pvy;Pvz]))::instrs)|SUBINT->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a - %a@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Extern"%int_sub",[Pvy;Pvz]))::instrs)|MULINT->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a * %a@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Extern"%int_mul",[Pvy;Pvz]))::instrs)|DIVINT->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a / %a@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Extern"%int_div",[Pvy;Pvz]))::instrs)|MODINT->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a %% %a@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Extern"%int_mod",[Pvy;Pvz]))::instrs)|ANDINT->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a & %a@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Extern"%int_and",[Pvy;Pvz]))::instrs)|ORINT->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a | %a@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Extern"%int_or",[Pvy;Pvz]))::instrs)|XORINT->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a ^ %a@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Extern"%int_xor",[Pvy;Pvz]))::instrs)|LSLINT->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a << %a@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Extern"%int_lsl",[Pvy;Pvz]))::instrs)|LSRINT->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a >>> %a@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Extern"%int_lsr",[Pvy;Pvz]))::instrs)|ASRINT->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a >> %a@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Extern"%int_asr",[Pvy;Pvz]))::instrs)|EQ->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = mk_bool(%a == %a)@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Eq,[Pvy;Pvz]))::instrs)|NEQ->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = mk_bool(%a != %a)@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Neq,[Pvy;Pvz]))::instrs)|LTINT->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = mk_bool(%a < %a)@."Var.printxVar.printyVar.print(State.peek0state);compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Lt,[Pvy;Pvz]))::instrs)|LEINT->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = mk_bool(%a <= %a)@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Le,[Pvy;Pvz]))::instrs)|GTINT->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = mk_bool(%a > %a)@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Lt,[Pvz;Pvy]))::instrs)|GEINT->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = mk_bool(%a >= %a)@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Le,[Pvz;Pvy]))::instrs)|OFFSETINT->letn=gets32code(pc+1)inlety=State.accustateinletz,state=State.fresh_varstateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %a + %ld@."Var.printxVar.printyn;compileinfos(pc+2)state(Let(x,Prim(Extern"%int_add",[Pvy;Pvz]))::Let(z,const32n)::instrs)|OFFSETREF->letn=getscode(pc+1)inletx=State.accustateinifdebug_parser()thenFormat.printf"%a += %d@."Var.printxn;letinstrs=Offset_ref(x,n)::instrsinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"x = 0@.";compileinfos(pc+2)state(Let(x,const0)::instrs)|ISINT->lety=State.accustateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = !%a@."Var.printxVar.printy;compileinfos(pc+1)state(Let(x,Prim(IsInt,[Pvy]))::instrs)|BEQ->letn=gets32code(pc+1)inletoffset=getscode(pc+2)inletx=State.accustateinlety=Var.fresh()in(Let(y,Prim(Eq,[Pc(Int(Targetint.of_int32_exnn));Pvx]))::instrs,Cond(y,(pc+offset+2,[]),(pc+3,[])),state)|BNEQ->letn=gets32code(pc+1)inletoffset=getscode(pc+2)inletx=State.accustateinlety=Var.fresh()in(Let(y,Prim(Eq,[Pc(Int(Targetint.of_int32_exnn));Pvx]))::instrs,Cond(y,(pc+3,[]),(pc+offset+2,[])),state)|BLTINT->letn=gets32code(pc+1)inletoffset=getscode(pc+2)inletx=State.accustateinlety=Var.fresh()in(Let(y,Prim(Lt,[Pc(Int(Targetint.of_int32_exnn));Pvx]))::instrs,Cond(y,(pc+offset+2,[]),(pc+3,[])),state)|BLEINT->letn=gets32code(pc+1)inletoffset=getscode(pc+2)inletx=State.accustateinlety=Var.fresh()in(Let(y,Prim(Le,[Pc(Int(Targetint.of_int32_exnn));Pvx]))::instrs,Cond(y,(pc+offset+2,[]),(pc+3,[])),state)|BGTINT->letn=gets32code(pc+1)inletoffset=getscode(pc+2)inletx=State.accustateinlety=Var.fresh()in(Let(y,Prim(Le,[Pc(Int(Targetint.of_int32_exnn));Pvx]))::instrs,Cond(y,(pc+3,[]),(pc+offset+2,[])),state)|BGEINT->letn=gets32code(pc+1)inletoffset=getscode(pc+2)inletx=State.accustateinlety=Var.fresh()in(Let(y,Prim(Lt,[Pc(Int(Targetint.of_int32_exnn));Pvx]))::instrs,Cond(y,(pc+3,[]),(pc+offset+2,[])),state)|BULTINT->letn=getu32code(pc+1)inletoffset=getscode(pc+2)inletx=State.accustateinlety=Var.fresh()in(Let(y,Prim(Ult,[Pc(Int(Targetint.of_int32_exnn));Pvx]))::instrs,Cond(y,(pc+offset+2,[]),(pc+3,[])),state)|BUGEINT->letn=getu32code(pc+1)inletoffset=getscode(pc+2)inletx=State.accustateinlety=Var.fresh()in(Let(y,Prim(Ult,[Pc(Int(Targetint.of_int32_exnn));Pvx]))::instrs,Cond(y,(pc+3,[]),(pc+offset+2,[])),state)|ULTINT->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = mk_bool(%a <= %a) (unsigned)@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Ult,[Pvy;Pvz]))::instrs)|UGEINT->lety=State.accustateinletz=State.peek0stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = mk_bool(%a >= %a)@."Var.printxVar.printyVar.printz;compileinfos(pc+1)(State.pop1state)(Let(x,Prim(Ult,[Pvz;Pvy]))::instrs)|GETPUBMET->letn=gets32code(pc+1)inletcache=!method_cache_idinincrmethod_cache_id;letobj=State.accustateinletstate=State.pushstateinlettag,state=State.fresh_varstateinletm,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = %ld@."Var.printtagn;ifdebug_parser()thenFormat.printf"%a = caml_get_public_method(%a, %a)@."Var.printmVar.printobjVar.printtag;compileinfos(pc+3)state(Let(m,Prim(Extern"caml_get_public_method",[Pvobj;Pvtag;Pc(Int(Targetint.of_int_exncache))]))::Let(tag,const32n)::instrs)|GETDYNMET->lettag=State.accustateinletobj=State.peek0stateinletm,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = caml_get_public_method(%a, %a)@."Var.printmVar.printobjVar.printtag;compileinfos(pc+1)state(Let(m,Prim(Extern"caml_get_public_method",[Pvobj;Pvtag;Pc(IntTargetint.zero)]))::instrs)|GETMETHOD->letlab=State.accustateinletobj=State.peek0stateinletmeths,state=State.fresh_varstateinletm,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = lookup(%a, %a)@."Var.printmVar.printobjVar.printlab;compileinfos(pc+1)state(Let(m,Prim(Array_get,[Pvmeths;Pvlab]))::Let(meths,Field(obj,0,Non_float))::instrs)|STOP->instrs,Stop,state|RESUME->letstack=State.accustateinletfunc=State.peek0stateinletarg=State.peek1stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = resume(%a, %a, %a)@."Var.printxVar.printstackVar.printfuncVar.printarg;letstate=matchOcaml_version.compareOcaml_version.current[5;2]<0with|true->State.pop2state|false->State.pop3stateincompileinfos(pc+1)state(Let(x,Prim(Extern"%resume",[Pvstack;Pvfunc;Pvarg]))::instrs)|RESUMETERM->letstack=State.accustateinletfunc=State.peek0stateinletarg=State.peek1stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"return resume(%a, %a, %a)@."Var.printstackVar.printfuncVar.printarg;(Let(x,Prim(Extern"%resume",[Pvstack;Pvfunc;Pvarg]))::instrs,Returnx,state)|PERFORM->leteff=State.accustateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"%a = perform(%a)@."Var.printxVar.printeff;compileinfos(pc+1)state(Let(x,Prim(Extern"%perform",[Pveff]))::instrs)|REPERFORMTERM->leteff=State.accustateinletstack=State.peek0statein(* We don't need [State.peek 1 state] *)letstate=State.pop2stateinletx,state=State.fresh_varstateinifdebug_parser()thenFormat.printf"return reperform(%a, %a)@."Var.printeffVar.printstack;(Let(x,Prim(Extern"%reperform",[Pveff;Pvstack]))::instrs,Returnx,state)|EVENT|BREAK|FIRST_UNIMPLEMENTED_OP->assertfalse)(****)typeone={code:Code.program;cmis:StringSet.t;debug:Debug.t}letparse_bytecodecodeglobalsdebug_data=letstate=State.initialglobalsinCode.Var.reset();letblocks'=Blocks.analysecodeinletp=ifnot(Blocks.is_emptyblocks')then(letstart=0incompile_blockblocks'debug_datacodestartstate;letblocks=Addr.Map.mapi(fun_(state,instr,last)->{params=State.stack_varsstate;body=instr;branch=last})!compiled_blocksinletfree_pc=String.lengthcode/4in{start;blocks;free_pc})elseCode.emptyincompiled_blocks:=Addr.Map.empty;tagged_blocks:=Addr.Map.empty;p(* HACK - override module *)letoverride_global=matchOcaml_version.compareOcaml_version.current[4;13]>=0with|true->[]|false->[("CamlinternalMod",fun_originstrs->letx=Var.fresh_n"internalMod"inletinit_mod=Var.fresh_n"init_mod"inletupdate_mod=Var.fresh_n"update_mod"in(x,Let(x,Block(0,[|init_mod;update_mod|],NotArray,Immutable))::Let(init_mod,Special(Alias_prim"caml_CamlinternalMod_init_mod"))::Let(update_mod,Special(Alias_prim"caml_CamlinternalMod_update_mod"))::instrs))](* HACK END *)moduleToc:sigtypetvalread:in_channel->tvalseek_section:t->in_channel->string->intvalread_code:t->in_channel->stringvalread_data:t->in_channel->Obj.tarrayvalread_crcs:t->in_channel->(string*Digest.toption)listvalread_prim:t->in_channel->stringvalread_symb:t->in_channel->Ocaml_compiler.Symtable.GlobalMap.tend=structtypet=(string*int)listletseek_sectiontocicname=letrecseek_seccurr_ofs=function|[]->raiseNot_found|(n,len)::rem->ifString.equalnnamethen(seek_inic(curr_ofs-len);len)elseseek_sec(curr_ofs-len)reminseek_sec(in_channel_lengthic-16-(8*List.lengthtoc))tocletreadic=letpos_trailer=in_channel_lengthic-16inseek_inicpos_trailer;letnum_sections=input_binary_inticinseek_inic(pos_trailer-(8*num_sections));letsection_table=ref[]infor_i=1tonum_sectionsdoletname=really_input_stringic4inletlen=input_binary_inticinsection_table:=(name,len)::!section_tabledone;!section_tableletread_codetocic=letcode_size=seek_sectiontocic"CODE"inreally_input_stringiccode_sizeletread_datatocic=ignore(seek_sectiontocic"DATA");letinit_data:Obj.tarray=input_valueicininit_dataletread_symbtocic=ignore(seek_sectiontocic"SYMB");letorig_symbols:Ocaml_compiler.Symtable.GlobalMap.t=input_valueicinorig_symbolsletread_crcstocic=ignore(seek_sectiontocic"CRCS");letorig_crcs:(string*Digest.toption)list=input_valueicinorig_crcsletread_primtocic=letprim_size=seek_sectiontocic"PRIM"inletprim=really_input_stringicprim_sizeinprimendletread_primitivestocic=letprim=Toc.read_primtocicinassert(Char.equal(String.getprim(String.lengthprim-1))'\000');String.split_char~sep:'\000'(String.subprim~pos:0~len:(String.lengthprim-1))typebytesections={symb:Ocaml_compiler.Symtable.GlobalMap.t;crcs:(string*Digest.toption)list;prim:stringlist;dlpt:stringlist}[@@ocaml.warning"-unused-field"]letfrom_exe?(includes=[])~linkall~link_info~include_cmis?exported_unit?(debug=false)ic=letdebug_data=Debug.create~include_cmisdebuginlettoc=Toc.readicinletprimitives=read_primitivestocicinletprimitive_table=Array.of_listprimitivesinletcode=Toc.read_codetocicinletinit_data=Toc.read_datatocicinletinit_data=Array.map~f:Constants.parseinit_datainletorig_symbols=Toc.read_symbtocicinletorig_crcs=Toc.read_crcstocicinletkeeps=lett=Hashtbl.create17inList.iter~f:(fun(_,s)->Hashtbl.addts())predefined_exceptions;List.iter~f:(funs->Hashtbl.addts())["Outcometree";"Topdirs";"Toploop"];tinletkeeps=tryHashtbl.findkeepss;truewithNot_found->(matchexported_unitwith|Somel->List.mems~set:l|None->true)inletcrcs=List.filter~f:(fun(unit,_crc)->keepunit)orig_crcsinletsymbols=Ocaml_compiler.Symtable.GlobalMap.filter(function|Glob_predef_->true|Glob_compunitname->keepname)orig_symbolsinlett=Timer.make()in(ifDebug.dbg_section_neededdebug_datathentryignore(Toc.seek_sectiontocic"DBUG");Debug.readdebug_data~crcs~includesicwithNot_found->ifDebug.enableddebug_data||include_cmisthenwarn"Warning: Program not linked with -g, original variable names and locations \
not available.@.");iftimes()thenFormat.eprintf" read debug events: %a@."Timer.printt;letglobals=make_globals(Array.lengthinit_data)init_dataprimitive_tablein(* Initialize module override mechanism *)List.iteroverride_global~f:(fun(name,v)->tryletnn=Ocaml_compiler.Symtable.Global.Glob_compunitnameinleti=Ocaml_compiler.Symtable.GlobalMap.findnnorig_symbolsinglobals.override.(i)<-Somev;ifdebug_parser()thenFormat.eprintf"overriding global %s@."namewithNot_found->());iflinkallthen(* export globals *)Ocaml_compiler.Symtable.GlobalMap.itersymbols~f:(funidn->globals.named_value.(n)<-Some(Ocaml_compiler.Symtable.Global.nameid);globals.is_exported.(n)<-true);letp=parse_bytecodecodeglobalsdebug_datain(* register predefined exception *)letbody=List.fold_leftpredefined_exceptions~init:[]~f:(funbody(i,name)->globals.named_value.(i)<-Somename;letbody=register_global~force:trueglobalsibodyinglobals.is_exported.(i)<-false;body)inletbody=Array.fold_right_iglobals.constants~init:body~f:(funi_l->matchglobals.vars.(i)with|Somexwhenglobals.is_const.(i)->letl=register_globalglobalsilinLet(x,Constantglobals.constants.(i))::l|_->l)inletbody=iflink_infothenletsymbols_array=Ocaml_compiler.Symtable.GlobalMap.fold(funipacc->(Ocaml_compiler.Symtable.Global.namei,p)::acc)symbols[]|>Array.of_listin(* Include linking information *)letsections={symb=symbols;crcs;prim=primitives;dlpt=[]}inletgdata=Var.fresh()inletneed_gdata=reffalseinletinfos=["sections",Constants.parse(Obj.reprsections);"symbols",Constants.parse(Obj.reprsymbols_array);"prim_count",Int(Targetint.of_int_exn(Array.lengthglobals.primitives))]inletbody=List.fold_leftinfos~init:body~f:(funrem(name,const)->assert(String.is_valid_utf_8name);need_gdata:=true;letc=Var.fresh()inLet(c,Constantconst)::Let(Var.fresh(),Prim(Extern"caml_js_set",[Pvgdata;Pc(NativeString(Code.Native_string.of_stringname));Pvc]))::rem)inif!need_gdatathenLet(gdata,Prim(Extern"caml_get_global_data",[]))::bodyelsebodyelsebodyin(* List interface files *)letis_module=letis_ident_char=function|'A'..'Z'|'a'..'z'|'_'|'\''|'0'..'9'->true|_->falseinletis_uppercase=function|'A'..'Z'->true|_->falseinfunname->tryifString.lengthname=0thenraiseExit;ifnot(is_uppercasename.[0])thenraiseExit;fori=1toString.lengthname-1doifnot(is_ident_charname.[i])thenraiseExitdone;truewithExit->falseinletcmis=ifinclude_cmisthenOcaml_compiler.Symtable.GlobalMap.fold(funid_numacc->matchidwith|Ocaml_compiler.Symtable.Global.Glob_compunitname->ifis_modulenamethenStringSet.addnameaccelseacc|Glob_predef_->acc)symbolsStringSet.emptyelseStringSet.emptyinletcmis=matchexported_unitwith|None->cmis|Somel->ifinclude_cmisthenList.fold_leftl~init:cmis~f:(funaccs->StringSet.addsacc)elsecmisinletcode=prependpbodyinCode.invariantcode;{code;cmis;debug=debug_data}(* As input: list of primitives + size of global table *)letfrom_bytes~prims~debug(code:bytecode)=letdebug_data=Debug.create~include_cmis:falsetrueinlett=Timer.make()inifDebug.namesdebug_datathenArray.iterdebug~f:(funl->List.iterl~f:(funev->Debug.read_event~paths:[]~crcs:(Hashtbl.create17)~orig:0debug_dataev));iftimes()thenFormat.eprintf" read debug events: %a@."Timer.printt;letident_table=lett=Hashtbl.create17inifDebug.namesdebug_datathenOcaml_compiler.Symtable.GlobalMap.iter(Ocaml_compiler.Symtable.current_state())~f:(funidpos'->Hashtbl.addtpos'id);tinletglobals=make_globals0[||]primsinletp=parse_bytecodecodeglobalsdebug_datainletgdata=Var.fresh_n"global_data"inletneed_gdata=reffalseinletfind_namei=letvalue=(Meta.global_data()).(i)inlettag=Obj.tagvalueiniftag=Obj.string_tagthenSome("cst_"^Obj.magicvalue:string)elsematchHashtbl.findident_tableiwith|exceptionNot_found->None|glob->Some(Ocaml_compiler.Symtable.Global.nameglob)inletbody=Array.fold_right_iglobals.vars~init:[]~f:(funivarl->matchvarwith|Somexwhenglobals.is_const.(i)->(ifDebug.namesdebug_datathenmatchfind_nameiwith|None->()|Somename->Code.Var.namexname);need_gdata:=true;Let(x,Field(gdata,i,Non_float))::l|_->l)inletbody=if!need_gdatathenLet(gdata,Prim(Extern"caml_get_global_data",[]))::bodyelsebodyinprependpbody,debug_dataletfrom_string~prims~debug(code:string)=from_bytes~prims~debugcodemoduleReloc=structletgen_patch_intbuffposn=Bytes.setbuff(pos+0)(Char.unsafe_chrn);Bytes.setbuff(pos+1)(Char.unsafe_chr(nasr8));Bytes.setbuff(pos+2)(Char.unsafe_chr(nasr16));Bytes.setbuff(pos+3)(Char.unsafe_chr(nasr24))typet={mutablepos:int;mutableconstants:Code.constantlist;mutablestep2_started:bool;names:(string,int)Hashtbl.t;primitives:(string,int)Hashtbl.t}letcreate()=letconstants=[]in{pos=List.lengthconstants;constants;step2_started=false;names=Hashtbl.create17;primitives=Hashtbl.create17}letconstant_of_constx=Ocaml_compiler.constant_of_constx[@@ifocaml_version<(5,1,0)]letconstant_of_constx=Constants.parsex[@@ifocaml_version>=(5,1,0)](* We currently rely on constants to be relocated before globals. *)letstep1tcompunitcode=ift.step2_startedthenassertfalse;letopenCmo_formatinList.itercompunit.cu_primitives~f:(funname->Hashtbl.addt.primitivesname(Hashtbl.lengtht.primitives));letslot_for_literalsc=t.constants<-constant_of_constsc::t.constants;letpos=t.posint.pos<-succt.pos;posinletnum_of_primname=tryHashtbl.findt.primitivesnamewithNot_found->leti=Hashtbl.lengtht.primitivesinHashtbl.addt.primitivesnamei;iinList.itercompunit.cu_reloc~f:(function|Reloc_literalsc,pos->gen_patch_intcodepos(slot_for_literalsc)|Reloc_primitivename,pos->gen_patch_intcodepos(num_of_primname)|_->())letstep2tcompunitcode=t.step2_started<-true;letopenCmo_formatinletnextname=tryHashtbl.findt.namesnamewithNot_found->letpos=t.posint.pos<-succt.pos;Hashtbl.addt.namesnamepos;posinletslot_for_globalid=nextidinList.itercompunit.cu_reloc~f:(fun(reloc,pos)->letpatchname=gen_patch_intcodeposnameinmatchrelocwith|((Reloc_getglobalid)[@ifocaml_version<(5,2,0)])->patch(slot_for_global(Ident.nameid))|((Reloc_setglobalid)[@ifocaml_version<(5,2,0)])->patch(slot_for_global(Ident.nameid))|((Reloc_getcompunit(Compunitid))[@ifocaml_version>=(5,2,0)])->patch(slot_for_globalid)|((Reloc_getpredef(Predef_exnid))[@ifocaml_version>=(5,2,0)])->patch(slot_for_globalid)|((Reloc_setcompunit(Compunitid))[@ifocaml_version>=(5,2,0)])->patch(slot_for_globalid)|_->())letprimitivest=letl=Hashtbl.lengtht.primitivesinleta=Array.makel""inHashtbl.iter(funnamei->a.(i)<-name)t.primitives;aletconstantst=Array.of_list(List.revt.constants)letmake_globalst=letprimitives=primitivestinletconstants=constantstinletglobals=make_globals(Array.lengthconstants)constantsprimitivesinresize_globalsglobalst.pos;Hashtbl.iter(funnamei->globals.named_value.(i)<-Somename)t.names;(* Initialize module override mechanism *)List.iteroverride_global~f:(fun(name,v)->tryleti=Hashtbl.findt.namesnameinglobals.override.(i)<-Somev;ifdebug_parser()thenFormat.eprintf"overriding global %s@."namewithNot_found->());globalsendletfrom_compilation_units~includes:_~include_cmis~debug_datal=letreloc=Reloc.create()inList.iterl~f:(fun(compunit,code)->Reloc.step1reloccompunitcode);List.iterl~f:(fun(compunit,code)->Reloc.step2reloccompunitcode);letglobals=Reloc.make_globalsrelocinletcode=letl=List.mapl~f:(fun(_,c)->Bytes.to_stringc)inString.concat~sep:""linletprog=parse_bytecodecodeglobalsdebug_datainletgdata=Var.fresh_n"global_data"inletneed_gdata=reffalseinletbody=Array.fold_right_iglobals.vars~init:[]~f:(funivarl->matchvarwith|Somexwhenglobals.is_const.(i)->(matchglobals.named_value.(i)with|None->letl=register_globalglobalsilinletcst=globals.constants.(i)in(matchcst,Code.Var.get_namexwith|Stringstr,None->Code.Var.namex(Printf.sprintf"cst_%s"str)|_->());Let(x,Constantcst)::l|Somename->Var.namexname;need_gdata:=true;Let(x,Prim(Extern"caml_js_get",[Pvgdata;Pc(NativeString(Native_string.of_stringname))]))::l)|_->l)inletbody=if!need_gdatathenLet(gdata,Prim(Extern"caml_get_global_data",[]))::bodyelsebodyinletcmis=ifinclude_cmisthenList.fold_leftl~init:StringSet.empty~f:(funacc(compunit,_)->StringSet.add(Ocaml_compiler.Cmo_format.namecompunit)acc)elseStringSet.emptyin{code=prependprogbody;cmis;debug=debug_data}letfrom_cmo?(includes=[])?(include_cmis=false)?(debug=false)compunitic=letdebug_data=Debug.create~include_cmisdebuginseek_iniccompunit.Cmo_format.cu_pos;letcode=Bytes.createcompunit.Cmo_format.cu_codesizeinreally_inputiccode0compunit.Cmo_format.cu_codesize;lett=Timer.make()inifDebug.dbg_section_neededdebug_data&&compunit.Cmo_format.cu_debug<>0then(seek_iniccompunit.Cmo_format.cu_debug;Debug.read_event_listdebug_data~crcs:[]~includes~orig:0ic);iftimes()thenFormat.eprintf" read debug events: %a@."Timer.printt;letp=from_compilation_units~includes~include_cmis~debug_data[compunit,code]inCode.invariantp.code;pletfrom_cma?(includes=[])?(include_cmis=false)?(debug=false)libic=letdebug_data=Debug.create~include_cmisdebuginletorig=ref0inlett=ref0.inletunits=List.maplib.Cmo_format.lib_units~f:(funcompunit->seek_iniccompunit.Cmo_format.cu_pos;letcode=Bytes.createcompunit.Cmo_format.cu_codesizeinreally_inputiccode0compunit.Cmo_format.cu_codesize;lett0=Timer.make()inifDebug.dbg_section_neededdebug_data&&compunit.Cmo_format.cu_debug<>0then(seek_iniccompunit.Cmo_format.cu_debug;Debug.read_event_listdebug_data~crcs:[]~includes~orig:!origic);t:=!t+.Timer.gett0;orig:=!orig+compunit.Cmo_format.cu_codesize;compunit,code)iniftimes()thenFormat.eprintf" read debug events: %.2f@."!t;letp=from_compilation_units~includes~include_cmis~debug_dataunitsinCode.invariantp.code;pletfrom_channelic=letformat=tryletheader=really_input_stringicMagic_number.sizein`Pre(Magic_number.of_stringheader)with_->letpos_magic=in_channel_lengthic-Magic_number.sizeinseek_inicpos_magic;letheader=really_input_stringicMagic_number.sizein`Post(Magic_number.of_stringheader)inmatchformatwith|`Premagic->(matchMagic_number.kindmagicwith|`Cmo->ifConfig.Flag.check_magic()&¬(Magic_number.equalmagicMagic_number.current_cmo)thenraiseMagic_number.(Bad_magic_versionmagic);letcompunit_pos=input_binary_inticinseek_iniccompunit_pos;letcompunit:Cmo_format.compilation_unit=input_valueicin`Cmocompunit|`Cma->ifConfig.Flag.check_magic()&¬(Magic_number.equalmagicMagic_number.current_cma)thenraiseMagic_number.(Bad_magic_versionmagic);letpos_toc=input_binary_inticin(* Go to table of contents *)seek_inicpos_toc;letlib:Cmo_format.library=input_valueicin`Cmalib|_->raiseMagic_number.(Bad_magic_number(to_stringmagic)))|`Postmagic->(matchMagic_number.kindmagicwith|`Exe->ifConfig.Flag.check_magic()&¬(Magic_number.equalmagicMagic_number.current_exe)thenraiseMagic_number.(Bad_magic_versionmagic);`Exe|_->raiseMagic_number.(Bad_magic_number(to_stringmagic)))letpredefined_exceptions()=(* Register predefined exceptions in case of separate compilation *)letbody=letopenCodeinList.mappredefined_exceptions~f:(fun(index,name)->assert(String.is_valid_utf_8name);letexn=Var.fresh()inletv_name=Var.fresh()inletv_index=Var.fresh()in[Let(v_name,Constant(Stringname));Let(v_index,Constant(Int((* Predefined exceptions are registered in
Symtable.init with [-index - 1] *)Targetint.of_int_exn(-index-1))));Let(exn,Block(248,[|v_name;v_index|],NotArray,Immutable))]@matchConfig.target()with|`JavaScript->letv_name_js=Var.fresh()in[Let(v_name_js,Constant(NativeString(Native_string.of_stringname)));Let(Var.fresh(),Prim(Extern"caml_register_global",[Pc(Int(Targetint.of_int_exnindex));Pvexn;Pvv_name_js]))]|`Wasm->[Let(Var.fresh(),Prim(Extern"caml_register_global",[Pc(Int(Targetint.of_int_exnindex));Pvexn;Pvv_name]))(* Also make the exception available to the generated code *);Let(Var.fresh(),Prim(Extern"caml_set_global",[Pc(Stringname);Pvexn]))])|>List.concatinletblock={params=[];body;branch=Stop}inletunit_info={Unit_info.provides=StringSet.of_list(List.map~f:sndpredefined_exceptions);requires=StringSet.empty;crcs=StringMap.empty;force_link=true;effects_without_cps=false;primitives=[]}in{start=0;blocks=Addr.Map.singleton0block;free_pc=1},unit_infoletlink_info~symbols~primitives~crcs=letgdata=Code.Var.fresh_n"global_data"inletsymbols_array=Ocaml_compiler.Symtable.GlobalMap.fold(funipacc->(Ocaml_compiler.Symtable.Global.namei,p)::acc)symbols[]|>Array.of_listinletprimitives=(* Add the externals translated by jsoo directly (in generate.ml) *)StringSet.union(Primitive.get_external())primitives|>StringSet.elementsinletbody=[]inletbody=(* Include linking information *)letsections={symb=symbols;crcs;prim=primitives;dlpt=[]}inletinfos=["sections",Constants.parse(Obj.reprsections);"symbols",Constants.parse(Obj.reprsymbols_array);"prim_count",Int(Targetint.of_int_exn(List.lengthprimitives))]inletbody=List.fold_leftinfos~init:body~f:(funrem(name,const)->letc=Var.fresh()inLet(c,Constantconst)::Let(Var.fresh(),Prim(Extern"caml_js_set",[Pvgdata;Pc(NativeString(Native_string.of_stringname));Pvc]))::rem)inLet(gdata,Prim(Extern"caml_get_global_data",[]))::bodyinletblock={params=[];body;branch=Stop}in{start=0;blocks=Addr.Map.singleton0block;free_pc=1}