BackwardPass.cpp 305 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "Backend.h"
  6. #define INLINEEMETAARG_COUNT 3
  7. BackwardPass::BackwardPass(Func * func, GlobOpt * globOpt, Js::Phase tag)
  8. : func(func), globOpt(globOpt), tag(tag), currentPrePassLoop(nullptr), tempAlloc(nullptr),
  9. preOpBailOutInstrToProcess(nullptr),
  10. considerSymAsRealUseInNoImplicitCallUses(nullptr),
  11. isCollectionPass(false), currentRegion(nullptr)
  12. {
  13. // Those are the only two phase dead store will be used currently
  14. Assert(tag == Js::BackwardPhase || tag == Js::DeadStorePhase);
  15. this->implicitCallBailouts = 0;
  16. this->fieldOpts = 0;
  17. #if DBG_DUMP
  18. this->numDeadStore = 0;
  19. this->numMarkTempNumber = 0;
  20. this->numMarkTempNumberTransferred = 0;
  21. this->numMarkTempObject = 0;
  22. #endif
  23. }
  24. void
  25. BackwardPass::DoSetDead(IR::Opnd * opnd, bool isDead) const
  26. {
  27. // Note: Dead bit on the Opnd records flow-based liveness.
  28. // This is distinct from isLastUse, which records lexical last-ness.
  29. if (isDead && this->tag == Js::BackwardPhase && !this->IsPrePass())
  30. {
  31. opnd->SetIsDead();
  32. }
  33. else if (this->tag == Js::DeadStorePhase)
  34. {
  35. // Set or reset in DeadStorePhase.
  36. // CSE could make previous dead operand not the last use, so reset it.
  37. opnd->SetIsDead(isDead);
  38. }
  39. }
  40. bool
  41. BackwardPass::DoByteCodeUpwardExposedUsed() const
  42. {
  43. return (this->tag == Js::DeadStorePhase && this->func->hasBailout) ||
  44. (this->func->HasTry() && this->func->DoOptimizeTry() && this->tag == Js::BackwardPhase);
  45. }
  46. bool
  47. BackwardPass::DoFieldHoistCandidates() const
  48. {
  49. return DoFieldHoistCandidates(this->currentBlock->loop);
  50. }
  51. bool
  52. BackwardPass::DoFieldHoistCandidates(Loop * loop) const
  53. {
  54. // We only need to do one pass to generate this data
  55. return this->tag == Js::BackwardPhase
  56. && !this->IsPrePass() && loop && GlobOpt::DoFieldHoisting(loop);
  57. }
  58. bool
  59. BackwardPass::DoMarkTempNumbers() const
  60. {
  61. #if FLOATVAR
  62. return false;
  63. #else
  64. // only mark temp number on the dead store phase
  65. return (tag == Js::DeadStorePhase) && !PHASE_OFF(Js::MarkTempPhase, this->func) &&
  66. !PHASE_OFF(Js::MarkTempNumberPhase, this->func) && func->DoFastPaths() && (!this->func->HasTry());
  67. #endif
  68. }
  69. bool
  70. BackwardPass::DoMarkTempObjects() const
  71. {
  72. // only mark temp object on the backward store phase
  73. return (tag == Js::BackwardPhase) && !PHASE_OFF(Js::MarkTempPhase, this->func) &&
  74. !PHASE_OFF(Js::MarkTempObjectPhase, this->func) && func->DoGlobOpt() && func->GetHasTempObjectProducingInstr() &&
  75. !func->IsJitInDebugMode() &&
  76. func->DoGlobOptsForGeneratorFunc();
  77. // Why MarkTempObject is disabled under debugger:
  78. // We add 'identified so far dead non-temp locals' to byteCodeUpwardExposedUsed in ProcessBailOutInfo,
  79. // this may cause MarkTempObject to convert some temps back to non-temp when it sees a 'transferred exposed use'
  80. // from a temp to non-temp. That's in general not a supported conversion (while non-temp -> temp is fine).
  81. }
  82. bool
  83. BackwardPass::DoMarkTempNumbersOnTempObjects() const
  84. {
  85. return !PHASE_OFF(Js::MarkTempNumberOnTempObjectPhase, this->func) && DoMarkTempNumbers() && this->func->GetHasMarkTempObjects();
  86. }
  87. #if DBG
  88. bool
  89. BackwardPass::DoMarkTempObjectVerify() const
  90. {
  91. // only mark temp object on the backward store phase
  92. return (tag == Js::DeadStorePhase) && !PHASE_OFF(Js::MarkTempPhase, this->func) &&
  93. !PHASE_OFF(Js::MarkTempObjectPhase, this->func) && func->DoGlobOpt() && func->GetHasTempObjectProducingInstr();
  94. }
  95. #endif
  96. // static
  97. bool
  98. BackwardPass::DoDeadStore(Func* func)
  99. {
  100. return
  101. !PHASE_OFF(Js::DeadStorePhase, func) &&
  102. (!func->HasTry() || func->DoOptimizeTry());
  103. }
  104. bool
  105. BackwardPass::DoDeadStore() const
  106. {
  107. return
  108. this->tag == Js::DeadStorePhase &&
  109. DoDeadStore(this->func);
  110. }
  111. bool
  112. BackwardPass::DoDeadStoreSlots() const
  113. {
  114. // only dead store fields if glob opt is on to generate the trackable fields bitvector
  115. return (tag == Js::DeadStorePhase && this->func->DoGlobOpt()
  116. && (!this->func->HasTry()));
  117. }
  118. // Whether dead store is enabled for given func and sym.
  119. // static
  120. bool
  121. BackwardPass::DoDeadStore(Func* func, StackSym* sym)
  122. {
  123. // Dead store is disabled under debugger for non-temp local vars.
  124. return
  125. DoDeadStore(func) &&
  126. !(func->IsJitInDebugMode() && sym->HasByteCodeRegSlot() && func->IsNonTempLocalVar(sym->GetByteCodeRegSlot())) &&
  127. func->DoGlobOptsForGeneratorFunc();
  128. }
  129. bool
  130. BackwardPass::DoTrackNegativeZero() const
  131. {
  132. return
  133. !PHASE_OFF(Js::TrackIntUsagePhase, func) &&
  134. !PHASE_OFF(Js::TrackNegativeZeroPhase, func) &&
  135. func->DoGlobOpt() &&
  136. !IsPrePass() &&
  137. !func->IsJitInDebugMode() &&
  138. func->DoGlobOptsForGeneratorFunc();
  139. }
  140. bool
  141. BackwardPass::DoTrackBitOpsOrNumber() const
  142. {
  143. #if _WIN64
  144. return
  145. !PHASE_OFF1(Js::TypedArrayVirtualPhase) &&
  146. tag == Js::BackwardPhase &&
  147. func->DoGlobOpt() &&
  148. !IsPrePass() &&
  149. !func->IsJitInDebugMode() &&
  150. func->DoGlobOptsForGeneratorFunc();
  151. #else
  152. return false;
  153. #endif
  154. }
  155. bool
  156. BackwardPass::DoTrackIntOverflow() const
  157. {
  158. return
  159. !PHASE_OFF(Js::TrackIntUsagePhase, func) &&
  160. !PHASE_OFF(Js::TrackIntOverflowPhase, func) &&
  161. tag == Js::BackwardPhase &&
  162. !IsPrePass() &&
  163. globOpt->DoLossyIntTypeSpec() &&
  164. !func->IsJitInDebugMode() &&
  165. func->DoGlobOptsForGeneratorFunc();
  166. }
  167. bool
  168. BackwardPass::DoTrackCompoundedIntOverflow() const
  169. {
  170. return
  171. !PHASE_OFF(Js::TrackCompoundedIntOverflowPhase, func) &&
  172. DoTrackIntOverflow() && !func->IsTrackCompoundedIntOverflowDisabled();
  173. }
  174. bool
  175. BackwardPass::DoTrackNon32BitOverflow() const
  176. {
  177. // enabled only for IA
  178. #if defined(_M_IX86) || defined(_M_X64)
  179. return true;
  180. #else
  181. return false;
  182. #endif
  183. }
  184. void
  185. BackwardPass::CleanupBackwardPassInfoInFlowGraph()
  186. {
  187. if (!this->func->m_fg->hasBackwardPassInfo)
  188. {
  189. // No information to clean up
  190. return;
  191. }
  192. // The backward pass temp arena has already been deleted, we can just reset the data
  193. FOREACH_BLOCK_IN_FUNC_DEAD_OR_ALIVE(block, this->func)
  194. {
  195. block->upwardExposedUses = nullptr;
  196. block->upwardExposedFields = nullptr;
  197. block->typesNeedingKnownObjectLayout = nullptr;
  198. block->fieldHoistCandidates = nullptr;
  199. block->slotDeadStoreCandidates = nullptr;
  200. block->byteCodeUpwardExposedUsed = nullptr;
  201. #if DBG
  202. block->byteCodeRestoreSyms = nullptr;
  203. #endif
  204. block->tempNumberTracker = nullptr;
  205. block->tempObjectTracker = nullptr;
  206. #if DBG
  207. block->tempObjectVerifyTracker = nullptr;
  208. #endif
  209. block->stackSymToFinalType = nullptr;
  210. block->stackSymToGuardedProperties = nullptr;
  211. block->stackSymToWriteGuardsMap = nullptr;
  212. block->cloneStrCandidates = nullptr;
  213. block->noImplicitCallUses = nullptr;
  214. block->noImplicitCallNoMissingValuesUses = nullptr;
  215. block->noImplicitCallNativeArrayUses = nullptr;
  216. block->noImplicitCallJsArrayHeadSegmentSymUses = nullptr;
  217. block->noImplicitCallArrayLengthSymUses = nullptr;
  218. block->couldRemoveNegZeroBailoutForDef = nullptr;
  219. if (block->loop != nullptr)
  220. {
  221. block->loop->hasDeadStoreCollectionPass = false;
  222. block->loop->hasDeadStorePrepass = false;
  223. }
  224. }
  225. NEXT_BLOCK_IN_FUNC_DEAD_OR_ALIVE;
  226. }
  227. /*
  228. * We Insert ArgIns at the start of the function for all the formals.
  229. * Unused formals will be deadstored during the deadstore pass.
  230. * We need ArgIns only for the outermost function(inliner).
  231. */
  232. void
  233. BackwardPass::InsertArgInsForFormals()
  234. {
  235. if (func->IsStackArgsEnabled() && !func->GetJITFunctionBody()->HasImplicitArgIns())
  236. {
  237. IR::Instr * insertAfterInstr = func->m_headInstr->m_next;
  238. AssertMsg(insertAfterInstr->IsLabelInstr(), "First Instr of the first block should always have a label");
  239. Js::ArgSlot paramsCount = insertAfterInstr->m_func->GetJITFunctionBody()->GetInParamsCount() - 1;
  240. IR::Instr * argInInstr = nullptr;
  241. for (Js::ArgSlot argumentIndex = 1; argumentIndex <= paramsCount; argumentIndex++)
  242. {
  243. IR::SymOpnd * srcOpnd;
  244. StackSym * symSrc = StackSym::NewParamSlotSym(argumentIndex + 1, func);
  245. StackSym * symDst = StackSym::New(func);
  246. IR::RegOpnd * dstOpnd = IR::RegOpnd::New(symDst, TyVar, func);
  247. func->SetArgOffset(symSrc, (argumentIndex + LowererMD::GetFormalParamOffset()) * MachPtr);
  248. srcOpnd = IR::SymOpnd::New(symSrc, TyVar, func);
  249. argInInstr = IR::Instr::New(Js::OpCode::ArgIn_A, dstOpnd, srcOpnd, func);
  250. insertAfterInstr->InsertAfter(argInInstr);
  251. insertAfterInstr = argInInstr;
  252. AssertMsg(!func->HasStackSymForFormal(argumentIndex - 1), "Already has a stack sym for this formal?");
  253. this->func->TrackStackSymForFormalIndex(argumentIndex - 1, symDst);
  254. }
  255. if (PHASE_VERBOSE_TRACE1(Js::StackArgFormalsOptPhase) && paramsCount > 0)
  256. {
  257. Output::Print(_u("StackArgFormals : %s (%d) :Inserting ArgIn_A for LdSlot (formals) in the start of Deadstore pass. \n"), func->GetJITFunctionBody()->GetDisplayName(), func->GetFunctionNumber());
  258. Output::Flush();
  259. }
  260. }
  261. }
  262. void
  263. BackwardPass::MarkScopeObjSymUseForStackArgOpt()
  264. {
  265. IR::Instr * instr = this->currentInstr;
  266. if (tag == Js::DeadStorePhase)
  267. {
  268. if (instr->DoStackArgsOpt(this->func) && instr->m_func->GetScopeObjSym() != nullptr && this->DoByteCodeUpwardExposedUsed())
  269. {
  270. if (this->currentBlock->byteCodeUpwardExposedUsed == nullptr)
  271. {
  272. this->currentBlock->byteCodeUpwardExposedUsed = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  273. }
  274. this->currentBlock->byteCodeUpwardExposedUsed->Set(instr->m_func->GetScopeObjSym()->m_id);
  275. }
  276. }
  277. }
  278. void
  279. BackwardPass::ProcessBailOnStackArgsOutOfActualsRange()
  280. {
  281. IR::Instr * instr = this->currentInstr;
  282. if (tag == Js::DeadStorePhase &&
  283. (instr->m_opcode == Js::OpCode::LdElemI_A || instr->m_opcode == Js::OpCode::TypeofElem) &&
  284. instr->HasBailOutInfo() && !IsPrePass())
  285. {
  286. if (instr->DoStackArgsOpt(this->func))
  287. {
  288. AssertMsg(instr->GetBailOutKind() & IR::BailOnStackArgsOutOfActualsRange, "Stack args bail out is not set when the optimization is turned on? ");
  289. if (instr->GetBailOutKind() & ~IR::BailOnStackArgsOutOfActualsRange)
  290. {
  291. Assert(instr->GetBailOutKind() == (IR::BailOnStackArgsOutOfActualsRange | IR::BailOutOnImplicitCallsPreOp));
  292. //We are sure at this point, that we will not have any implicit calls as we wouldn't have done this optimization in the first place.
  293. instr->SetBailOutKind(IR::BailOnStackArgsOutOfActualsRange);
  294. }
  295. }
  296. else if (instr->GetBailOutKind() & IR::BailOnStackArgsOutOfActualsRange)
  297. {
  298. //If we don't decide to do StackArgs, then remove the bail out at this point.
  299. //We would have optimistically set the bailout in the forward pass, and by the end of forward pass - we
  300. //turned off stack args for some reason. So we are removing it in the deadstore pass.
  301. IR::BailOutKind bailOutKind = instr->GetBailOutKind() & ~IR::BailOnStackArgsOutOfActualsRange;
  302. if (bailOutKind == IR::BailOutInvalid)
  303. {
  304. instr->ClearBailOutInfo();
  305. }
  306. else
  307. {
  308. instr->SetBailOutKind(bailOutKind);
  309. }
  310. }
  311. }
  312. }
  313. void
  314. BackwardPass::Optimize()
  315. {
  316. if (tag == Js::BackwardPhase && PHASE_OFF(tag, this->func))
  317. {
  318. return;
  319. }
  320. if (tag == Js::DeadStorePhase)
  321. {
  322. if (!this->func->DoLoopFastPaths() || !this->func->DoFastPaths())
  323. {
  324. //arguments[] access is similar to array fast path hence disable when array fastpath is disabled.
  325. //loopFastPath is always true except explicitly disabled
  326. //defaultDoFastPath can be false when we the source code size is huge
  327. func->SetHasStackArgs(false);
  328. }
  329. InsertArgInsForFormals();
  330. }
  331. NoRecoverMemoryJitArenaAllocator localAlloc(tag == Js::BackwardPhase? _u("BE-Backward") : _u("BE-DeadStore"),
  332. this->func->m_alloc->GetPageAllocator(), Js::Throw::OutOfMemory);
  333. this->tempAlloc = &localAlloc;
  334. #if DBG_DUMP
  335. if (this->IsTraceEnabled())
  336. {
  337. this->func->DumpHeader();
  338. }
  339. #endif
  340. this->CleanupBackwardPassInfoInFlowGraph();
  341. // Info about whether a sym is used in a way in which -0 differs from +0, or whether the sym is used in a way in which an
  342. // int32 overflow when generating the value of the sym matters, in the current block. The info is transferred to
  343. // instructions that define the sym in the current block as they are encountered. The info in these bit vectors is discarded
  344. // after optimizing each block, so the only info that remains for GlobOpt is that which is transferred to instructions.
  345. BVSparse<JitArenaAllocator> localNegativeZeroDoesNotMatterBySymId(tempAlloc);
  346. negativeZeroDoesNotMatterBySymId = &localNegativeZeroDoesNotMatterBySymId;
  347. BVSparse<JitArenaAllocator> localSymUsedOnlyForBitOpsBySymId(tempAlloc);
  348. symUsedOnlyForBitOpsBySymId = &localSymUsedOnlyForBitOpsBySymId;
  349. BVSparse<JitArenaAllocator> localSymUsedOnlyForNumberBySymId(tempAlloc);
  350. symUsedOnlyForNumberBySymId = &localSymUsedOnlyForNumberBySymId;
  351. BVSparse<JitArenaAllocator> localIntOverflowDoesNotMatterBySymId(tempAlloc);
  352. intOverflowDoesNotMatterBySymId = &localIntOverflowDoesNotMatterBySymId;
  353. BVSparse<JitArenaAllocator> localIntOverflowDoesNotMatterInRangeBySymId(tempAlloc);
  354. intOverflowDoesNotMatterInRangeBySymId = &localIntOverflowDoesNotMatterInRangeBySymId;
  355. BVSparse<JitArenaAllocator> localCandidateSymsRequiredToBeInt(tempAlloc);
  356. candidateSymsRequiredToBeInt = &localCandidateSymsRequiredToBeInt;
  357. BVSparse<JitArenaAllocator> localCandidateSymsRequiredToBeLossyInt(tempAlloc);
  358. candidateSymsRequiredToBeLossyInt = &localCandidateSymsRequiredToBeLossyInt;
  359. intOverflowCurrentlyMattersInRange = true;
  360. FloatSymEquivalenceMap localFloatSymEquivalenceMap(tempAlloc);
  361. floatSymEquivalenceMap = &localFloatSymEquivalenceMap;
  362. NumberTempRepresentativePropertySymMap localNumberTempRepresentativePropertySym(tempAlloc);
  363. numberTempRepresentativePropertySym = &localNumberTempRepresentativePropertySym;
  364. FOREACH_BLOCK_BACKWARD_IN_FUNC_DEAD_OR_ALIVE(block, this->func)
  365. {
  366. this->OptBlock(block);
  367. }
  368. NEXT_BLOCK_BACKWARD_IN_FUNC_DEAD_OR_ALIVE;
  369. if (this->tag == Js::DeadStorePhase && !PHASE_OFF(Js::MemOpPhase, this->func))
  370. {
  371. this->RemoveEmptyLoops();
  372. }
  373. this->func->m_fg->hasBackwardPassInfo = true;
  374. if(DoTrackCompoundedIntOverflow())
  375. {
  376. // Tracking int overflow makes use of a scratch field in stack syms, which needs to be cleared
  377. func->m_symTable->ClearStackSymScratch();
  378. }
  379. #if DBG_DUMP
  380. if (PHASE_STATS(this->tag, this->func))
  381. {
  382. this->func->DumpHeader();
  383. Output::Print(this->tag == Js::BackwardPhase? _u("Backward Phase Stats:\n") : _u("Deadstore Phase Stats:\n"));
  384. if (this->DoDeadStore())
  385. {
  386. Output::Print(_u(" Deadstore : %3d\n"), this->numDeadStore);
  387. }
  388. if (this->DoMarkTempNumbers())
  389. {
  390. Output::Print(_u(" Temp Number : %3d\n"), this->numMarkTempNumber);
  391. Output::Print(_u(" Transferred Temp Number: %3d\n"), this->numMarkTempNumberTransferred);
  392. }
  393. if (this->DoMarkTempObjects())
  394. {
  395. Output::Print(_u(" Temp Object : %3d\n"), this->numMarkTempObject);
  396. }
  397. }
  398. #endif
  399. }
  400. void
  401. BackwardPass::MergeSuccBlocksInfo(BasicBlock * block)
  402. {
  403. // Can't reuse the bv in the current block, because its successor can be itself.
  404. TempNumberTracker * tempNumberTracker = nullptr;
  405. TempObjectTracker * tempObjectTracker = nullptr;
  406. #if DBG
  407. TempObjectVerifyTracker * tempObjectVerifyTracker = nullptr;
  408. #endif
  409. HashTable<AddPropertyCacheBucket> * stackSymToFinalType = nullptr;
  410. HashTable<ObjTypeGuardBucket> * stackSymToGuardedProperties = nullptr;
  411. HashTable<ObjWriteGuardBucket> * stackSymToWriteGuardsMap = nullptr;
  412. BVSparse<JitArenaAllocator> * cloneStrCandidates = nullptr;
  413. BVSparse<JitArenaAllocator> * noImplicitCallUses = nullptr;
  414. BVSparse<JitArenaAllocator> * noImplicitCallNoMissingValuesUses = nullptr;
  415. BVSparse<JitArenaAllocator> * noImplicitCallNativeArrayUses = nullptr;
  416. BVSparse<JitArenaAllocator> * noImplicitCallJsArrayHeadSegmentSymUses = nullptr;
  417. BVSparse<JitArenaAllocator> * noImplicitCallArrayLengthSymUses = nullptr;
  418. BVSparse<JitArenaAllocator> * upwardExposedUses = nullptr;
  419. BVSparse<JitArenaAllocator> * upwardExposedFields = nullptr;
  420. BVSparse<JitArenaAllocator> * typesNeedingKnownObjectLayout = nullptr;
  421. BVSparse<JitArenaAllocator> * fieldHoistCandidates = nullptr;
  422. BVSparse<JitArenaAllocator> * slotDeadStoreCandidates = nullptr;
  423. BVSparse<JitArenaAllocator> * byteCodeUpwardExposedUsed = nullptr;
  424. BVSparse<JitArenaAllocator> * couldRemoveNegZeroBailoutForDef = nullptr;
  425. #if DBG
  426. uint byteCodeLocalsCount = func->GetJITFunctionBody()->GetLocalsCount();
  427. StackSym ** byteCodeRestoreSyms = nullptr;
  428. #endif
  429. Assert(!block->isDead || block->GetSuccList()->Empty());
  430. if (this->DoByteCodeUpwardExposedUsed())
  431. {
  432. byteCodeUpwardExposedUsed = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  433. #if DBG
  434. byteCodeRestoreSyms = JitAnewArrayZ(this->tempAlloc, StackSym *, byteCodeLocalsCount);
  435. #endif
  436. }
  437. #if DBG
  438. if (!IsCollectionPass() && this->DoMarkTempObjectVerify())
  439. {
  440. tempObjectVerifyTracker = JitAnew(this->tempAlloc, TempObjectVerifyTracker, this->tempAlloc, block->loop != nullptr);
  441. }
  442. #endif
  443. if (!block->isDead)
  444. {
  445. bool keepUpwardExposed = (this->tag == Js::BackwardPhase);
  446. JitArenaAllocator *upwardExposedArena = nullptr;
  447. if(!IsCollectionPass())
  448. {
  449. upwardExposedArena = keepUpwardExposed ? this->globOpt->alloc : this->tempAlloc;
  450. upwardExposedUses = JitAnew(upwardExposedArena, BVSparse<JitArenaAllocator>, upwardExposedArena);
  451. upwardExposedFields = JitAnew(upwardExposedArena, BVSparse<JitArenaAllocator>, upwardExposedArena);
  452. if (this->tag == Js::DeadStorePhase)
  453. {
  454. typesNeedingKnownObjectLayout = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  455. }
  456. if (this->DoFieldHoistCandidates())
  457. {
  458. fieldHoistCandidates = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  459. }
  460. if (this->DoDeadStoreSlots())
  461. {
  462. slotDeadStoreCandidates = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  463. }
  464. if (this->DoMarkTempNumbers())
  465. {
  466. tempNumberTracker = JitAnew(this->tempAlloc, TempNumberTracker, this->tempAlloc, block->loop != nullptr);
  467. }
  468. if (this->DoMarkTempObjects())
  469. {
  470. tempObjectTracker = JitAnew(this->tempAlloc, TempObjectTracker, this->tempAlloc, block->loop != nullptr);
  471. }
  472. noImplicitCallUses = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  473. noImplicitCallNoMissingValuesUses = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  474. noImplicitCallNativeArrayUses = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  475. noImplicitCallJsArrayHeadSegmentSymUses = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  476. noImplicitCallArrayLengthSymUses = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  477. if (this->tag == Js::BackwardPhase)
  478. {
  479. cloneStrCandidates = JitAnew(this->globOpt->alloc, BVSparse<JitArenaAllocator>, this->globOpt->alloc);
  480. }
  481. else
  482. {
  483. couldRemoveNegZeroBailoutForDef = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  484. }
  485. }
  486. bool firstSucc = true;
  487. FOREACH_SUCCESSOR_BLOCK(blockSucc, block)
  488. {
  489. #if defined(DBG_DUMP) || defined(ENABLE_DEBUG_CONFIG_OPTIONS)
  490. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  491. #endif
  492. // save the byteCodeUpwardExposedUsed from deleting for the block right after the memop loop
  493. if (this->tag == Js::DeadStorePhase && !this->IsPrePass() && globOpt->HasMemOp(block->loop) && blockSucc->loop != block->loop)
  494. {
  495. Assert(block->loop->memOpInfo->inductionVariablesUsedAfterLoop == nullptr);
  496. block->loop->memOpInfo->inductionVariablesUsedAfterLoop = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  497. block->loop->memOpInfo->inductionVariablesUsedAfterLoop->Or(blockSucc->byteCodeUpwardExposedUsed);
  498. block->loop->memOpInfo->inductionVariablesUsedAfterLoop->Or(blockSucc->upwardExposedUses);
  499. }
  500. bool deleteData = false;
  501. if (!blockSucc->isLoopHeader && blockSucc->backwardPassCurrentLoop == this->currentPrePassLoop)
  502. {
  503. Assert(blockSucc->GetDataUseCount() != 0);
  504. deleteData = (blockSucc->DecrementDataUseCount() == 0);
  505. }
  506. Assert((byteCodeUpwardExposedUsed == nullptr) == !this->DoByteCodeUpwardExposedUsed());
  507. if (byteCodeUpwardExposedUsed && blockSucc->byteCodeUpwardExposedUsed)
  508. {
  509. byteCodeUpwardExposedUsed->Or(blockSucc->byteCodeUpwardExposedUsed);
  510. if (this->tag == Js::DeadStorePhase)
  511. {
  512. #if DBG
  513. for (uint i = 0; i < byteCodeLocalsCount; i++)
  514. {
  515. if (byteCodeRestoreSyms[i] == nullptr)
  516. {
  517. byteCodeRestoreSyms[i] = blockSucc->byteCodeRestoreSyms[i];
  518. }
  519. else
  520. {
  521. Assert(blockSucc->byteCodeRestoreSyms[i] == nullptr
  522. || byteCodeRestoreSyms[i] == blockSucc->byteCodeRestoreSyms[i]);
  523. }
  524. }
  525. #endif
  526. if (deleteData)
  527. {
  528. // byteCodeUpwardExposedUsed is required to populate the writeThroughSymbolsSet for the try region. So, don't delete it in the backwards pass.
  529. JitAdelete(this->tempAlloc, blockSucc->byteCodeUpwardExposedUsed);
  530. blockSucc->byteCodeUpwardExposedUsed = nullptr;
  531. }
  532. }
  533. #if DBG
  534. if (deleteData)
  535. {
  536. JitAdeleteArray(this->tempAlloc, byteCodeLocalsCount, blockSucc->byteCodeRestoreSyms);
  537. blockSucc->byteCodeRestoreSyms = nullptr;
  538. }
  539. #endif
  540. }
  541. else
  542. {
  543. Assert(blockSucc->byteCodeUpwardExposedUsed == nullptr);
  544. Assert(blockSucc->byteCodeRestoreSyms == nullptr);
  545. }
  546. if(IsCollectionPass())
  547. {
  548. continue;
  549. }
  550. Assert((blockSucc->upwardExposedUses != nullptr)
  551. || (blockSucc->isLoopHeader && (this->IsPrePass() || blockSucc->loop->IsDescendentOrSelf(block->loop))));
  552. Assert((blockSucc->upwardExposedFields != nullptr)
  553. || (blockSucc->isLoopHeader && (this->IsPrePass() || blockSucc->loop->IsDescendentOrSelf(block->loop))));
  554. Assert((blockSucc->typesNeedingKnownObjectLayout != nullptr)
  555. || (blockSucc->isLoopHeader && (this->IsPrePass() || blockSucc->loop->IsDescendentOrSelf(block->loop)))
  556. || this->tag != Js::DeadStorePhase);
  557. Assert((blockSucc->fieldHoistCandidates != nullptr)
  558. || blockSucc->isLoopHeader
  559. || !this->DoFieldHoistCandidates(blockSucc->loop));
  560. Assert((blockSucc->slotDeadStoreCandidates != nullptr)
  561. || (blockSucc->isLoopHeader && (this->IsPrePass() || blockSucc->loop->IsDescendentOrSelf(block->loop)))
  562. || !this->DoDeadStoreSlots());
  563. Assert((blockSucc->tempNumberTracker != nullptr)
  564. || (blockSucc->isLoopHeader && (this->IsPrePass() || blockSucc->loop->IsDescendentOrSelf(block->loop)))
  565. || !this->DoMarkTempNumbers());
  566. Assert((blockSucc->tempObjectTracker != nullptr)
  567. || (blockSucc->isLoopHeader && (this->IsPrePass() || blockSucc->loop->IsDescendentOrSelf(block->loop)))
  568. || !this->DoMarkTempObjects());
  569. Assert((blockSucc->tempObjectVerifyTracker != nullptr)
  570. || (blockSucc->isLoopHeader && (this->IsPrePass() || blockSucc->loop->IsDescendentOrSelf(block->loop)))
  571. || !this->DoMarkTempObjectVerify());
  572. if (blockSucc->upwardExposedUses != nullptr)
  573. {
  574. upwardExposedUses->Or(blockSucc->upwardExposedUses);
  575. if (deleteData && (!keepUpwardExposed
  576. || (this->IsPrePass() && blockSucc->backwardPassCurrentLoop == this->currentPrePassLoop)))
  577. {
  578. JitAdelete(upwardExposedArena, blockSucc->upwardExposedUses);
  579. blockSucc->upwardExposedUses = nullptr;
  580. }
  581. }
  582. if (blockSucc->upwardExposedFields != nullptr)
  583. {
  584. upwardExposedFields->Or(blockSucc->upwardExposedFields);
  585. if (deleteData && (!keepUpwardExposed
  586. || (this->IsPrePass() && blockSucc->backwardPassCurrentLoop == this->currentPrePassLoop)))
  587. {
  588. JitAdelete(upwardExposedArena, blockSucc->upwardExposedFields);
  589. blockSucc->upwardExposedFields = nullptr;
  590. }
  591. }
  592. if (blockSucc->typesNeedingKnownObjectLayout != nullptr)
  593. {
  594. typesNeedingKnownObjectLayout->Or(blockSucc->typesNeedingKnownObjectLayout);
  595. if (deleteData)
  596. {
  597. JitAdelete(this->tempAlloc, blockSucc->typesNeedingKnownObjectLayout);
  598. blockSucc->typesNeedingKnownObjectLayout = nullptr;
  599. }
  600. }
  601. if (fieldHoistCandidates && blockSucc->fieldHoistCandidates != nullptr)
  602. {
  603. fieldHoistCandidates->Or(blockSucc->fieldHoistCandidates);
  604. if (deleteData)
  605. {
  606. JitAdelete(this->tempAlloc, blockSucc->fieldHoistCandidates);
  607. blockSucc->fieldHoistCandidates = nullptr;
  608. }
  609. }
  610. if (blockSucc->slotDeadStoreCandidates != nullptr)
  611. {
  612. slotDeadStoreCandidates->And(blockSucc->slotDeadStoreCandidates);
  613. if (deleteData)
  614. {
  615. JitAdelete(this->tempAlloc, blockSucc->slotDeadStoreCandidates);
  616. blockSucc->slotDeadStoreCandidates = nullptr;
  617. }
  618. }
  619. if (blockSucc->tempNumberTracker != nullptr)
  620. {
  621. Assert((blockSucc->loop != nullptr) == blockSucc->tempNumberTracker->HasTempTransferDependencies());
  622. tempNumberTracker->MergeData(blockSucc->tempNumberTracker, deleteData);
  623. if (deleteData)
  624. {
  625. blockSucc->tempNumberTracker = nullptr;
  626. }
  627. }
  628. if (blockSucc->tempObjectTracker != nullptr)
  629. {
  630. Assert((blockSucc->loop != nullptr) == blockSucc->tempObjectTracker->HasTempTransferDependencies());
  631. tempObjectTracker->MergeData(blockSucc->tempObjectTracker, deleteData);
  632. if (deleteData)
  633. {
  634. blockSucc->tempObjectTracker = nullptr;
  635. }
  636. }
  637. #if DBG
  638. if (blockSucc->tempObjectVerifyTracker != nullptr)
  639. {
  640. Assert((blockSucc->loop != nullptr) == blockSucc->tempObjectVerifyTracker->HasTempTransferDependencies());
  641. tempObjectVerifyTracker->MergeData(blockSucc->tempObjectVerifyTracker, deleteData);
  642. if (deleteData)
  643. {
  644. blockSucc->tempObjectVerifyTracker = nullptr;
  645. }
  646. }
  647. #endif
  648. PHASE_PRINT_TRACE(Js::ObjTypeSpecStorePhase, this->func,
  649. _u("ObjTypeSpecStore: func %s, edge %d => %d: "),
  650. this->func->GetDebugNumberSet(debugStringBuffer),
  651. block->GetBlockNum(), blockSucc->GetBlockNum());
  652. auto fixupFrom = [block, blockSucc, this](Bucket<AddPropertyCacheBucket> &bucket)
  653. {
  654. AddPropertyCacheBucket *fromData = &bucket.element;
  655. if (fromData->GetInitialType() == nullptr ||
  656. fromData->GetFinalType() == fromData->GetInitialType())
  657. {
  658. return;
  659. }
  660. this->InsertTypeTransitionsAtPriorSuccessors(block, blockSucc, bucket.value, fromData);
  661. };
  662. auto fixupTo = [blockSucc, this](Bucket<AddPropertyCacheBucket> &bucket)
  663. {
  664. AddPropertyCacheBucket *toData = &bucket.element;
  665. if (toData->GetInitialType() == nullptr ||
  666. toData->GetFinalType() == toData->GetInitialType())
  667. {
  668. return;
  669. }
  670. this->InsertTypeTransitionAtBlock(blockSucc, bucket.value, toData);
  671. };
  672. if (blockSucc->stackSymToFinalType != nullptr)
  673. {
  674. #if DBG_DUMP
  675. if (PHASE_TRACE(Js::ObjTypeSpecStorePhase, this->func))
  676. {
  677. blockSucc->stackSymToFinalType->Dump();
  678. }
  679. #endif
  680. if (firstSucc)
  681. {
  682. stackSymToFinalType = blockSucc->stackSymToFinalType->Copy();
  683. }
  684. else if (stackSymToFinalType != nullptr)
  685. {
  686. if (this->IsPrePass())
  687. {
  688. stackSymToFinalType->And(blockSucc->stackSymToFinalType);
  689. }
  690. else
  691. {
  692. // Insert any type transitions that can't be merged past this point.
  693. stackSymToFinalType->AndWithFixup(blockSucc->stackSymToFinalType, fixupFrom, fixupTo);
  694. }
  695. }
  696. else if (!this->IsPrePass())
  697. {
  698. FOREACH_HASHTABLE_ENTRY(AddPropertyCacheBucket, bucket, blockSucc->stackSymToFinalType)
  699. {
  700. fixupTo(bucket);
  701. }
  702. NEXT_HASHTABLE_ENTRY;
  703. }
  704. if (deleteData)
  705. {
  706. blockSucc->stackSymToFinalType->Delete();
  707. blockSucc->stackSymToFinalType = nullptr;
  708. }
  709. }
  710. else
  711. {
  712. PHASE_PRINT_TRACE(Js::ObjTypeSpecStorePhase, this->func, _u("null\n"));
  713. if (stackSymToFinalType)
  714. {
  715. if (!this->IsPrePass())
  716. {
  717. FOREACH_HASHTABLE_ENTRY(AddPropertyCacheBucket, bucket, stackSymToFinalType)
  718. {
  719. fixupFrom(bucket);
  720. }
  721. NEXT_HASHTABLE_ENTRY;
  722. }
  723. stackSymToFinalType->Delete();
  724. stackSymToFinalType = nullptr;
  725. }
  726. }
  727. if (tag == Js::BackwardPhase)
  728. {
  729. if (blockSucc->cloneStrCandidates != nullptr)
  730. {
  731. Assert(cloneStrCandidates != nullptr);
  732. cloneStrCandidates->Or(blockSucc->cloneStrCandidates);
  733. if (deleteData)
  734. {
  735. JitAdelete(this->globOpt->alloc, blockSucc->cloneStrCandidates);
  736. blockSucc->cloneStrCandidates = nullptr;
  737. }
  738. }
  739. #if DBG_DUMP
  740. if (PHASE_VERBOSE_TRACE(Js::TraceObjTypeSpecWriteGuardsPhase, this->func))
  741. {
  742. char16 debugStringBuffer2[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  743. Output::Print(_u("ObjTypeSpec: top function %s (%s), function %s (%s), write guard symbols on edge %d => %d: "),
  744. this->func->GetTopFunc()->GetJITFunctionBody()->GetDisplayName(),
  745. this->func->GetTopFunc()->GetDebugNumberSet(debugStringBuffer),
  746. this->func->GetJITFunctionBody()->GetDisplayName(),
  747. this->func->GetDebugNumberSet(debugStringBuffer2), block->GetBlockNum(),
  748. blockSucc->GetBlockNum());
  749. }
  750. #endif
  751. if (blockSucc->stackSymToWriteGuardsMap != nullptr)
  752. {
  753. #if DBG_DUMP
  754. if (PHASE_VERBOSE_TRACE(Js::TraceObjTypeSpecWriteGuardsPhase, this->func))
  755. {
  756. Output::Print(_u("\n"));
  757. blockSucc->stackSymToWriteGuardsMap->Dump();
  758. }
  759. #endif
  760. if (stackSymToWriteGuardsMap == nullptr)
  761. {
  762. stackSymToWriteGuardsMap = blockSucc->stackSymToWriteGuardsMap->Copy();
  763. }
  764. else
  765. {
  766. stackSymToWriteGuardsMap->Or(
  767. blockSucc->stackSymToWriteGuardsMap, &BackwardPass::MergeWriteGuards);
  768. }
  769. if (deleteData)
  770. {
  771. blockSucc->stackSymToWriteGuardsMap->Delete();
  772. blockSucc->stackSymToWriteGuardsMap = nullptr;
  773. }
  774. }
  775. else
  776. {
  777. #if DBG_DUMP
  778. if (PHASE_VERBOSE_TRACE(Js::TraceObjTypeSpecWriteGuardsPhase, this->func))
  779. {
  780. Output::Print(_u("null\n"));
  781. }
  782. #endif
  783. }
  784. }
  785. else
  786. {
  787. #if DBG_DUMP
  788. if (PHASE_VERBOSE_TRACE(Js::TraceObjTypeSpecTypeGuardsPhase, this->func))
  789. {
  790. char16 debugStringBuffer2[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  791. Output::Print(_u("ObjTypeSpec: top function %s (%s), function %s (%s), guarded property operations on edge %d => %d: \n"),
  792. this->func->GetTopFunc()->GetJITFunctionBody()->GetDisplayName(),
  793. this->func->GetTopFunc()->GetDebugNumberSet(debugStringBuffer),
  794. this->func->GetJITFunctionBody()->GetDisplayName(),
  795. this->func->GetDebugNumberSet(debugStringBuffer2),
  796. block->GetBlockNum(), blockSucc->GetBlockNum());
  797. }
  798. #endif
  799. if (blockSucc->stackSymToGuardedProperties != nullptr)
  800. {
  801. #if DBG_DUMP
  802. if (PHASE_VERBOSE_TRACE(Js::TraceObjTypeSpecTypeGuardsPhase, this->func))
  803. {
  804. blockSucc->stackSymToGuardedProperties->Dump();
  805. Output::Print(_u("\n"));
  806. }
  807. #endif
  808. if (stackSymToGuardedProperties == nullptr)
  809. {
  810. stackSymToGuardedProperties = blockSucc->stackSymToGuardedProperties->Copy();
  811. }
  812. else
  813. {
  814. stackSymToGuardedProperties->Or(
  815. blockSucc->stackSymToGuardedProperties, &BackwardPass::MergeGuardedProperties);
  816. }
  817. if (deleteData)
  818. {
  819. blockSucc->stackSymToGuardedProperties->Delete();
  820. blockSucc->stackSymToGuardedProperties = nullptr;
  821. }
  822. }
  823. else
  824. {
  825. #if DBG_DUMP
  826. if (PHASE_VERBOSE_TRACE(Js::TraceObjTypeSpecTypeGuardsPhase, this->func))
  827. {
  828. Output::Print(_u("null\n"));
  829. }
  830. #endif
  831. }
  832. if (blockSucc->couldRemoveNegZeroBailoutForDef != nullptr)
  833. {
  834. couldRemoveNegZeroBailoutForDef->And(blockSucc->couldRemoveNegZeroBailoutForDef);
  835. if (deleteData)
  836. {
  837. JitAdelete(this->tempAlloc, blockSucc->couldRemoveNegZeroBailoutForDef);
  838. blockSucc->couldRemoveNegZeroBailoutForDef = nullptr;
  839. }
  840. }
  841. }
  842. if (blockSucc->noImplicitCallUses != nullptr)
  843. {
  844. noImplicitCallUses->Or(blockSucc->noImplicitCallUses);
  845. if (deleteData)
  846. {
  847. JitAdelete(this->tempAlloc, blockSucc->noImplicitCallUses);
  848. blockSucc->noImplicitCallUses = nullptr;
  849. }
  850. }
  851. if (blockSucc->noImplicitCallNoMissingValuesUses != nullptr)
  852. {
  853. noImplicitCallNoMissingValuesUses->Or(blockSucc->noImplicitCallNoMissingValuesUses);
  854. if (deleteData)
  855. {
  856. JitAdelete(this->tempAlloc, blockSucc->noImplicitCallNoMissingValuesUses);
  857. blockSucc->noImplicitCallNoMissingValuesUses = nullptr;
  858. }
  859. }
  860. if (blockSucc->noImplicitCallNativeArrayUses != nullptr)
  861. {
  862. noImplicitCallNativeArrayUses->Or(blockSucc->noImplicitCallNativeArrayUses);
  863. if (deleteData)
  864. {
  865. JitAdelete(this->tempAlloc, blockSucc->noImplicitCallNativeArrayUses);
  866. blockSucc->noImplicitCallNativeArrayUses = nullptr;
  867. }
  868. }
  869. if (blockSucc->noImplicitCallJsArrayHeadSegmentSymUses != nullptr)
  870. {
  871. noImplicitCallJsArrayHeadSegmentSymUses->Or(blockSucc->noImplicitCallJsArrayHeadSegmentSymUses);
  872. if (deleteData)
  873. {
  874. JitAdelete(this->tempAlloc, blockSucc->noImplicitCallJsArrayHeadSegmentSymUses);
  875. blockSucc->noImplicitCallJsArrayHeadSegmentSymUses = nullptr;
  876. }
  877. }
  878. if (blockSucc->noImplicitCallArrayLengthSymUses != nullptr)
  879. {
  880. noImplicitCallArrayLengthSymUses->Or(blockSucc->noImplicitCallArrayLengthSymUses);
  881. if (deleteData)
  882. {
  883. JitAdelete(this->tempAlloc, blockSucc->noImplicitCallArrayLengthSymUses);
  884. blockSucc->noImplicitCallArrayLengthSymUses = nullptr;
  885. }
  886. }
  887. firstSucc = false;
  888. }
  889. NEXT_SUCCESSOR_BLOCK;
  890. #if DBG_DUMP
  891. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  892. if (PHASE_TRACE(Js::ObjTypeSpecStorePhase, this->func))
  893. {
  894. Output::Print(_u("ObjTypeSpecStore: func %s, block %d: "),
  895. this->func->GetDebugNumberSet(debugStringBuffer),
  896. block->GetBlockNum());
  897. if (stackSymToFinalType)
  898. {
  899. stackSymToFinalType->Dump();
  900. }
  901. else
  902. {
  903. Output::Print(_u("null\n"));
  904. }
  905. }
  906. if (PHASE_TRACE(Js::TraceObjTypeSpecTypeGuardsPhase, this->func))
  907. {
  908. Output::Print(_u("ObjTypeSpec: func %s, block %d, guarded properties:\n"),
  909. this->func->GetDebugNumberSet(debugStringBuffer), block->GetBlockNum());
  910. if (stackSymToGuardedProperties)
  911. {
  912. stackSymToGuardedProperties->Dump();
  913. Output::Print(_u("\n"));
  914. }
  915. else
  916. {
  917. Output::Print(_u("null\n"));
  918. }
  919. }
  920. if (PHASE_TRACE(Js::TraceObjTypeSpecWriteGuardsPhase, this->func))
  921. {
  922. Output::Print(_u("ObjTypeSpec: func %s, block %d, write guards: "),
  923. this->func->GetDebugNumberSet(debugStringBuffer), block->GetBlockNum());
  924. if (stackSymToWriteGuardsMap)
  925. {
  926. Output::Print(_u("\n"));
  927. stackSymToWriteGuardsMap->Dump();
  928. Output::Print(_u("\n"));
  929. }
  930. else
  931. {
  932. Output::Print(_u("null\n"));
  933. }
  934. }
  935. #endif
  936. }
  937. #if DBG
  938. if (tempObjectVerifyTracker)
  939. {
  940. FOREACH_DEAD_SUCCESSOR_BLOCK(deadBlockSucc, block)
  941. {
  942. Assert(deadBlockSucc->tempObjectVerifyTracker || deadBlockSucc->isLoopHeader);
  943. if (deadBlockSucc->tempObjectVerifyTracker != nullptr)
  944. {
  945. Assert((deadBlockSucc->loop != nullptr) == deadBlockSucc->tempObjectVerifyTracker->HasTempTransferDependencies());
  946. // Dead block don't effect non temp use, we only need to carry the removed use bit vector forward
  947. // and put all the upward exposed use to the set that we might found out to be mark temp
  948. // after globopt
  949. tempObjectVerifyTracker->MergeDeadData(deadBlockSucc);
  950. }
  951. if (!byteCodeUpwardExposedUsed)
  952. {
  953. if (!deadBlockSucc->isLoopHeader && deadBlockSucc->backwardPassCurrentLoop == this->currentPrePassLoop)
  954. {
  955. Assert(deadBlockSucc->GetDataUseCount() != 0);
  956. if (deadBlockSucc->DecrementDataUseCount() == 0)
  957. {
  958. this->DeleteBlockData(deadBlockSucc);
  959. }
  960. }
  961. }
  962. }
  963. NEXT_DEAD_SUCCESSOR_BLOCK;
  964. }
  965. #endif
  966. if (byteCodeUpwardExposedUsed)
  967. {
  968. FOREACH_DEAD_SUCCESSOR_BLOCK(deadBlockSucc, block)
  969. {
  970. Assert(deadBlockSucc->byteCodeUpwardExposedUsed || deadBlockSucc->isLoopHeader);
  971. if (deadBlockSucc->byteCodeUpwardExposedUsed)
  972. {
  973. byteCodeUpwardExposedUsed->Or(deadBlockSucc->byteCodeUpwardExposedUsed);
  974. if (this->tag == Js::DeadStorePhase)
  975. {
  976. #if DBG
  977. for (uint i = 0; i < byteCodeLocalsCount; i++)
  978. {
  979. if (byteCodeRestoreSyms[i] == nullptr)
  980. {
  981. byteCodeRestoreSyms[i] = deadBlockSucc->byteCodeRestoreSyms[i];
  982. }
  983. else
  984. {
  985. Assert(deadBlockSucc->byteCodeRestoreSyms[i] == nullptr
  986. || byteCodeRestoreSyms[i] == deadBlockSucc->byteCodeRestoreSyms[i]);
  987. }
  988. }
  989. #endif
  990. }
  991. }
  992. if (!deadBlockSucc->isLoopHeader && deadBlockSucc->backwardPassCurrentLoop == this->currentPrePassLoop)
  993. {
  994. Assert(deadBlockSucc->GetDataUseCount() != 0);
  995. if (deadBlockSucc->DecrementDataUseCount() == 0)
  996. {
  997. this->DeleteBlockData(deadBlockSucc);
  998. }
  999. }
  1000. }
  1001. NEXT_DEAD_SUCCESSOR_BLOCK;
  1002. }
  1003. if (block->isLoopHeader)
  1004. {
  1005. this->DeleteBlockData(block);
  1006. }
  1007. else
  1008. {
  1009. if(block->GetDataUseCount() == 0)
  1010. {
  1011. Assert(block->slotDeadStoreCandidates == nullptr);
  1012. Assert(block->tempNumberTracker == nullptr);
  1013. Assert(block->tempObjectTracker == nullptr);
  1014. Assert(block->tempObjectVerifyTracker == nullptr);
  1015. Assert(block->upwardExposedUses == nullptr);
  1016. Assert(block->upwardExposedFields == nullptr);
  1017. Assert(block->typesNeedingKnownObjectLayout == nullptr);
  1018. Assert(block->fieldHoistCandidates == nullptr);
  1019. // byteCodeUpwardExposedUsed is required to populate the writeThroughSymbolsSet for the try region in the backwards pass
  1020. Assert(block->byteCodeUpwardExposedUsed == nullptr || (this->tag == Js::BackwardPhase && this->func->HasTry() && this->func->DoOptimizeTry()));
  1021. Assert(block->byteCodeRestoreSyms == nullptr);
  1022. Assert(block->stackSymToFinalType == nullptr);
  1023. Assert(block->stackSymToGuardedProperties == nullptr);
  1024. Assert(block->stackSymToWriteGuardsMap == nullptr);
  1025. Assert(block->cloneStrCandidates == nullptr);
  1026. Assert(block->noImplicitCallUses == nullptr);
  1027. Assert(block->noImplicitCallNoMissingValuesUses == nullptr);
  1028. Assert(block->noImplicitCallNativeArrayUses == nullptr);
  1029. Assert(block->noImplicitCallJsArrayHeadSegmentSymUses == nullptr);
  1030. Assert(block->noImplicitCallArrayLengthSymUses == nullptr);
  1031. Assert(block->couldRemoveNegZeroBailoutForDef == nullptr);
  1032. }
  1033. else
  1034. {
  1035. // The collection pass sometimes does not know whether it can delete a successor block's data, so it may leave some
  1036. // blocks with data intact. Delete the block data now.
  1037. Assert(block->backwardPassCurrentLoop);
  1038. Assert(block->backwardPassCurrentLoop->hasDeadStoreCollectionPass);
  1039. Assert(!block->backwardPassCurrentLoop->hasDeadStorePrepass);
  1040. DeleteBlockData(block);
  1041. }
  1042. block->backwardPassCurrentLoop = this->currentPrePassLoop;
  1043. if (this->DoByteCodeUpwardExposedUsed()
  1044. #if DBG
  1045. || this->DoMarkTempObjectVerify()
  1046. #endif
  1047. )
  1048. {
  1049. block->SetDataUseCount(block->GetPredList()->Count() + block->GetDeadPredList()->Count());
  1050. }
  1051. else
  1052. {
  1053. block->SetDataUseCount(block->GetPredList()->Count());
  1054. }
  1055. }
  1056. block->upwardExposedUses = upwardExposedUses;
  1057. block->upwardExposedFields = upwardExposedFields;
  1058. block->typesNeedingKnownObjectLayout = typesNeedingKnownObjectLayout;
  1059. block->fieldHoistCandidates = fieldHoistCandidates;
  1060. block->byteCodeUpwardExposedUsed = byteCodeUpwardExposedUsed;
  1061. #if DBG
  1062. block->byteCodeRestoreSyms = byteCodeRestoreSyms;
  1063. #endif
  1064. block->slotDeadStoreCandidates = slotDeadStoreCandidates;
  1065. block->tempNumberTracker = tempNumberTracker;
  1066. block->tempObjectTracker = tempObjectTracker;
  1067. #if DBG
  1068. block->tempObjectVerifyTracker = tempObjectVerifyTracker;
  1069. #endif
  1070. block->stackSymToFinalType = stackSymToFinalType;
  1071. block->stackSymToGuardedProperties = stackSymToGuardedProperties;
  1072. block->stackSymToWriteGuardsMap = stackSymToWriteGuardsMap;
  1073. block->cloneStrCandidates = cloneStrCandidates;
  1074. block->noImplicitCallUses = noImplicitCallUses;
  1075. block->noImplicitCallNoMissingValuesUses = noImplicitCallNoMissingValuesUses;
  1076. block->noImplicitCallNativeArrayUses = noImplicitCallNativeArrayUses;
  1077. block->noImplicitCallJsArrayHeadSegmentSymUses = noImplicitCallJsArrayHeadSegmentSymUses;
  1078. block->noImplicitCallArrayLengthSymUses = noImplicitCallArrayLengthSymUses;
  1079. block->couldRemoveNegZeroBailoutForDef = couldRemoveNegZeroBailoutForDef;
  1080. }
  1081. ObjTypeGuardBucket
  1082. BackwardPass::MergeGuardedProperties(ObjTypeGuardBucket bucket1, ObjTypeGuardBucket bucket2)
  1083. {
  1084. BVSparse<JitArenaAllocator> *guardedPropertyOps1 = bucket1.GetGuardedPropertyOps();
  1085. BVSparse<JitArenaAllocator> *guardedPropertyOps2 = bucket2.GetGuardedPropertyOps();
  1086. Assert(guardedPropertyOps1 || guardedPropertyOps2);
  1087. BVSparse<JitArenaAllocator> *mergedPropertyOps;
  1088. if (guardedPropertyOps1)
  1089. {
  1090. mergedPropertyOps = guardedPropertyOps1->CopyNew();
  1091. if (guardedPropertyOps2)
  1092. {
  1093. mergedPropertyOps->Or(guardedPropertyOps2);
  1094. }
  1095. }
  1096. else
  1097. {
  1098. mergedPropertyOps = guardedPropertyOps2->CopyNew();
  1099. }
  1100. ObjTypeGuardBucket bucket;
  1101. bucket.SetGuardedPropertyOps(mergedPropertyOps);
  1102. JITTypeHolder monoGuardType = bucket1.GetMonoGuardType();
  1103. if (monoGuardType != nullptr)
  1104. {
  1105. Assert(!bucket2.NeedsMonoCheck() || monoGuardType == bucket2.GetMonoGuardType());
  1106. }
  1107. else
  1108. {
  1109. monoGuardType = bucket2.GetMonoGuardType();
  1110. }
  1111. bucket.SetMonoGuardType(monoGuardType);
  1112. return bucket;
  1113. }
  1114. ObjWriteGuardBucket
  1115. BackwardPass::MergeWriteGuards(ObjWriteGuardBucket bucket1, ObjWriteGuardBucket bucket2)
  1116. {
  1117. BVSparse<JitArenaAllocator> *writeGuards1 = bucket1.GetWriteGuards();
  1118. BVSparse<JitArenaAllocator> *writeGuards2 = bucket2.GetWriteGuards();
  1119. Assert(writeGuards1 || writeGuards2);
  1120. BVSparse<JitArenaAllocator> *mergedWriteGuards;
  1121. if (writeGuards1)
  1122. {
  1123. mergedWriteGuards = writeGuards1->CopyNew();
  1124. if (writeGuards2)
  1125. {
  1126. mergedWriteGuards->Or(writeGuards2);
  1127. }
  1128. }
  1129. else
  1130. {
  1131. mergedWriteGuards = writeGuards2->CopyNew();
  1132. }
  1133. ObjWriteGuardBucket bucket;
  1134. bucket.SetWriteGuards(mergedWriteGuards);
  1135. return bucket;
  1136. }
  1137. void
  1138. BackwardPass::DeleteBlockData(BasicBlock * block)
  1139. {
  1140. if (block->slotDeadStoreCandidates != nullptr)
  1141. {
  1142. JitAdelete(this->tempAlloc, block->slotDeadStoreCandidates);
  1143. block->slotDeadStoreCandidates = nullptr;
  1144. }
  1145. if (block->tempNumberTracker != nullptr)
  1146. {
  1147. JitAdelete(this->tempAlloc, block->tempNumberTracker);
  1148. block->tempNumberTracker = nullptr;
  1149. }
  1150. if (block->tempObjectTracker != nullptr)
  1151. {
  1152. JitAdelete(this->tempAlloc, block->tempObjectTracker);
  1153. block->tempObjectTracker = nullptr;
  1154. }
  1155. #if DBG
  1156. if (block->tempObjectVerifyTracker != nullptr)
  1157. {
  1158. JitAdelete(this->tempAlloc, block->tempObjectVerifyTracker);
  1159. block->tempObjectVerifyTracker = nullptr;
  1160. }
  1161. #endif
  1162. if (block->stackSymToFinalType != nullptr)
  1163. {
  1164. block->stackSymToFinalType->Delete();
  1165. block->stackSymToFinalType = nullptr;
  1166. }
  1167. if (block->stackSymToGuardedProperties != nullptr)
  1168. {
  1169. block->stackSymToGuardedProperties->Delete();
  1170. block->stackSymToGuardedProperties = nullptr;
  1171. }
  1172. if (block->stackSymToWriteGuardsMap != nullptr)
  1173. {
  1174. block->stackSymToWriteGuardsMap->Delete();
  1175. block->stackSymToWriteGuardsMap = nullptr;
  1176. }
  1177. if (block->cloneStrCandidates != nullptr)
  1178. {
  1179. Assert(this->tag == Js::BackwardPhase);
  1180. JitAdelete(this->globOpt->alloc, block->cloneStrCandidates);
  1181. block->cloneStrCandidates = nullptr;
  1182. }
  1183. if (block->noImplicitCallUses != nullptr)
  1184. {
  1185. JitAdelete(this->tempAlloc, block->noImplicitCallUses);
  1186. block->noImplicitCallUses = nullptr;
  1187. }
  1188. if (block->noImplicitCallNoMissingValuesUses != nullptr)
  1189. {
  1190. JitAdelete(this->tempAlloc, block->noImplicitCallNoMissingValuesUses);
  1191. block->noImplicitCallNoMissingValuesUses = nullptr;
  1192. }
  1193. if (block->noImplicitCallNativeArrayUses != nullptr)
  1194. {
  1195. JitAdelete(this->tempAlloc, block->noImplicitCallNativeArrayUses);
  1196. block->noImplicitCallNativeArrayUses = nullptr;
  1197. }
  1198. if (block->noImplicitCallJsArrayHeadSegmentSymUses != nullptr)
  1199. {
  1200. JitAdelete(this->tempAlloc, block->noImplicitCallJsArrayHeadSegmentSymUses);
  1201. block->noImplicitCallJsArrayHeadSegmentSymUses = nullptr;
  1202. }
  1203. if (block->noImplicitCallArrayLengthSymUses != nullptr)
  1204. {
  1205. JitAdelete(this->tempAlloc, block->noImplicitCallArrayLengthSymUses);
  1206. block->noImplicitCallArrayLengthSymUses = nullptr;
  1207. }
  1208. if (block->upwardExposedUses != nullptr)
  1209. {
  1210. JitArenaAllocator *upwardExposedArena = (this->tag == Js::BackwardPhase) ? this->globOpt->alloc : this->tempAlloc;
  1211. JitAdelete(upwardExposedArena, block->upwardExposedUses);
  1212. block->upwardExposedUses = nullptr;
  1213. }
  1214. if (block->upwardExposedFields != nullptr)
  1215. {
  1216. JitArenaAllocator *upwardExposedArena = (this->tag == Js::BackwardPhase) ? this->globOpt->alloc : this->tempAlloc;
  1217. JitAdelete(upwardExposedArena, block->upwardExposedFields);
  1218. block->upwardExposedFields = nullptr;
  1219. }
  1220. if (block->typesNeedingKnownObjectLayout != nullptr)
  1221. {
  1222. JitAdelete(this->tempAlloc, block->typesNeedingKnownObjectLayout);
  1223. block->typesNeedingKnownObjectLayout = nullptr;
  1224. }
  1225. if (block->fieldHoistCandidates != nullptr)
  1226. {
  1227. JitAdelete(this->tempAlloc, block->fieldHoistCandidates);
  1228. block->fieldHoistCandidates = nullptr;
  1229. }
  1230. if (block->byteCodeUpwardExposedUsed != nullptr)
  1231. {
  1232. JitAdelete(this->tempAlloc, block->byteCodeUpwardExposedUsed);
  1233. block->byteCodeUpwardExposedUsed = nullptr;
  1234. #if DBG
  1235. JitAdeleteArray(this->tempAlloc, func->GetJITFunctionBody()->GetLocalsCount(), block->byteCodeRestoreSyms);
  1236. block->byteCodeRestoreSyms = nullptr;
  1237. #endif
  1238. }
  1239. if (block->couldRemoveNegZeroBailoutForDef != nullptr)
  1240. {
  1241. JitAdelete(this->tempAlloc, block->couldRemoveNegZeroBailoutForDef);
  1242. block->couldRemoveNegZeroBailoutForDef = nullptr;
  1243. }
  1244. }
  1245. void
  1246. BackwardPass::ProcessLoopCollectionPass(BasicBlock *const lastBlock)
  1247. {
  1248. // The collection pass is done before the prepass, to collect and propagate a minimal amount of information into nested
  1249. // loops, for cases where the information is needed to make appropriate decisions on changing other state. For instance,
  1250. // bailouts in nested loops need to be able to see all byte-code uses that are exposed to the bailout so that the
  1251. // appropriate syms can be made upwards-exposed during the prepass. Byte-code uses that occur before the bailout in the
  1252. // flow, or byte-code uses after the current loop, are not seen by bailouts inside the loop. The collection pass collects
  1253. // byte-code uses and propagates them at least into each loop's header such that when bailouts are processed in the prepass,
  1254. // they will have full visibility of byte-code upwards-exposed uses.
  1255. //
  1256. // For the collection pass, one pass is needed to collect all byte-code uses of a loop to the loop header. If the loop has
  1257. // inner loops, another pass is needed to propagate byte-code uses in the outer loop into the inner loop's header, since
  1258. // some byte-code uses may occur before the inner loop in the flow. The process continues recursively for inner loops. The
  1259. // second pass only needs to walk as far as the first inner loop's header, since the purpose of that pass is only to
  1260. // propagate collected information into the inner loops' headers.
  1261. //
  1262. // Consider the following case:
  1263. // (Block 1, Loop 1 header)
  1264. // ByteCodeUses s1
  1265. // (Block 2, Loop 2 header)
  1266. // (Block 3, Loop 3 header)
  1267. // (Block 4)
  1268. // BailOut
  1269. // (Block 5, Loop 3 back-edge)
  1270. // (Block 6, Loop 2 back-edge)
  1271. // (Block 7, Loop 1 back-edge)
  1272. //
  1273. // Assume that the exit branch in each of these loops is in the loop's header block, like a 'while' loop. For the byte-code
  1274. // use of 's1' to become visible to the bailout in the innermost loop, we need to walk the following blocks:
  1275. // - Collection pass
  1276. // - 7, 6, 5, 4, 3, 2, 1, 7 - block 1 is the first block in loop 1 that sees 's1', and since block 7 has block 1 as its
  1277. // successor, block 7 sees 's1' now as well
  1278. // - 6, 5, 4, 3, 2, 6 - block 2 is the first block in loop 2 that sees 's1', and since block 6 has block 2 as its
  1279. // successor, block 6 sees 's1' now as well
  1280. // - 5, 4, 3 - block 3 is the first block in loop 3 that sees 's1'
  1281. // - The collection pass does not have to do another pass through the innermost loop because it does not have any inner
  1282. // loops of its own. It's sufficient to propagate the byte-code uses up to the loop header of each loop, as the
  1283. // prepass will do the remaining propagation.
  1284. // - Prepass
  1285. // - 7, 6, 5, 4, ... - since block 5 has block 3 as its successor, block 5 sees 's1', and so does block 4. So, the bailout
  1286. // finally sees 's1' as a byte-code upwards-exposed use.
  1287. //
  1288. // The collection pass walks as described above, and consists of one pass, followed by another pass if there are inner
  1289. // loops. The second pass only walks up to the first inner loop's header block, and during this pass upon reaching an inner
  1290. // loop, the algorithm goes recursively for that inner loop, and once it returns, the second pass continues from above that
  1291. // inner loop. Each bullet of the walk in the example above is a recursive call to ProcessLoopCollectionPass, except the
  1292. // first line, which is the initial call.
  1293. //
  1294. // Imagine the whole example above is inside another loop, and at the bottom of that loop there is an assignment to 's1'. If
  1295. // the bailout is the only use of 's1', then it needs to register 's1' as a use in the prepass to prevent treating the
  1296. // assignment to 's1' as a dead store.
  1297. Assert(tag == Js::DeadStorePhase);
  1298. Assert(IsCollectionPass());
  1299. Assert(lastBlock);
  1300. Loop *const collectionPassLoop = lastBlock->loop;
  1301. Assert(collectionPassLoop);
  1302. Assert(!collectionPassLoop->hasDeadStoreCollectionPass);
  1303. collectionPassLoop->hasDeadStoreCollectionPass = true;
  1304. Loop *const previousPrepassLoop = currentPrePassLoop;
  1305. currentPrePassLoop = collectionPassLoop;
  1306. Assert(IsPrePass());
  1307. // First pass
  1308. BasicBlock *firstInnerLoopHeader = nullptr;
  1309. {
  1310. #if DBG_DUMP
  1311. if(IsTraceEnabled())
  1312. {
  1313. Output::Print(_u("******* COLLECTION PASS 1 START: Loop %u ********\n"), collectionPassLoop->GetLoopTopInstr()->m_id);
  1314. }
  1315. #endif
  1316. FOREACH_BLOCK_BACKWARD_IN_RANGE_DEAD_OR_ALIVE(block, lastBlock, nullptr)
  1317. {
  1318. ProcessBlock(block);
  1319. if(block->isLoopHeader)
  1320. {
  1321. if(block->loop == collectionPassLoop)
  1322. {
  1323. break;
  1324. }
  1325. // Keep track of the first inner loop's header for the second pass, which need only walk up to that block
  1326. firstInnerLoopHeader = block;
  1327. }
  1328. } NEXT_BLOCK_BACKWARD_IN_RANGE_DEAD_OR_ALIVE;
  1329. #if DBG_DUMP
  1330. if(IsTraceEnabled())
  1331. {
  1332. Output::Print(_u("******** COLLECTION PASS 1 END: Loop %u *********\n"), collectionPassLoop->GetLoopTopInstr()->m_id);
  1333. }
  1334. #endif
  1335. }
  1336. // Second pass, only needs to run if there are any inner loops, to propagate collected information into those loops
  1337. if(firstInnerLoopHeader)
  1338. {
  1339. #if DBG_DUMP
  1340. if(IsTraceEnabled())
  1341. {
  1342. Output::Print(_u("******* COLLECTION PASS 2 START: Loop %u ********\n"), collectionPassLoop->GetLoopTopInstr()->m_id);
  1343. }
  1344. #endif
  1345. FOREACH_BLOCK_BACKWARD_IN_RANGE_DEAD_OR_ALIVE(block, lastBlock, firstInnerLoopHeader)
  1346. {
  1347. Loop *const loop = block->loop;
  1348. if(loop && loop != collectionPassLoop && !loop->hasDeadStoreCollectionPass)
  1349. {
  1350. // About to make a recursive call, so when jitting in the foreground, probe the stack
  1351. if(!func->IsBackgroundJIT())
  1352. {
  1353. PROBE_STACK(func->GetScriptContext(), Js::Constants::MinStackDefault);
  1354. }
  1355. ProcessLoopCollectionPass(block);
  1356. // The inner loop's collection pass would have propagated collected information to its header block. Skip to the
  1357. // inner loop's header block and continue from the block before it.
  1358. block = loop->GetHeadBlock();
  1359. Assert(block->isLoopHeader);
  1360. continue;
  1361. }
  1362. ProcessBlock(block);
  1363. } NEXT_BLOCK_BACKWARD_IN_RANGE_DEAD_OR_ALIVE;
  1364. #if DBG_DUMP
  1365. if(IsTraceEnabled())
  1366. {
  1367. Output::Print(_u("******** COLLECTION PASS 2 END: Loop %u *********\n"), collectionPassLoop->GetLoopTopInstr()->m_id);
  1368. }
  1369. #endif
  1370. }
  1371. currentPrePassLoop = previousPrepassLoop;
  1372. }
  1373. void
  1374. BackwardPass::ProcessLoop(BasicBlock * lastBlock)
  1375. {
  1376. #if DBG_DUMP
  1377. if (this->IsTraceEnabled())
  1378. {
  1379. Output::Print(_u("******* PREPASS START ********\n"));
  1380. }
  1381. #endif
  1382. Loop *loop = lastBlock->loop;
  1383. // This code doesn't work quite as intended. It is meant to capture fields that are live out of a loop to limit the
  1384. // number of implicit call bailouts the forward pass must create (only compiler throughput optimization, no impact
  1385. // on emitted code), but because it looks only at the lexically last block in the loop, it does the right thing only
  1386. // for do-while loops. For other loops (for and while) the last block does not exit the loop. Even for do-while loops
  1387. // this tracking can have the adverse effect of killing fields that should stay live after copy prop. Disabled by default.
  1388. // Left in under a flag, in case we find compiler throughput issues and want to do additional experiments.
  1389. if (PHASE_ON(Js::LiveOutFieldsPhase, this->func))
  1390. {
  1391. if (this->globOpt->DoFieldOpts(loop) || this->globOpt->DoFieldRefOpts(loop))
  1392. {
  1393. // Get the live-out set at the loop bottom.
  1394. // This may not be the only loop exit, but all loop exits either leave the function or pass through here.
  1395. // In the forward pass, we'll use this set to trim the live fields on exit from the loop
  1396. // in order to limit the number of bailout points following the loop.
  1397. BVSparse<JitArenaAllocator> *bv = JitAnew(this->func->m_fg->alloc, BVSparse<JitArenaAllocator>, this->func->m_fg->alloc);
  1398. FOREACH_SUCCESSOR_BLOCK(blockSucc, lastBlock)
  1399. {
  1400. if (blockSucc->loop != loop)
  1401. {
  1402. // Would like to assert this, but in strange exprgen cases involving "break LABEL" in nested
  1403. // loops the loop graph seems to get confused.
  1404. //Assert(!blockSucc->loop || blockSucc->loop->IsDescendentOrSelf(loop));
  1405. Assert(!blockSucc->loop || blockSucc->loop->hasDeadStorePrepass);
  1406. bv->Or(blockSucc->upwardExposedFields);
  1407. }
  1408. }
  1409. NEXT_SUCCESSOR_BLOCK;
  1410. lastBlock->loop->liveOutFields = bv;
  1411. }
  1412. }
  1413. if(tag == Js::DeadStorePhase && !loop->hasDeadStoreCollectionPass)
  1414. {
  1415. Assert(!IsCollectionPass());
  1416. Assert(!IsPrePass());
  1417. isCollectionPass = true;
  1418. ProcessLoopCollectionPass(lastBlock);
  1419. isCollectionPass = false;
  1420. }
  1421. Assert(!this->IsPrePass());
  1422. this->currentPrePassLoop = loop;
  1423. FOREACH_BLOCK_BACKWARD_IN_RANGE_DEAD_OR_ALIVE(block, lastBlock, nullptr)
  1424. {
  1425. this->ProcessBlock(block);
  1426. if (block->isLoopHeader && block->loop == lastBlock->loop)
  1427. {
  1428. Assert(block->fieldHoistCandidates == nullptr);
  1429. break;
  1430. }
  1431. }
  1432. NEXT_BLOCK_BACKWARD_IN_RANGE_DEAD_OR_ALIVE;
  1433. this->currentPrePassLoop = nullptr;
  1434. Assert(lastBlock);
  1435. __analysis_assume(lastBlock);
  1436. lastBlock->loop->hasDeadStorePrepass = true;
  1437. #if DBG_DUMP
  1438. if (this->IsTraceEnabled())
  1439. {
  1440. Output::Print(_u("******** PREPASS END *********\n"));
  1441. }
  1442. #endif
  1443. }
  1444. void
  1445. BackwardPass::OptBlock(BasicBlock * block)
  1446. {
  1447. this->func->ThrowIfScriptClosed();
  1448. if (block->loop && !block->loop->hasDeadStorePrepass)
  1449. {
  1450. ProcessLoop(block);
  1451. }
  1452. this->ProcessBlock(block);
  1453. if(DoTrackNegativeZero())
  1454. {
  1455. negativeZeroDoesNotMatterBySymId->ClearAll();
  1456. }
  1457. if (DoTrackBitOpsOrNumber())
  1458. {
  1459. symUsedOnlyForBitOpsBySymId->ClearAll();
  1460. symUsedOnlyForNumberBySymId->ClearAll();
  1461. }
  1462. if(DoTrackIntOverflow())
  1463. {
  1464. intOverflowDoesNotMatterBySymId->ClearAll();
  1465. if(DoTrackCompoundedIntOverflow())
  1466. {
  1467. intOverflowDoesNotMatterInRangeBySymId->ClearAll();
  1468. }
  1469. }
  1470. }
  1471. void
  1472. BackwardPass::ProcessBailOutArgObj(BailOutInfo * bailOutInfo, BVSparse<JitArenaAllocator> * byteCodeUpwardExposedUsed)
  1473. {
  1474. Assert(this->tag != Js::BackwardPhase);
  1475. if (this->globOpt->TrackArgumentsObject() && bailOutInfo->capturedValues.argObjSyms)
  1476. {
  1477. FOREACH_BITSET_IN_SPARSEBV(symId, bailOutInfo->capturedValues.argObjSyms)
  1478. {
  1479. if (byteCodeUpwardExposedUsed->TestAndClear(symId))
  1480. {
  1481. if (bailOutInfo->usedCapturedValues.argObjSyms == nullptr)
  1482. {
  1483. bailOutInfo->usedCapturedValues.argObjSyms = JitAnew(this->func->m_alloc,
  1484. BVSparse<JitArenaAllocator>, this->func->m_alloc);
  1485. }
  1486. bailOutInfo->usedCapturedValues.argObjSyms->Set(symId);
  1487. }
  1488. }
  1489. NEXT_BITSET_IN_SPARSEBV;
  1490. }
  1491. if (bailOutInfo->usedCapturedValues.argObjSyms)
  1492. {
  1493. byteCodeUpwardExposedUsed->Minus(bailOutInfo->usedCapturedValues.argObjSyms);
  1494. }
  1495. }
  1496. void
  1497. BackwardPass::ProcessBailOutConstants(BailOutInfo * bailOutInfo, BVSparse<JitArenaAllocator> * byteCodeUpwardExposedUsed, BVSparse<JitArenaAllocator>* bailoutReferencedArgSymsBv)
  1498. {
  1499. Assert(this->tag != Js::BackwardPhase);
  1500. // Remove constants that we are already going to restore
  1501. SListBase<ConstantStackSymValue> * usedConstantValues = &bailOutInfo->usedCapturedValues.constantValues;
  1502. FOREACH_SLISTBASE_ENTRY(ConstantStackSymValue, value, usedConstantValues)
  1503. {
  1504. byteCodeUpwardExposedUsed->Clear(value.Key()->m_id);
  1505. bailoutReferencedArgSymsBv->Clear(value.Key()->m_id);
  1506. }
  1507. NEXT_SLISTBASE_ENTRY;
  1508. // Find other constants that we need to restore
  1509. FOREACH_SLISTBASE_ENTRY_EDITING(ConstantStackSymValue, value, &bailOutInfo->capturedValues.constantValues, iter)
  1510. {
  1511. if (byteCodeUpwardExposedUsed->TestAndClear(value.Key()->m_id) || bailoutReferencedArgSymsBv->TestAndClear(value.Key()->m_id))
  1512. {
  1513. // Constant need to be restore, move it to the restore list
  1514. iter.MoveCurrentTo(usedConstantValues);
  1515. }
  1516. else if (!this->IsPrePass())
  1517. {
  1518. // Constants don't need to be restored, delete
  1519. iter.RemoveCurrent(this->func->m_alloc);
  1520. }
  1521. }
  1522. NEXT_SLISTBASE_ENTRY_EDITING;
  1523. }
  1524. void
  1525. BackwardPass::ProcessBailOutCopyProps(BailOutInfo * bailOutInfo, BVSparse<JitArenaAllocator> * byteCodeUpwardExposedUsed, BVSparse<JitArenaAllocator>* bailoutReferencedArgSymsBv)
  1526. {
  1527. Assert(this->tag != Js::BackwardPhase);
  1528. Assert(!this->func->GetJITFunctionBody()->IsAsmJsMode());
  1529. // Remove copy prop that we were already going to restore
  1530. SListBase<CopyPropSyms> * usedCopyPropSyms = &bailOutInfo->usedCapturedValues.copyPropSyms;
  1531. FOREACH_SLISTBASE_ENTRY(CopyPropSyms, copyPropSyms, usedCopyPropSyms)
  1532. {
  1533. byteCodeUpwardExposedUsed->Clear(copyPropSyms.Key()->m_id);
  1534. this->currentBlock->upwardExposedUses->Set(copyPropSyms.Value()->m_id);
  1535. }
  1536. NEXT_SLISTBASE_ENTRY;
  1537. JitArenaAllocator * allocator = this->func->m_alloc;
  1538. BasicBlock * block = this->currentBlock;
  1539. BVSparse<JitArenaAllocator> * upwardExposedUses = block->upwardExposedUses;
  1540. // Find other copy prop that we need to restore
  1541. FOREACH_SLISTBASE_ENTRY_EDITING(CopyPropSyms, copyPropSyms, &bailOutInfo->capturedValues.copyPropSyms, iter)
  1542. {
  1543. // Copy prop syms should be vars
  1544. Assert(!copyPropSyms.Key()->IsTypeSpec());
  1545. Assert(!copyPropSyms.Value()->IsTypeSpec());
  1546. if (byteCodeUpwardExposedUsed->TestAndClear(copyPropSyms.Key()->m_id) || bailoutReferencedArgSymsBv->TestAndClear(copyPropSyms.Key()->m_id))
  1547. {
  1548. // This copy-prop sym needs to be restored; add it to the restore list.
  1549. /*
  1550. - copyPropSyms.Key() - original sym that is byte-code upwards-exposed, its corresponding byte-code register needs
  1551. to be restored
  1552. - copyPropSyms.Value() - copy-prop sym whose value the original sym has at the point of this instruction
  1553. Heuristic:
  1554. - By default, use the copy-prop sym to restore its corresponding byte code register
  1555. - This is typically better because that allows the value of the original sym, if it's not used after the copy-prop
  1556. sym is changed, to be discarded and we only have one lifetime (the copy-prop sym's lifetime) in to deal with for
  1557. register allocation
  1558. - Additionally, if the transferring store, which caused the original sym to have the same value as the copy-prop
  1559. sym, becomes a dead store, the original sym won't actually attain the value of the copy-prop sym. In that case,
  1560. the copy-prop sym must be used to restore the byte code register corresponding to original sym.
  1561. Special case for functional correctness:
  1562. - Consider that we always use the copy-prop sym to restore, and consider the following case:
  1563. b = a
  1564. a = c * d <Pre-op bail-out>
  1565. = b
  1566. - This is rewritten by the lowerer as follows:
  1567. b = a
  1568. a = c
  1569. a = a * d <Pre-op bail-out> (to make dst and src1 the same)
  1570. = b
  1571. - The problem here is that at the point of the bail-out instruction, 'a' would be used to restore the value of 'b',
  1572. but the value of 'a' has changed before the bail-out (at 'a = c').
  1573. - In this case, we need to use 'b' (the original sym) to restore the value of 'b'. Because 'b' is upwards-exposed,
  1574. 'b = a' cannot be a dead store, therefore making it valid to use 'b' to restore.
  1575. - Use the original sym to restore when all of the following are true:
  1576. - The bailout is a pre-op bailout, and the bailout check is done after overwriting the destination
  1577. - It's an int-specialized unary or binary operation that produces a value
  1578. - The copy-prop sym is the destination of this instruction
  1579. - None of the sources are the copy-prop sym. Otherwise, the value of the copy-prop sym will be saved as
  1580. necessary by the bailout code.
  1581. */
  1582. StackSym * stackSym = copyPropSyms.Key(); // assume that we'll use the original sym to restore
  1583. SymID symId = stackSym->m_id;
  1584. IR::Instr *const instr = bailOutInfo->bailOutInstr;
  1585. StackSym *const dstSym = IR::RegOpnd::TryGetStackSym(instr->GetDst());
  1586. if(instr->GetBailOutKind() & IR::BailOutOnResultConditions &&
  1587. instr->GetByteCodeOffset() != Js::Constants::NoByteCodeOffset &&
  1588. bailOutInfo->bailOutOffset <= instr->GetByteCodeOffset() &&
  1589. dstSym &&
  1590. dstSym->IsInt32() &&
  1591. dstSym->IsTypeSpec() &&
  1592. dstSym->GetVarEquivSym(nullptr) == copyPropSyms.Value() &&
  1593. instr->GetSrc1() &&
  1594. !instr->GetDst()->IsEqual(instr->GetSrc1()) &&
  1595. !(instr->GetSrc2() && instr->GetDst()->IsEqual(instr->GetSrc2())))
  1596. {
  1597. Assert(bailOutInfo->bailOutOffset == instr->GetByteCodeOffset());
  1598. // Need to use the original sym to restore. The original sym is byte-code upwards-exposed, which is why it needs
  1599. // to be restored. Because the original sym needs to be restored and the copy-prop sym is changing here, the
  1600. // original sym must be live in some fashion at the point of this instruction, that will be verified below. The
  1601. // original sym will also be made upwards-exposed from here, so the aforementioned transferring store of the
  1602. // copy-prop sym to the original sym will not be a dead store.
  1603. }
  1604. else if (block->upwardExposedUses->Test(stackSym->m_id) && !block->upwardExposedUses->Test(copyPropSyms.Value()->m_id))
  1605. {
  1606. // Don't use the copy prop sym if it is not used and the orig sym still has uses.
  1607. // No point in extending the lifetime of the copy prop sym unnecessarily.
  1608. }
  1609. else
  1610. {
  1611. // Need to use the copy-prop sym to restore
  1612. stackSym = copyPropSyms.Value();
  1613. symId = stackSym->m_id;
  1614. }
  1615. // Prefer to restore from type-specialized versions of the sym, as that will reduce the need for potentially
  1616. // expensive ToVars that can more easily be eliminated due to being dead stores
  1617. StackSym * int32StackSym = nullptr;
  1618. StackSym * float64StackSym = nullptr;
  1619. StackSym * simd128StackSym = nullptr;
  1620. if (bailOutInfo->liveLosslessInt32Syms->Test(symId))
  1621. {
  1622. // Var version of the sym is not live, use the int32 version
  1623. int32StackSym = stackSym->GetInt32EquivSym(nullptr);
  1624. Assert(int32StackSym);
  1625. }
  1626. else if(bailOutInfo->liveFloat64Syms->Test(symId))
  1627. {
  1628. // Var/int32 version of the sym is not live, use the float64 version
  1629. float64StackSym = stackSym->GetFloat64EquivSym(nullptr);
  1630. Assert(float64StackSym);
  1631. }
  1632. #ifdef ENABLE_SIMDJS
  1633. // SIMD_JS
  1634. else if (bailOutInfo->liveSimd128F4Syms->Test(symId))
  1635. {
  1636. simd128StackSym = stackSym->GetSimd128F4EquivSym(nullptr);
  1637. }
  1638. else if (bailOutInfo->liveSimd128I4Syms->Test(symId))
  1639. {
  1640. simd128StackSym = stackSym->GetSimd128I4EquivSym(nullptr);
  1641. }
  1642. #endif
  1643. else
  1644. {
  1645. Assert(bailOutInfo->liveVarSyms->Test(symId));
  1646. }
  1647. // We did not end up using the copy prop sym. Let's make sure the use of the original sym by the bailout is captured.
  1648. if (stackSym != copyPropSyms.Value() && stackSym->HasArgSlotNum())
  1649. {
  1650. bailoutReferencedArgSymsBv->Set(stackSym->m_id);
  1651. }
  1652. if (int32StackSym != nullptr)
  1653. {
  1654. Assert(float64StackSym == nullptr);
  1655. usedCopyPropSyms->PrependNode(allocator, copyPropSyms.Key(), int32StackSym);
  1656. iter.RemoveCurrent(allocator);
  1657. upwardExposedUses->Set(int32StackSym->m_id);
  1658. }
  1659. else if (float64StackSym != nullptr)
  1660. {
  1661. // This float-specialized sym is going to be used to restore the corresponding byte-code register. Need to
  1662. // ensure that the float value can be precisely coerced back to the original Var value by requiring that it is
  1663. // specialized using BailOutNumberOnly.
  1664. float64StackSym->m_requiresBailOnNotNumber = true;
  1665. usedCopyPropSyms->PrependNode(allocator, copyPropSyms.Key(), float64StackSym);
  1666. iter.RemoveCurrent(allocator);
  1667. upwardExposedUses->Set(float64StackSym->m_id);
  1668. }
  1669. // SIMD_JS
  1670. else if (simd128StackSym != nullptr)
  1671. {
  1672. usedCopyPropSyms->PrependNode(allocator, copyPropSyms.Key(), simd128StackSym);
  1673. iter.RemoveCurrent(allocator);
  1674. upwardExposedUses->Set(simd128StackSym->m_id);
  1675. }
  1676. else
  1677. {
  1678. usedCopyPropSyms->PrependNode(allocator, copyPropSyms.Key(), stackSym);
  1679. iter.RemoveCurrent(allocator);
  1680. upwardExposedUses->Set(symId);
  1681. }
  1682. }
  1683. else if (!this->IsPrePass())
  1684. {
  1685. // Copy prop sym doesn't need to be restored, delete.
  1686. iter.RemoveCurrent(allocator);
  1687. }
  1688. }
  1689. NEXT_SLISTBASE_ENTRY_EDITING;
  1690. }
  1691. bool
  1692. BackwardPass::ProcessBailOutInfo(IR::Instr * instr)
  1693. {
  1694. if (this->tag == Js::BackwardPhase)
  1695. {
  1696. // We don't need to fill in the bailout instruction in backward pass
  1697. Assert(this->func->hasBailout || !instr->HasBailOutInfo());
  1698. Assert(!instr->HasBailOutInfo() || instr->GetBailOutInfo()->byteCodeUpwardExposedUsed == nullptr || (this->func->HasTry() && this->func->DoOptimizeTry()));
  1699. if (instr->IsByteCodeUsesInstr())
  1700. {
  1701. // FGPeeps inserts bytecodeuses instrs with srcs. We need to look at them to set the proper
  1702. // UpwardExposedUsed info and keep the defs alive.
  1703. // The inliner inserts bytecodeuses instrs withs dsts, but we don't want to look at them for upwardExposedUsed
  1704. // as it would cause real defs to look dead. We use these for bytecodeUpwardExposedUsed info only, which is needed
  1705. // in the dead-store pass only.
  1706. //
  1707. // Handle the source side.
  1708. IR::ByteCodeUsesInstr *byteCodeUsesInstr = instr->AsByteCodeUsesInstr();
  1709. const BVSparse<JitArenaAllocator> * byteCodeUpwardExposedUsed = byteCodeUsesInstr->GetByteCodeUpwardExposedUsed();
  1710. if (byteCodeUpwardExposedUsed != nullptr)
  1711. {
  1712. this->currentBlock->upwardExposedUses->Or(byteCodeUpwardExposedUsed);
  1713. }
  1714. return true;
  1715. }
  1716. return false;
  1717. }
  1718. if (instr->IsByteCodeUsesInstr())
  1719. {
  1720. Assert(instr->m_opcode == Js::OpCode::ByteCodeUses);
  1721. #if DBG
  1722. if (this->DoMarkTempObjectVerify() && (this->currentBlock->isDead || !this->func->hasBailout))
  1723. {
  1724. if (IsCollectionPass())
  1725. {
  1726. if (!this->func->hasBailout)
  1727. {
  1728. // Prevent byte code uses from being remove on collection pass for mark temp object verify
  1729. // if we don't have any bailout
  1730. return true;
  1731. }
  1732. }
  1733. else
  1734. {
  1735. this->currentBlock->tempObjectVerifyTracker->NotifyDeadByteCodeUses(instr);
  1736. }
  1737. }
  1738. #endif
  1739. if (this->func->hasBailout)
  1740. {
  1741. Assert(this->DoByteCodeUpwardExposedUsed());
  1742. // Just collect the byte code uses, and remove the instruction
  1743. // We are going backward, process the dst first and then the src
  1744. IR::Opnd * dst = instr->GetDst();
  1745. if (dst)
  1746. {
  1747. IR::RegOpnd * dstRegOpnd = dst->AsRegOpnd();
  1748. StackSym * dstStackSym = dstRegOpnd->m_sym->AsStackSym();
  1749. Assert(!dstRegOpnd->GetIsJITOptimizedReg());
  1750. Assert(dstStackSym->GetByteCodeRegSlot() != Js::Constants::NoRegister);
  1751. if (dstStackSym->GetType() != TyVar)
  1752. {
  1753. dstStackSym = dstStackSym->GetVarEquivSym(nullptr);
  1754. }
  1755. // If the current region is a Try, symbols in its write-through set shouldn't be cleared.
  1756. // Otherwise, symbols in the write-through set of the first try ancestor shouldn't be cleared.
  1757. if (!this->currentRegion ||
  1758. !this->CheckWriteThroughSymInRegion(this->currentRegion, dstStackSym))
  1759. {
  1760. this->currentBlock->byteCodeUpwardExposedUsed->Clear(dstStackSym->m_id);
  1761. #if DBG
  1762. // We can only track first level function stack syms right now
  1763. if (dstStackSym->GetByteCodeFunc() == this->func)
  1764. {
  1765. this->currentBlock->byteCodeRestoreSyms[dstStackSym->GetByteCodeRegSlot()] = nullptr;
  1766. }
  1767. #endif
  1768. }
  1769. }
  1770. IR::ByteCodeUsesInstr *byteCodeUsesInstr = instr->AsByteCodeUsesInstr();
  1771. if (byteCodeUsesInstr->GetByteCodeUpwardExposedUsed() != nullptr)
  1772. {
  1773. this->currentBlock->byteCodeUpwardExposedUsed->Or(byteCodeUsesInstr->GetByteCodeUpwardExposedUsed());
  1774. #if DBG
  1775. FOREACH_BITSET_IN_SPARSEBV(symId, byteCodeUsesInstr->GetByteCodeUpwardExposedUsed())
  1776. {
  1777. StackSym * stackSym = this->func->m_symTable->FindStackSym(symId);
  1778. Assert(!stackSym->IsTypeSpec());
  1779. // We can only track first level function stack syms right now
  1780. if (stackSym->GetByteCodeFunc() == this->func)
  1781. {
  1782. Js::RegSlot byteCodeRegSlot = stackSym->GetByteCodeRegSlot();
  1783. Assert(byteCodeRegSlot != Js::Constants::NoRegister);
  1784. if (this->currentBlock->byteCodeRestoreSyms[byteCodeRegSlot] != stackSym)
  1785. {
  1786. AssertMsg(this->currentBlock->byteCodeRestoreSyms[byteCodeRegSlot] == nullptr,
  1787. "Can't have two active lifetime for the same byte code register");
  1788. this->currentBlock->byteCodeRestoreSyms[byteCodeRegSlot] = stackSym;
  1789. }
  1790. }
  1791. }
  1792. NEXT_BITSET_IN_SPARSEBV;
  1793. #endif
  1794. }
  1795. if(IsCollectionPass())
  1796. {
  1797. return true;
  1798. }
  1799. ProcessPendingPreOpBailOutInfo(instr);
  1800. PropertySym *propertySymUse = byteCodeUsesInstr->propertySymUse;
  1801. if (propertySymUse && !this->currentBlock->isDead)
  1802. {
  1803. this->currentBlock->upwardExposedFields->Set(propertySymUse->m_id);
  1804. }
  1805. if (this->IsPrePass())
  1806. {
  1807. // Don't remove the instruction yet if we are in the prepass
  1808. // But tell the caller we don't need to process the instruction any more
  1809. return true;
  1810. }
  1811. }
  1812. this->currentBlock->RemoveInstr(instr);
  1813. return true;
  1814. }
  1815. if(IsCollectionPass())
  1816. {
  1817. return false;
  1818. }
  1819. if (instr->HasBailOutInfo())
  1820. {
  1821. Assert(this->func->hasBailout);
  1822. Assert(this->DoByteCodeUpwardExposedUsed());
  1823. BailOutInfo * bailOutInfo = instr->GetBailOutInfo();
  1824. // Only process the bailout info if this is the main bailout point (instead of shared)
  1825. if (bailOutInfo->bailOutInstr == instr)
  1826. {
  1827. if(instr->GetByteCodeOffset() == Js::Constants::NoByteCodeOffset ||
  1828. bailOutInfo->bailOutOffset > instr->GetByteCodeOffset())
  1829. {
  1830. // Currently, we only have post-op bailout with BailOutOnImplicitCalls
  1831. // or JIT inserted operation (which no byte code offsets).
  1832. // If there are other bailouts that we want to bailout after the operation,
  1833. // we have to make sure that it still doesn't do the implicit call
  1834. // if it is done on the stack object.
  1835. // Otherwise, the stack object will be passed to the implicit call functions.
  1836. Assert(instr->GetByteCodeOffset() == Js::Constants::NoByteCodeOffset
  1837. || (instr->GetBailOutKind() & ~IR::BailOutKindBits) == IR::BailOutOnImplicitCalls
  1838. || (instr->GetBailOutKind() & ~IR::BailOutKindBits) == IR::BailOutInvalid);
  1839. // This instruction bails out to a later byte-code instruction, so process the bailout info now
  1840. ProcessBailOutInfo(instr, bailOutInfo);
  1841. }
  1842. else
  1843. {
  1844. // This instruction bails out to the equivalent byte code instruction. This instruction and ByteCodeUses
  1845. // instructions relevant to this instruction need to be processed before the bailout info for this instruction
  1846. // can be processed, so that it can be determined what byte code registers are used by the equivalent byte code
  1847. // instruction and need to be restored. Save the instruction for bailout info processing later.
  1848. Assert(bailOutInfo->bailOutOffset == instr->GetByteCodeOffset());
  1849. Assert(!preOpBailOutInstrToProcess);
  1850. preOpBailOutInstrToProcess = instr;
  1851. }
  1852. }
  1853. }
  1854. return false;
  1855. }
  1856. bool
  1857. BackwardPass::IsImplicitCallBailOutCurrentlyNeeded(IR::Instr * instr, bool mayNeedImplicitCallBailOut, bool hasLiveFields)
  1858. {
  1859. return this->globOpt->IsImplicitCallBailOutCurrentlyNeeded(
  1860. instr, nullptr, nullptr, this->currentBlock, hasLiveFields, mayNeedImplicitCallBailOut, false);
  1861. }
  1862. void
  1863. BackwardPass::DeadStoreTypeCheckBailOut(IR::Instr * instr)
  1864. {
  1865. // Good news: There are cases where the forward pass installs BailOutFailedTypeCheck, but the dead store pass
  1866. // discovers that the checked type is dead.
  1867. // Bad news: We may still need implicit call bailout, and it's up to the dead store pass to figure this out.
  1868. // Worse news: BailOutFailedTypeCheck is pre-op, and BailOutOnImplicitCall is post-op. We'll use a special
  1869. // bailout kind to indicate implicit call bailout that targets its own instruction. The lowerer will emit
  1870. // code to disable/re-enable implicit calls around the operation.
  1871. Assert(this->tag == Js::DeadStorePhase);
  1872. if (this->IsPrePass() || !instr->HasBailOutInfo())
  1873. {
  1874. return;
  1875. }
  1876. IR::BailOutKind oldBailOutKind = instr->GetBailOutKind();
  1877. if (!IR::IsTypeCheckBailOutKind(oldBailOutKind))
  1878. {
  1879. return;
  1880. }
  1881. // Either src1 or dst must be a property sym operand
  1882. Assert((instr->GetSrc1() && instr->GetSrc1()->IsSymOpnd() && instr->GetSrc1()->AsSymOpnd()->IsPropertySymOpnd()) ||
  1883. (instr->GetDst() && instr->GetDst()->IsSymOpnd() && instr->GetDst()->AsSymOpnd()->IsPropertySymOpnd()));
  1884. IR::PropertySymOpnd *propertySymOpnd =
  1885. (instr->GetDst() && instr->GetDst()->IsSymOpnd()) ? instr->GetDst()->AsPropertySymOpnd() : instr->GetSrc1()->AsPropertySymOpnd();
  1886. bool isTypeCheckProtected = false;
  1887. IR::BailOutKind bailOutKind;
  1888. if (GlobOpt::NeedsTypeCheckBailOut(instr, propertySymOpnd, propertySymOpnd == instr->GetDst(), &isTypeCheckProtected, &bailOutKind))
  1889. {
  1890. // If we installed a failed type check bailout in the forward pass, but we are now discovering that the checked
  1891. // type is dead, we may still need a bailout on failed fixed field type check. These type checks are required
  1892. // regardless of whether the checked type is dead. Hence, the bailout kind may change here.
  1893. Assert((oldBailOutKind & ~IR::BailOutKindBits) == bailOutKind ||
  1894. bailOutKind == IR::BailOutFailedFixedFieldTypeCheck || bailOutKind == IR::BailOutFailedEquivalentFixedFieldTypeCheck);
  1895. instr->SetBailOutKind(bailOutKind);
  1896. return;
  1897. }
  1898. else if (isTypeCheckProtected)
  1899. {
  1900. instr->ClearBailOutInfo();
  1901. if (preOpBailOutInstrToProcess == instr)
  1902. {
  1903. preOpBailOutInstrToProcess = nullptr;
  1904. }
  1905. return;
  1906. }
  1907. Assert(!propertySymOpnd->IsTypeCheckProtected());
  1908. // If all we're doing here is checking the type (e.g. because we've hoisted a field load or store out of the loop, but needed
  1909. // the type check to remain in the loop), and now it turns out we don't need the type checked, we can simply turn this into
  1910. // a NOP and remove the bailout.
  1911. if (instr->m_opcode == Js::OpCode::CheckObjType)
  1912. {
  1913. Assert(instr->GetDst() == nullptr && instr->GetSrc1() != nullptr && instr->GetSrc2() == nullptr);
  1914. instr->m_opcode = Js::OpCode::Nop;
  1915. instr->FreeSrc1();
  1916. instr->ClearBailOutInfo();
  1917. if (this->preOpBailOutInstrToProcess == instr)
  1918. {
  1919. this->preOpBailOutInstrToProcess = nullptr;
  1920. }
  1921. return;
  1922. }
  1923. // We don't need BailOutFailedTypeCheck but may need BailOutOnImplicitCall.
  1924. // Consider: are we in the loop landing pad? If so, no bailout, since implicit calls will be checked at
  1925. // the end of the block.
  1926. if (this->currentBlock->IsLandingPad())
  1927. {
  1928. // We're in the landing pad.
  1929. if (preOpBailOutInstrToProcess == instr)
  1930. {
  1931. preOpBailOutInstrToProcess = nullptr;
  1932. }
  1933. instr->UnlinkBailOutInfo();
  1934. return;
  1935. }
  1936. // If bailOutKind is equivTypeCheck then leave alone the bailout
  1937. if (bailOutKind == IR::BailOutFailedEquivalentTypeCheck ||
  1938. bailOutKind == IR::BailOutFailedEquivalentFixedFieldTypeCheck)
  1939. {
  1940. return;
  1941. }
  1942. // We're not checking for polymorphism, so don't let the bailout indicate that we
  1943. // detected polymorphism.
  1944. instr->GetBailOutInfo()->polymorphicCacheIndex = (uint)-1;
  1945. // Keep the mark temp object bit if it is there so that we will not remove the implicit call check
  1946. instr->SetBailOutKind(IR::BailOutOnImplicitCallsPreOp | (oldBailOutKind & IR::BailOutMarkTempObject));
  1947. }
  1948. void
  1949. BackwardPass::DeadStoreImplicitCallBailOut(IR::Instr * instr, bool hasLiveFields)
  1950. {
  1951. Assert(this->tag == Js::DeadStorePhase);
  1952. if (this->IsPrePass() || !instr->HasBailOutInfo())
  1953. {
  1954. // Don't do this in the pre-pass, because, for instance, we don't have live-on-back-edge fields yet.
  1955. return;
  1956. }
  1957. if (OpCodeAttr::BailOutRec(instr->m_opcode))
  1958. {
  1959. // This is something like OpCode::BailOutOnNotEqual. Assume it needs what it's got.
  1960. return;
  1961. }
  1962. UpdateArrayBailOutKind(instr);
  1963. // Install the implicit call PreOp for mark temp object if we need one.
  1964. IR::BailOutKind kind = instr->GetBailOutKind();
  1965. IR::BailOutKind kindNoBits = kind & ~IR::BailOutKindBits;
  1966. if ((kind & IR::BailOutMarkTempObject) != 0 && kindNoBits != IR::BailOutOnImplicitCallsPreOp)
  1967. {
  1968. Assert(kindNoBits != IR::BailOutOnImplicitCalls);
  1969. if (kindNoBits == IR::BailOutInvalid)
  1970. {
  1971. // We should only have combined with array bits
  1972. Assert((kind & ~IR::BailOutForArrayBits) == IR::BailOutMarkTempObject);
  1973. // Don't need to install if we are not going to do helper calls,
  1974. // or we are in the landingPad since implicit calls are already turned off.
  1975. if ((kind & IR::BailOutOnArrayAccessHelperCall) == 0 && !this->currentBlock->IsLandingPad())
  1976. {
  1977. kind += IR::BailOutOnImplicitCallsPreOp;
  1978. instr->SetBailOutKind(kind);
  1979. }
  1980. }
  1981. }
  1982. // Currently only try to eliminate these bailout kinds. The others are required in cases
  1983. // where we don't necessarily have live/hoisted fields.
  1984. const bool mayNeedBailOnImplicitCall = BailOutInfo::IsBailOutOnImplicitCalls(kind);
  1985. if (!mayNeedBailOnImplicitCall)
  1986. {
  1987. if (kind & IR::BailOutMarkTempObject)
  1988. {
  1989. if (kind == IR::BailOutMarkTempObject)
  1990. {
  1991. // Landing pad does not need per-instr implicit call bailouts.
  1992. Assert(this->currentBlock->IsLandingPad());
  1993. instr->ClearBailOutInfo();
  1994. if (this->preOpBailOutInstrToProcess == instr)
  1995. {
  1996. this->preOpBailOutInstrToProcess = nullptr;
  1997. }
  1998. }
  1999. else
  2000. {
  2001. // Mark temp object bit is not needed after dead store pass
  2002. instr->SetBailOutKind(kind & ~IR::BailOutMarkTempObject);
  2003. }
  2004. }
  2005. return;
  2006. }
  2007. // We have an implicit call bailout in the code, and we want to make sure that it's required.
  2008. // Do this now, because only in the dead store pass do we have complete forward and backward liveness info.
  2009. bool needsBailOutOnImplicitCall = this->IsImplicitCallBailOutCurrentlyNeeded(instr, mayNeedBailOnImplicitCall, hasLiveFields);
  2010. if(!UpdateImplicitCallBailOutKind(instr, needsBailOutOnImplicitCall))
  2011. {
  2012. instr->ClearBailOutInfo();
  2013. if (preOpBailOutInstrToProcess == instr)
  2014. {
  2015. preOpBailOutInstrToProcess = nullptr;
  2016. }
  2017. #if DBG
  2018. if (this->DoMarkTempObjectVerify())
  2019. {
  2020. this->currentBlock->tempObjectVerifyTracker->NotifyBailOutRemoval(instr, this);
  2021. }
  2022. #endif
  2023. }
  2024. }
  2025. void
  2026. BackwardPass::ProcessPendingPreOpBailOutInfo(IR::Instr *const currentInstr)
  2027. {
  2028. Assert(!IsCollectionPass());
  2029. if(!preOpBailOutInstrToProcess)
  2030. {
  2031. return;
  2032. }
  2033. IR::Instr *const prevInstr = currentInstr->m_prev;
  2034. if(prevInstr &&
  2035. prevInstr->IsByteCodeUsesInstr() &&
  2036. prevInstr->AsByteCodeUsesInstr()->GetByteCodeOffset() == preOpBailOutInstrToProcess->GetByteCodeOffset())
  2037. {
  2038. return;
  2039. }
  2040. // A pre-op bailout instruction was saved for bailout info processing after the instruction and relevant ByteCodeUses
  2041. // instructions before it have been processed. We can process the bailout info for that instruction now.
  2042. BailOutInfo *const bailOutInfo = preOpBailOutInstrToProcess->GetBailOutInfo();
  2043. Assert(bailOutInfo->bailOutInstr == preOpBailOutInstrToProcess);
  2044. Assert(bailOutInfo->bailOutOffset == preOpBailOutInstrToProcess->GetByteCodeOffset());
  2045. ProcessBailOutInfo(preOpBailOutInstrToProcess, bailOutInfo);
  2046. preOpBailOutInstrToProcess = nullptr;
  2047. }
  2048. void
  2049. BackwardPass::ProcessBailOutInfo(IR::Instr * instr, BailOutInfo * bailOutInfo)
  2050. {
  2051. /*
  2052. When we optimize functions having try-catch, we install a bailout at the starting of the catch block, namely, BailOnException.
  2053. We don't have flow edges from all the possible exception points in the try to the catch block. As a result, this bailout should
  2054. not try to restore from the constant values or copy-prop syms or the type specialized syms, as these may not necessarily be/have
  2055. the right values. For example,
  2056. //constant values
  2057. c =
  2058. try
  2059. {
  2060. <exception>
  2061. c = k (constant)
  2062. }
  2063. catch
  2064. {
  2065. BailOnException
  2066. = c <-- We need to restore c from the value outside the try.
  2067. }
  2068. //copy-prop syms
  2069. c =
  2070. try
  2071. {
  2072. b = a
  2073. <exception>
  2074. c = b
  2075. }
  2076. catch
  2077. {
  2078. BailOnException
  2079. = c <-- We really want to restore c from its original sym, and not from its copy-prop sym, a
  2080. }
  2081. //type specialized syms
  2082. a =
  2083. try
  2084. {
  2085. <exception>
  2086. a++ <-- type specializes a
  2087. }
  2088. catch
  2089. {
  2090. BailOnException
  2091. = a <-- We need to restore a from its var version.
  2092. }
  2093. */
  2094. BasicBlock * block = this->currentBlock;
  2095. BVSparse<JitArenaAllocator> * byteCodeUpwardExposedUsed = block->byteCodeUpwardExposedUsed;
  2096. Assert(bailOutInfo->bailOutInstr == instr);
  2097. // The byteCodeUpwardExposedUsed should only be assigned once. The only case which would break this
  2098. // assumption is when we are optimizing a function having try-catch. In that case, we need the
  2099. // byteCodeUpwardExposedUsed analysis in the initial backward pass too.
  2100. Assert(bailOutInfo->byteCodeUpwardExposedUsed == nullptr || (this->func->HasTry() && this->func->DoOptimizeTry()));
  2101. // Make a copy of the byteCodeUpwardExposedUsed so we can remove the constants
  2102. if (!this->IsPrePass())
  2103. {
  2104. // Create the BV of symbols that need to be restored in the BailOutRecord
  2105. byteCodeUpwardExposedUsed = byteCodeUpwardExposedUsed->CopyNew(this->func->m_alloc);
  2106. bailOutInfo->byteCodeUpwardExposedUsed = byteCodeUpwardExposedUsed;
  2107. }
  2108. else
  2109. {
  2110. // Create a temporary byteCodeUpwardExposedUsed
  2111. byteCodeUpwardExposedUsed = byteCodeUpwardExposedUsed->CopyNew(this->tempAlloc);
  2112. }
  2113. // All the register-based argument syms need to be tracked. They are either:
  2114. // 1. Referenced as constants in bailOutInfo->usedcapturedValues.constantValues
  2115. // 2. Referenced using copy prop syms in bailOutInfo->usedcapturedValues.copyPropSyms
  2116. // 3. Marked as m_isBailOutReferenced = true & added to upwardExposedUsed bit vector to ensure we do not dead store their defs.
  2117. // The third set of syms is represented by the bailoutReferencedArgSymsBv.
  2118. BVSparse<JitArenaAllocator>* bailoutReferencedArgSymsBv = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  2119. if (!this->IsPrePass())
  2120. {
  2121. bailOutInfo->IterateArgOutSyms([=](uint, uint, StackSym* sym) {
  2122. if (!sym->IsArgSlotSym())
  2123. {
  2124. bailoutReferencedArgSymsBv->Set(sym->m_id);
  2125. }
  2126. });
  2127. }
  2128. // Process Argument object first, as they can be found on the stack and don't need to rely on copy prop
  2129. this->ProcessBailOutArgObj(bailOutInfo, byteCodeUpwardExposedUsed);
  2130. if (instr->m_opcode != Js::OpCode::BailOnException) // see comment at the beginning of this function
  2131. {
  2132. this->ProcessBailOutConstants(bailOutInfo, byteCodeUpwardExposedUsed, bailoutReferencedArgSymsBv);
  2133. this->ProcessBailOutCopyProps(bailOutInfo, byteCodeUpwardExposedUsed, bailoutReferencedArgSymsBv);
  2134. }
  2135. BVSparse<JitArenaAllocator> * tempBv = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  2136. if (bailOutInfo->liveVarSyms)
  2137. {
  2138. // Prefer to restore from type-specialized versions of the sym, as that will reduce the need for potentially expensive
  2139. // ToVars that can more easily be eliminated due to being dead stores.
  2140. #if DBG
  2141. #ifdef ENABLE_SIMDJS
  2142. // SIMD_JS
  2143. // Simd128 syms should be live in at most one form
  2144. tempBv->And(bailOutInfo->liveSimd128F4Syms, bailOutInfo->liveSimd128I4Syms);
  2145. #endif
  2146. Assert(tempBv->IsEmpty());
  2147. // Verify that all syms to restore are live in some fashion
  2148. tempBv->Minus(byteCodeUpwardExposedUsed, bailOutInfo->liveVarSyms);
  2149. tempBv->Minus(bailOutInfo->liveLosslessInt32Syms);
  2150. tempBv->Minus(bailOutInfo->liveFloat64Syms);
  2151. #ifdef ENABLE_SIMDJS
  2152. tempBv->Minus(bailOutInfo->liveSimd128F4Syms);
  2153. tempBv->Minus(bailOutInfo->liveSimd128I4Syms);
  2154. #endif
  2155. Assert(tempBv->IsEmpty());
  2156. #endif
  2157. if (this->func->IsJitInDebugMode())
  2158. {
  2159. // Add to byteCodeUpwardExposedUsed the non-temp local vars used so far to restore during bail out.
  2160. // The ones that are not used so far will get their values from bytecode when we continue after bail out in interpreter.
  2161. Assert(this->func->m_nonTempLocalVars);
  2162. tempBv->And(this->func->m_nonTempLocalVars, bailOutInfo->liveVarSyms);
  2163. // Remove syms that are restored in other ways than byteCodeUpwardExposedUsed.
  2164. FOREACH_SLIST_ENTRY(ConstantStackSymValue, value, &bailOutInfo->usedCapturedValues.constantValues)
  2165. {
  2166. Assert(value.Key()->HasByteCodeRegSlot() || value.Key()->GetInstrDef()->m_opcode == Js::OpCode::BytecodeArgOutCapture);
  2167. if (value.Key()->HasByteCodeRegSlot())
  2168. {
  2169. tempBv->Clear(value.Key()->GetByteCodeRegSlot());
  2170. }
  2171. }
  2172. NEXT_SLIST_ENTRY;
  2173. FOREACH_SLIST_ENTRY(CopyPropSyms, value, &bailOutInfo->usedCapturedValues.copyPropSyms)
  2174. {
  2175. Assert(value.Key()->HasByteCodeRegSlot() || value.Key()->GetInstrDef()->m_opcode == Js::OpCode::BytecodeArgOutCapture);
  2176. if (value.Key()->HasByteCodeRegSlot())
  2177. {
  2178. tempBv->Clear(value.Key()->GetByteCodeRegSlot());
  2179. }
  2180. }
  2181. NEXT_SLIST_ENTRY;
  2182. if (bailOutInfo->usedCapturedValues.argObjSyms)
  2183. {
  2184. tempBv->Minus(bailOutInfo->usedCapturedValues.argObjSyms);
  2185. }
  2186. byteCodeUpwardExposedUsed->Or(tempBv);
  2187. }
  2188. if (instr->m_opcode != Js::OpCode::BailOnException) // see comment at the beginning of this function
  2189. {
  2190. // Int32
  2191. tempBv->And(byteCodeUpwardExposedUsed, bailOutInfo->liveLosslessInt32Syms);
  2192. byteCodeUpwardExposedUsed->Minus(tempBv);
  2193. FOREACH_BITSET_IN_SPARSEBV(symId, tempBv)
  2194. {
  2195. StackSym * stackSym = this->func->m_symTable->FindStackSym(symId);
  2196. Assert(stackSym->GetType() == TyVar);
  2197. StackSym * int32StackSym = stackSym->GetInt32EquivSym(nullptr);
  2198. Assert(int32StackSym);
  2199. byteCodeUpwardExposedUsed->Set(int32StackSym->m_id);
  2200. }
  2201. NEXT_BITSET_IN_SPARSEBV;
  2202. // Float64
  2203. tempBv->And(byteCodeUpwardExposedUsed, bailOutInfo->liveFloat64Syms);
  2204. byteCodeUpwardExposedUsed->Minus(tempBv);
  2205. FOREACH_BITSET_IN_SPARSEBV(symId, tempBv)
  2206. {
  2207. StackSym * stackSym = this->func->m_symTable->FindStackSym(symId);
  2208. Assert(stackSym->GetType() == TyVar);
  2209. StackSym * float64StackSym = stackSym->GetFloat64EquivSym(nullptr);
  2210. Assert(float64StackSym);
  2211. byteCodeUpwardExposedUsed->Set(float64StackSym->m_id);
  2212. // This float-specialized sym is going to be used to restore the corresponding byte-code register. Need to
  2213. // ensure that the float value can be precisely coerced back to the original Var value by requiring that it is
  2214. // specialized using BailOutNumberOnly.
  2215. float64StackSym->m_requiresBailOnNotNumber = true;
  2216. }
  2217. NEXT_BITSET_IN_SPARSEBV;
  2218. #ifdef ENABLE_SIMDJS
  2219. // SIMD_JS
  2220. tempBv->Or(bailOutInfo->liveSimd128F4Syms, bailOutInfo->liveSimd128I4Syms);
  2221. tempBv->And(byteCodeUpwardExposedUsed);
  2222. byteCodeUpwardExposedUsed->Minus(tempBv);
  2223. FOREACH_BITSET_IN_SPARSEBV(symId, tempBv)
  2224. {
  2225. StackSym * stackSym = this->func->m_symTable->FindStackSym(symId);
  2226. Assert(stackSym->GetType() == TyVar);
  2227. StackSym * simd128Sym = nullptr;
  2228. if (bailOutInfo->liveSimd128F4Syms->Test(symId))
  2229. {
  2230. simd128Sym = stackSym->GetSimd128F4EquivSym(nullptr);
  2231. }
  2232. else
  2233. {
  2234. Assert(bailOutInfo->liveSimd128I4Syms->Test(symId));
  2235. simd128Sym = stackSym->GetSimd128I4EquivSym(nullptr);
  2236. }
  2237. byteCodeUpwardExposedUsed->Set(simd128Sym->m_id);
  2238. }
  2239. NEXT_BITSET_IN_SPARSEBV;
  2240. #endif
  2241. }
  2242. // Var
  2243. // Any remaining syms to restore will be restored from their var versions
  2244. }
  2245. else
  2246. {
  2247. Assert(!this->func->DoGlobOpt());
  2248. }
  2249. JitAdelete(this->tempAlloc, tempBv);
  2250. // BailOnNoProfile makes some edges dead. Upward exposed symbols info set after the BailOnProfile won't
  2251. // flow through these edges, and, in turn, not through predecessor edges of the block containing the
  2252. // BailOnNoProfile. This is specifically bad for an inlinee's argout syms as they are set as upward exposed
  2253. // when we see the InlineeEnd, but may not look so to some blocks and may get overwritten.
  2254. // Set the argout syms as upward exposed here.
  2255. if (instr->m_opcode == Js::OpCode::BailOnNoProfile && instr->m_func->IsInlinee() &&
  2256. instr->m_func->m_hasInlineArgsOpt && instr->m_func->frameInfo->isRecorded)
  2257. {
  2258. instr->m_func->frameInfo->IterateSyms([=](StackSym* argSym)
  2259. {
  2260. this->currentBlock->upwardExposedUses->Set(argSym->m_id);
  2261. });
  2262. }
  2263. // Mark all the register that we need to restore as used (excluding constants)
  2264. block->upwardExposedUses->Or(byteCodeUpwardExposedUsed);
  2265. block->upwardExposedUses->Or(bailoutReferencedArgSymsBv);
  2266. if (!this->IsPrePass())
  2267. {
  2268. bailOutInfo->IterateArgOutSyms([=](uint index, uint, StackSym* sym) {
  2269. if (sym->IsArgSlotSym() || bailoutReferencedArgSymsBv->Test(sym->m_id))
  2270. {
  2271. bailOutInfo->argOutSyms[index]->m_isBailOutReferenced = true;
  2272. }
  2273. });
  2274. }
  2275. JitAdelete(this->tempAlloc, bailoutReferencedArgSymsBv);
  2276. if (this->IsPrePass())
  2277. {
  2278. JitAdelete(this->tempAlloc, byteCodeUpwardExposedUsed);
  2279. }
  2280. }
  2281. void
  2282. BackwardPass::ProcessBlock(BasicBlock * block)
  2283. {
  2284. this->currentBlock = block;
  2285. this->MergeSuccBlocksInfo(block);
  2286. #if DBG_DUMP
  2287. if (this->IsTraceEnabled())
  2288. {
  2289. Output::Print(_u("******************************* Before Process Block *******************************n"));
  2290. DumpBlockData(block);
  2291. }
  2292. #endif
  2293. FOREACH_INSTR_BACKWARD_IN_BLOCK_EDITING(instr, instrPrev, block)
  2294. {
  2295. #if DBG_DUMP
  2296. if (!IsCollectionPass() && IsTraceEnabled() && Js::Configuration::Global.flags.Verbose)
  2297. {
  2298. Output::Print(_u(">>>>>>>>>>>>>>>>>>>>>> %s: Instr Start\n"), tag == Js::BackwardPhase? _u("BACKWARD") : _u("DEADSTORE"));
  2299. instr->Dump();
  2300. if (block->upwardExposedUses)
  2301. {
  2302. Output::SkipToColumn(10);
  2303. Output::Print(_u(" Exposed Use: "));
  2304. block->upwardExposedUses->Dump();
  2305. }
  2306. if (block->upwardExposedFields)
  2307. {
  2308. Output::SkipToColumn(10);
  2309. Output::Print(_u("Exposed Fields: "));
  2310. block->upwardExposedFields->Dump();
  2311. }
  2312. if (block->byteCodeUpwardExposedUsed)
  2313. {
  2314. Output::SkipToColumn(10);
  2315. Output::Print(_u(" Byte Code Use: "));
  2316. block->byteCodeUpwardExposedUsed->Dump();
  2317. }
  2318. Output::Print(_u("--------------------\n"));
  2319. }
  2320. #endif
  2321. AssertOrFailFastMsg(!instr->IsLowered(), "Lowered instruction detected in pre-lower context!");
  2322. this->currentInstr = instr;
  2323. this->currentRegion = this->currentBlock->GetFirstInstr()->AsLabelInstr()->GetRegion();
  2324. IR::Instr * insertedInstr = TryChangeInstrForStackArgOpt();
  2325. if (insertedInstr != nullptr)
  2326. {
  2327. instrPrev = insertedInstr;
  2328. continue;
  2329. }
  2330. MarkScopeObjSymUseForStackArgOpt();
  2331. ProcessBailOnStackArgsOutOfActualsRange();
  2332. if (ProcessNoImplicitCallUses(instr) || this->ProcessBailOutInfo(instr))
  2333. {
  2334. continue;
  2335. }
  2336. IR::Instr *instrNext = instr->m_next;
  2337. if (this->TrackNoImplicitCallInlinees(instr))
  2338. {
  2339. instrPrev = instrNext->m_prev;
  2340. continue;
  2341. }
  2342. if (CanDeadStoreInstrForScopeObjRemoval() && DeadStoreOrChangeInstrForScopeObjRemoval(&instrPrev))
  2343. {
  2344. continue;
  2345. }
  2346. bool hasLiveFields = (block->upwardExposedFields && !block->upwardExposedFields->IsEmpty());
  2347. IR::Opnd * opnd = instr->GetDst();
  2348. if (opnd != nullptr)
  2349. {
  2350. bool isRemoved = ReverseCopyProp(instr);
  2351. if (isRemoved)
  2352. {
  2353. instrPrev = instrNext->m_prev;
  2354. continue;
  2355. }
  2356. if (instr->m_opcode == Js::OpCode::Conv_Bool)
  2357. {
  2358. isRemoved = this->FoldCmBool(instr);
  2359. if (isRemoved)
  2360. {
  2361. continue;
  2362. }
  2363. }
  2364. ProcessNewScObject(instr);
  2365. this->ProcessTransfers(instr);
  2366. isRemoved = this->ProcessDef(opnd);
  2367. if (isRemoved)
  2368. {
  2369. continue;
  2370. }
  2371. }
  2372. if(!IsCollectionPass())
  2373. {
  2374. this->MarkTempProcessInstr(instr);
  2375. this->ProcessFieldKills(instr);
  2376. if (this->DoDeadStoreSlots()
  2377. && (instr->HasAnyImplicitCalls() || instr->HasBailOutInfo() || instr->UsesAllFields()))
  2378. {
  2379. // Can't dead-store slots if there can be an implicit-call, an exception, or a bailout
  2380. block->slotDeadStoreCandidates->ClearAll();
  2381. }
  2382. if (this->DoFieldHoistCandidates())
  2383. {
  2384. this->ProcessFieldHoistKills(instr);
  2385. }
  2386. TrackIntUsage(instr);
  2387. TrackBitWiseOrNumberOp(instr);
  2388. TrackFloatSymEquivalence(instr);
  2389. }
  2390. opnd = instr->GetSrc1();
  2391. if (opnd != nullptr)
  2392. {
  2393. this->ProcessUse(opnd);
  2394. opnd = instr->GetSrc2();
  2395. if (opnd != nullptr)
  2396. {
  2397. this->ProcessUse(opnd);
  2398. }
  2399. }
  2400. if(IsCollectionPass())
  2401. {
  2402. continue;
  2403. }
  2404. if (this->tag == Js::DeadStorePhase)
  2405. {
  2406. switch(instr->m_opcode)
  2407. {
  2408. case Js::OpCode::LdSlot:
  2409. {
  2410. DeadStoreOrChangeInstrForScopeObjRemoval(&instrPrev);
  2411. break;
  2412. }
  2413. case Js::OpCode::InlineArrayPush:
  2414. case Js::OpCode::InlineArrayPop:
  2415. {
  2416. IR::Opnd *const thisOpnd = instr->GetSrc1();
  2417. if(thisOpnd && thisOpnd->IsRegOpnd())
  2418. {
  2419. IR::RegOpnd *const thisRegOpnd = thisOpnd->AsRegOpnd();
  2420. if(thisRegOpnd->IsArrayRegOpnd())
  2421. {
  2422. // Process the array use at the point of the array built-in call, since the array will actually
  2423. // be used at the call, not at the ArgOut_A_InlineBuiltIn
  2424. ProcessArrayRegOpndUse(instr, thisRegOpnd->AsArrayRegOpnd());
  2425. }
  2426. }
  2427. }
  2428. #if !INT32VAR // the following is not valid on 64-bit platforms
  2429. case Js::OpCode::BoundCheck:
  2430. {
  2431. if(IsPrePass())
  2432. {
  2433. break;
  2434. }
  2435. // Look for:
  2436. // BoundCheck 0 <= s1
  2437. // BoundCheck s1 <= s2 + c, where c == 0 || c == -1
  2438. //
  2439. // And change it to:
  2440. // UnsignedBoundCheck s1 <= s2 + c
  2441. //
  2442. // The BoundCheck instruction is a signed operation, so any unsigned operand used in the instruction must be
  2443. // guaranteed to be >= 0 and <= int32 max when its value is interpreted as signed. Due to the restricted
  2444. // range of s2 above, by using an unsigned comparison instead, the negative check on s1 will also be
  2445. // covered.
  2446. //
  2447. // A BoundCheck instruction takes the form (src1 <= src2 + dst).
  2448. // Check the current instruction's pattern for:
  2449. // BoundCheck s1 <= s2 + c, where c <= 0
  2450. if(!instr->GetSrc1()->IsRegOpnd() ||
  2451. !instr->GetSrc1()->IsInt32() ||
  2452. !instr->GetSrc2() ||
  2453. instr->GetSrc2()->IsIntConstOpnd())
  2454. {
  2455. break;
  2456. }
  2457. if(instr->GetDst())
  2458. {
  2459. const int c = instr->GetDst()->AsIntConstOpnd()->GetValue();
  2460. if(c != 0 && c != -1)
  2461. {
  2462. break;
  2463. }
  2464. }
  2465. // Check the previous instruction's pattern for:
  2466. // BoundCheck 0 <= s1
  2467. IR::Instr *const lowerBoundCheck = instr->m_prev;
  2468. if(lowerBoundCheck->m_opcode != Js::OpCode::BoundCheck ||
  2469. !lowerBoundCheck->GetSrc1()->IsIntConstOpnd() ||
  2470. lowerBoundCheck->GetSrc1()->AsIntConstOpnd()->GetValue() != 0 ||
  2471. !lowerBoundCheck->GetSrc2() ||
  2472. !instr->GetSrc1()->AsRegOpnd()->IsEqual(lowerBoundCheck->GetSrc2()) ||
  2473. lowerBoundCheck->GetDst() && lowerBoundCheck->GetDst()->AsIntConstOpnd()->GetValue() != 0)
  2474. {
  2475. break;
  2476. }
  2477. // Remove the previous lower bound check, and change the current upper bound check to:
  2478. // UnsignedBoundCheck s1 <= s2 + c
  2479. instr->m_opcode = Js::OpCode::UnsignedBoundCheck;
  2480. currentBlock->RemoveInstr(lowerBoundCheck);
  2481. instrPrev = instr->m_prev;
  2482. break;
  2483. }
  2484. #endif
  2485. }
  2486. DeadStoreTypeCheckBailOut(instr);
  2487. DeadStoreImplicitCallBailOut(instr, hasLiveFields);
  2488. if (block->stackSymToFinalType != nullptr)
  2489. {
  2490. this->InsertTypeTransitionsAtPotentialKills();
  2491. }
  2492. // NoImplicitCallUses transfers need to be processed after determining whether implicit calls need to be disabled
  2493. // for the current instruction, because the instruction where the def occurs also needs implicit calls disabled.
  2494. // Array value type for the destination needs to be updated before transfers have been processed by
  2495. // ProcessNoImplicitCallDef, and array value types for sources need to be updated after transfers have been
  2496. // processed by ProcessNoImplicitCallDef, as it requires the no-implicit-call tracking bit-vectors to be precise at
  2497. // the point of the update.
  2498. if(!IsPrePass())
  2499. {
  2500. UpdateArrayValueTypes(instr, instr->GetDst());
  2501. }
  2502. ProcessNoImplicitCallDef(instr);
  2503. if(!IsPrePass())
  2504. {
  2505. UpdateArrayValueTypes(instr, instr->GetSrc1());
  2506. UpdateArrayValueTypes(instr, instr->GetSrc2());
  2507. }
  2508. }
  2509. else
  2510. {
  2511. switch (instr->m_opcode)
  2512. {
  2513. case Js::OpCode::BailOnNoProfile:
  2514. {
  2515. this->ProcessBailOnNoProfile(instr, block);
  2516. // this call could change the last instr of the previous block... Adjust instrStop.
  2517. instrStop = block->GetFirstInstr()->m_prev;
  2518. Assert(this->tag != Js::DeadStorePhase);
  2519. continue;
  2520. }
  2521. case Js::OpCode::Catch:
  2522. {
  2523. if (this->func->DoOptimizeTry() && !this->IsPrePass())
  2524. {
  2525. // Execute the "Catch" in the JIT'ed code, and bailout to the next instruction. This way, the bailout will restore the exception object automatically.
  2526. IR::BailOutInstr* bailOnException = IR::BailOutInstr::New(Js::OpCode::BailOnException, IR::BailOutOnException, instr->m_next, instr->m_func);
  2527. instr->InsertAfter(bailOnException);
  2528. Assert(instr->GetDst()->IsRegOpnd() && instr->GetDst()->GetStackSym()->HasByteCodeRegSlot());
  2529. StackSym * exceptionObjSym = instr->GetDst()->GetStackSym();
  2530. Assert(instr->m_prev->IsLabelInstr() && (instr->m_prev->AsLabelInstr()->GetRegion()->GetType() == RegionTypeCatch));
  2531. instr->m_prev->AsLabelInstr()->GetRegion()->SetExceptionObjectSym(exceptionObjSym);
  2532. }
  2533. break;
  2534. }
  2535. case Js::OpCode::Throw:
  2536. case Js::OpCode::EHThrow:
  2537. case Js::OpCode::InlineThrow:
  2538. this->func->SetHasThrow();
  2539. break;
  2540. }
  2541. }
  2542. if (instr->m_opcode == Js::OpCode::InlineeEnd)
  2543. {
  2544. this->ProcessInlineeEnd(instr);
  2545. }
  2546. if ((instr->IsLabelInstr() && instr->m_next->m_opcode == Js::OpCode::Catch) || (instr->IsLabelInstr() && instr->m_next->m_opcode == Js::OpCode::Finally))
  2547. {
  2548. if (!this->currentRegion)
  2549. {
  2550. Assert(!this->func->DoOptimizeTry() && !(this->func->IsSimpleJit() && this->func->hasBailout));
  2551. }
  2552. else
  2553. {
  2554. Assert(this->currentRegion->GetType() == RegionTypeCatch || this->currentRegion->GetType() == RegionTypeFinally);
  2555. Region * matchingTryRegion = this->currentRegion->GetMatchingTryRegion();
  2556. Assert(matchingTryRegion);
  2557. // We need live-on-back-edge info to accurately set write-through symbols for try-catches in a loop.
  2558. // Don't set write-through symbols in pre-pass
  2559. if (!this->IsPrePass() && !matchingTryRegion->writeThroughSymbolsSet)
  2560. {
  2561. if (this->tag == Js::DeadStorePhase)
  2562. {
  2563. Assert(!this->func->DoGlobOpt());
  2564. }
  2565. // FullJit: Write-through symbols info must be populated in the backward pass as
  2566. // 1. the forward pass needs it to insert ToVars.
  2567. // 2. the deadstore pass needs it to not clear such symbols from the
  2568. // byteCodeUpwardExposedUsed BV upon a def in the try region. This is required
  2569. // because any bailout in the try region needs to restore all write-through
  2570. // symbols.
  2571. // SimpleJit: Won't run the initial backward pass, but write-through symbols info is still
  2572. // needed in the deadstore pass for <2> above.
  2573. this->SetWriteThroughSymbolsSetForRegion(this->currentBlock, matchingTryRegion);
  2574. }
  2575. }
  2576. }
  2577. #if DBG
  2578. if (instr->m_opcode == Js::OpCode::TryCatch)
  2579. {
  2580. if (!this->IsPrePass() && (this->func->DoOptimizeTry() || (this->func->IsSimpleJit() && this->func->hasBailout)))
  2581. {
  2582. Assert(instr->m_next->IsLabelInstr() && (instr->m_next->AsLabelInstr()->GetRegion() != nullptr));
  2583. Region * tryRegion = instr->m_next->AsLabelInstr()->GetRegion();
  2584. Assert(tryRegion && tryRegion->GetType() == RegionType::RegionTypeTry && tryRegion->GetMatchingCatchRegion() != nullptr);
  2585. Assert(tryRegion->writeThroughSymbolsSet);
  2586. }
  2587. }
  2588. #endif
  2589. ProcessPendingPreOpBailOutInfo(instr);
  2590. #if DBG_DUMP
  2591. if (!IsCollectionPass() && IsTraceEnabled() && Js::Configuration::Global.flags.Verbose)
  2592. {
  2593. Output::Print(_u("-------------------\n"));
  2594. instr->Dump();
  2595. if (block->upwardExposedUses)
  2596. {
  2597. Output::SkipToColumn(10);
  2598. Output::Print(_u(" Exposed Use: "));
  2599. block->upwardExposedUses->Dump();
  2600. }
  2601. if (block->upwardExposedFields)
  2602. {
  2603. Output::SkipToColumn(10);
  2604. Output::Print(_u("Exposed Fields: "));
  2605. block->upwardExposedFields->Dump();
  2606. }
  2607. if (block->byteCodeUpwardExposedUsed)
  2608. {
  2609. Output::SkipToColumn(10);
  2610. Output::Print(_u(" Byte Code Use: "));
  2611. block->byteCodeUpwardExposedUsed->Dump();
  2612. }
  2613. Output::Print(_u("<<<<<<<<<<<<<<<<<<<<<< %s: Instr End\n"), tag == Js::BackwardPhase? _u("BACKWARD") : _u("DEADSTORE"));
  2614. }
  2615. #endif
  2616. }
  2617. NEXT_INSTR_BACKWARD_IN_BLOCK_EDITING;
  2618. EndIntOverflowDoesNotMatterRange();
  2619. if (this->DoFieldHoistCandidates() && !block->isDead && block->isLoopHeader)
  2620. {
  2621. Assert(block->loop->fieldHoistCandidates == nullptr);
  2622. block->loop->fieldHoistCandidates = block->fieldHoistCandidates->CopyNew(this->func->m_alloc);
  2623. }
  2624. if (!this->IsPrePass() && !block->isDead && block->isLoopHeader)
  2625. {
  2626. // Copy the upward exposed use as the live on back edge regs
  2627. block->loop->regAlloc.liveOnBackEdgeSyms = block->upwardExposedUses->CopyNew(this->func->m_alloc);
  2628. }
  2629. Assert(!considerSymAsRealUseInNoImplicitCallUses);
  2630. #if DBG_DUMP
  2631. if (this->IsTraceEnabled())
  2632. {
  2633. Output::Print(_u("******************************* After Process Block *******************************n"));
  2634. DumpBlockData(block);
  2635. }
  2636. #endif
  2637. }
  2638. bool
  2639. BackwardPass::CanDeadStoreInstrForScopeObjRemoval(Sym *sym) const
  2640. {
  2641. if (tag == Js::DeadStorePhase && this->currentInstr->m_func->IsStackArgsEnabled())
  2642. {
  2643. Func * currFunc = this->currentInstr->m_func;
  2644. bool doScopeObjCreation = currFunc->GetJITFunctionBody()->GetDoScopeObjectCreation();
  2645. switch (this->currentInstr->m_opcode)
  2646. {
  2647. case Js::OpCode::InitCachedScope:
  2648. {
  2649. if(!doScopeObjCreation && this->currentInstr->GetDst()->IsScopeObjOpnd(currFunc))
  2650. {
  2651. /*
  2652. * We don't really dead store this instruction. We just want the source sym of this instruction
  2653. * to NOT be tracked as USED by this instruction.
  2654. * This instr will effectively be lowered to dest = MOV NULLObject, in the lowerer phase.
  2655. */
  2656. return true;
  2657. }
  2658. break;
  2659. }
  2660. case Js::OpCode::LdSlot:
  2661. {
  2662. if (sym && IsFormalParamSym(currFunc, sym))
  2663. {
  2664. return true;
  2665. }
  2666. break;
  2667. }
  2668. case Js::OpCode::CommitScope:
  2669. case Js::OpCode::GetCachedFunc:
  2670. {
  2671. return !doScopeObjCreation && this->currentInstr->GetSrc1()->IsScopeObjOpnd(currFunc);
  2672. }
  2673. case Js::OpCode::BrFncCachedScopeEq:
  2674. case Js::OpCode::BrFncCachedScopeNeq:
  2675. {
  2676. return !doScopeObjCreation && this->currentInstr->GetSrc2()->IsScopeObjOpnd(currFunc);
  2677. }
  2678. case Js::OpCode::CallHelper:
  2679. {
  2680. if (!doScopeObjCreation && this->currentInstr->GetSrc1()->AsHelperCallOpnd()->m_fnHelper == IR::JnHelperMethod::HelperOP_InitCachedFuncs)
  2681. {
  2682. IR::RegOpnd * scopeObjOpnd = this->currentInstr->GetSrc2()->GetStackSym()->GetInstrDef()->GetSrc1()->AsRegOpnd();
  2683. return scopeObjOpnd->IsScopeObjOpnd(currFunc);
  2684. }
  2685. break;
  2686. }
  2687. }
  2688. }
  2689. return false;
  2690. }
  2691. /*
  2692. * This is for Eliminating Scope Object Creation during Heap arguments optimization.
  2693. */
  2694. bool
  2695. BackwardPass::DeadStoreOrChangeInstrForScopeObjRemoval(IR::Instr ** pInstrPrev)
  2696. {
  2697. IR::Instr * instr = this->currentInstr;
  2698. Func * currFunc = instr->m_func;
  2699. if (this->tag == Js::DeadStorePhase && instr->m_func->IsStackArgsEnabled() && !IsPrePass())
  2700. {
  2701. switch (instr->m_opcode)
  2702. {
  2703. /*
  2704. * This LdSlot loads the formal from the formals array. We replace this a Ld_A <ArgInSym>.
  2705. * ArgInSym is inserted at the beginning of the function during the start of the deadstore pass- for the top func.
  2706. * In case of inlinee, it will be from the source sym of the ArgOut Instruction to the inlinee.
  2707. */
  2708. case Js::OpCode::LdSlot:
  2709. {
  2710. IR::Opnd * src1 = instr->GetSrc1();
  2711. if (src1 && src1->IsSymOpnd())
  2712. {
  2713. Sym * sym = src1->AsSymOpnd()->m_sym;
  2714. Assert(sym);
  2715. if (IsFormalParamSym(currFunc, sym))
  2716. {
  2717. AssertMsg(!currFunc->GetJITFunctionBody()->HasImplicitArgIns(), "We don't have mappings between named formals and arguments object here");
  2718. instr->m_opcode = Js::OpCode::Ld_A;
  2719. PropertySym * propSym = sym->AsPropertySym();
  2720. Js::ArgSlot value = (Js::ArgSlot)propSym->m_propertyId;
  2721. Assert(currFunc->HasStackSymForFormal(value));
  2722. StackSym * paramStackSym = currFunc->GetStackSymForFormal(value);
  2723. IR::RegOpnd * srcOpnd = IR::RegOpnd::New(paramStackSym, TyVar, currFunc);
  2724. instr->ReplaceSrc1(srcOpnd);
  2725. this->ProcessSymUse(paramStackSym, true, true);
  2726. if (PHASE_VERBOSE_TRACE1(Js::StackArgFormalsOptPhase))
  2727. {
  2728. Output::Print(_u("StackArgFormals : %s (%d) :Replacing LdSlot with Ld_A in Deadstore pass. \n"), instr->m_func->GetJITFunctionBody()->GetDisplayName(), instr->m_func->GetFunctionNumber());
  2729. Output::Flush();
  2730. }
  2731. }
  2732. }
  2733. break;
  2734. }
  2735. case Js::OpCode::CommitScope:
  2736. {
  2737. if (instr->GetSrc1()->IsScopeObjOpnd(currFunc))
  2738. {
  2739. instr->Remove();
  2740. return true;
  2741. }
  2742. break;
  2743. }
  2744. case Js::OpCode::BrFncCachedScopeEq:
  2745. case Js::OpCode::BrFncCachedScopeNeq:
  2746. {
  2747. if (instr->GetSrc2()->IsScopeObjOpnd(currFunc))
  2748. {
  2749. instr->Remove();
  2750. return true;
  2751. }
  2752. break;
  2753. }
  2754. case Js::OpCode::CallHelper:
  2755. {
  2756. //Remove the CALL and all its Argout instrs.
  2757. if (instr->GetSrc1()->AsHelperCallOpnd()->m_fnHelper == IR::JnHelperMethod::HelperOP_InitCachedFuncs)
  2758. {
  2759. IR::RegOpnd * scopeObjOpnd = instr->GetSrc2()->GetStackSym()->GetInstrDef()->GetSrc1()->AsRegOpnd();
  2760. if (scopeObjOpnd->IsScopeObjOpnd(currFunc))
  2761. {
  2762. IR::Instr * instrDef = instr;
  2763. IR::Instr * nextInstr = instr->m_next;
  2764. while (instrDef != nullptr)
  2765. {
  2766. IR::Instr * instrToDelete = instrDef;
  2767. if (instrDef->GetSrc2() != nullptr)
  2768. {
  2769. instrDef = instrDef->GetSrc2()->GetStackSym()->GetInstrDef();
  2770. Assert(instrDef->m_opcode == Js::OpCode::ArgOut_A);
  2771. }
  2772. else
  2773. {
  2774. instrDef = nullptr;
  2775. }
  2776. instrToDelete->Remove();
  2777. }
  2778. Assert(nextInstr != nullptr);
  2779. *pInstrPrev = nextInstr->m_prev;
  2780. return true;
  2781. }
  2782. }
  2783. break;
  2784. }
  2785. case Js::OpCode::GetCachedFunc:
  2786. {
  2787. // <dst> = GetCachedFunc <scopeObject>, <functionNum>
  2788. // is converted to
  2789. // <dst> = NewScFunc <functionNum>, <env: FrameDisplay>
  2790. if (instr->GetSrc1()->IsScopeObjOpnd(currFunc))
  2791. {
  2792. instr->m_opcode = Js::OpCode::NewScFunc;
  2793. IR::Opnd * intConstOpnd = instr->UnlinkSrc2();
  2794. Assert(intConstOpnd->IsIntConstOpnd());
  2795. uint nestedFuncIndex = instr->m_func->GetJITFunctionBody()->GetNestedFuncIndexForSlotIdInCachedScope(intConstOpnd->AsIntConstOpnd()->AsUint32());
  2796. intConstOpnd->Free(instr->m_func);
  2797. instr->ReplaceSrc1(IR::IntConstOpnd::New(nestedFuncIndex, TyUint32, instr->m_func));
  2798. instr->SetSrc2(IR::RegOpnd::New(currFunc->GetLocalFrameDisplaySym(), IRType::TyVar, currFunc));
  2799. }
  2800. break;
  2801. }
  2802. }
  2803. }
  2804. return false;
  2805. }
  2806. IR::Instr *
  2807. BackwardPass::TryChangeInstrForStackArgOpt()
  2808. {
  2809. IR::Instr * instr = this->currentInstr;
  2810. if (tag == Js::DeadStorePhase && instr->DoStackArgsOpt(this->func))
  2811. {
  2812. switch (instr->m_opcode)
  2813. {
  2814. case Js::OpCode::TypeofElem:
  2815. {
  2816. /*
  2817. Before:
  2818. dst = TypeOfElem arguments[i] <(BailOnStackArgsOutOfActualsRange)>
  2819. After:
  2820. tmpdst = LdElemI_A arguments[i] <(BailOnStackArgsOutOfActualsRange)>
  2821. dst = TypeOf tmpdst
  2822. */
  2823. AssertMsg(instr->HasBailOutInfo() && (instr->GetBailOutKind() & IR::BailOutKind::BailOnStackArgsOutOfActualsRange), "Why is the bailout kind not set, when it is StackArgOptimized?");
  2824. instr->m_opcode = Js::OpCode::LdElemI_A;
  2825. IR::Opnd * dstOpnd = instr->UnlinkDst();
  2826. IR::RegOpnd * elementOpnd = IR::RegOpnd::New(StackSym::New(instr->m_func), IRType::TyVar, instr->m_func);
  2827. instr->SetDst(elementOpnd);
  2828. IR::Instr * typeOfInstr = IR::Instr::New(Js::OpCode::Typeof, dstOpnd, elementOpnd, instr->m_func);
  2829. instr->InsertAfter(typeOfInstr);
  2830. return typeOfInstr;
  2831. }
  2832. }
  2833. }
  2834. /*
  2835. * Scope Object Sym is kept alive in all code paths.
  2836. * -This is to facilitate Bailout to record the live Scope object Sym, whenever required.
  2837. * -Reason for doing is this because - Scope object has to be implicitly live whenever Heap Arguments object is live.
  2838. * -When we restore HeapArguments object in the bail out path, it expects the scope object also to be restored - if one was created.
  2839. * -We do not know detailed information about Heap arguments obj syms(aliasing etc.) until we complete Forward Pass.
  2840. * -And we want to avoid dead sym clean up (in this case, scope object though not explicitly live, it is live implicitly) during Block merging in the forward pass.
  2841. * -Hence this is the optimal spot to do this.
  2842. */
  2843. if (tag == Js::BackwardPhase && instr->m_func->GetScopeObjSym() != nullptr)
  2844. {
  2845. this->currentBlock->upwardExposedUses->Set(instr->m_func->GetScopeObjSym()->m_id);
  2846. }
  2847. return nullptr;
  2848. }
  2849. void
  2850. BackwardPass::TraceDeadStoreOfInstrsForScopeObjectRemoval()
  2851. {
  2852. IR::Instr * instr = this->currentInstr;
  2853. if (instr->m_func->IsStackArgsEnabled())
  2854. {
  2855. if ((instr->m_opcode == Js::OpCode::InitCachedScope || instr->m_opcode == Js::OpCode::NewScopeObject) && !IsPrePass())
  2856. {
  2857. if (PHASE_TRACE1(Js::StackArgFormalsOptPhase))
  2858. {
  2859. Output::Print(_u("StackArgFormals : %s (%d) :Removing Scope object creation in Deadstore pass. \n"), instr->m_func->GetJITFunctionBody()->GetDisplayName(), instr->m_func->GetFunctionNumber());
  2860. Output::Flush();
  2861. }
  2862. }
  2863. }
  2864. }
  2865. bool
  2866. BackwardPass::IsFormalParamSym(Func * func, Sym * sym) const
  2867. {
  2868. Assert(sym);
  2869. if (sym->IsPropertySym())
  2870. {
  2871. //If the sym is a propertySym, then see if the propertyId is within the range of the formals
  2872. //We can have other properties stored in the scope object other than the formals (following the formals).
  2873. PropertySym * propSym = sym->AsPropertySym();
  2874. IntConstType value = propSym->m_propertyId;
  2875. return func->IsFormalsArraySym(propSym->m_stackSym->m_id) &&
  2876. (value >= 0 && value < func->GetJITFunctionBody()->GetInParamsCount() - 1);
  2877. }
  2878. else
  2879. {
  2880. Assert(sym->IsStackSym());
  2881. return !!func->IsFormalsArraySym(sym->AsStackSym()->m_id);
  2882. }
  2883. }
  2884. #if DBG_DUMP
  2885. void
  2886. BackwardPass::DumpBlockData(BasicBlock * block)
  2887. {
  2888. block->DumpHeader();
  2889. if (block->upwardExposedUses) // may be null for dead blocks
  2890. {
  2891. Output::Print(_u(" Exposed Uses: "));
  2892. block->upwardExposedUses->Dump();
  2893. }
  2894. if (block->typesNeedingKnownObjectLayout)
  2895. {
  2896. Output::Print(_u(" Needs Known Object Layout: "));
  2897. block->typesNeedingKnownObjectLayout->Dump();
  2898. }
  2899. if (this->DoFieldHoistCandidates() && !block->isDead)
  2900. {
  2901. Output::Print(_u(" Exposed Field: "));
  2902. block->fieldHoistCandidates->Dump();
  2903. }
  2904. if (block->byteCodeUpwardExposedUsed)
  2905. {
  2906. Output::Print(_u(" Byte Code Exposed Uses: "));
  2907. block->byteCodeUpwardExposedUsed->Dump();
  2908. }
  2909. if (!this->IsCollectionPass())
  2910. {
  2911. if (!block->isDead)
  2912. {
  2913. if (this->DoDeadStoreSlots())
  2914. {
  2915. Output::Print(_u("Slot deadStore candidates: "));
  2916. block->slotDeadStoreCandidates->Dump();
  2917. }
  2918. DumpMarkTemp();
  2919. }
  2920. }
  2921. Output::Flush();
  2922. }
  2923. #endif
  2924. bool
  2925. BackwardPass::UpdateImplicitCallBailOutKind(IR::Instr *const instr, bool needsBailOutOnImplicitCall)
  2926. {
  2927. Assert(instr);
  2928. Assert(instr->HasBailOutInfo());
  2929. IR::BailOutKind implicitCallBailOutKind = needsBailOutOnImplicitCall ? IR::BailOutOnImplicitCalls : IR::BailOutInvalid;
  2930. const IR::BailOutKind instrBailOutKind = instr->GetBailOutKind();
  2931. if (instrBailOutKind & IR::BailOutMarkTempObject)
  2932. {
  2933. // Don't remove the implicit call pre op bailout for mark temp object
  2934. // Remove the mark temp object bit, as we don't need it after the dead store pass
  2935. instr->SetBailOutKind(instrBailOutKind & ~IR::BailOutMarkTempObject);
  2936. return true;
  2937. }
  2938. const IR::BailOutKind instrImplicitCallBailOutKind = instrBailOutKind & ~IR::BailOutKindBits;
  2939. if(instrImplicitCallBailOutKind == IR::BailOutOnImplicitCallsPreOp)
  2940. {
  2941. if(needsBailOutOnImplicitCall)
  2942. {
  2943. implicitCallBailOutKind = IR::BailOutOnImplicitCallsPreOp;
  2944. }
  2945. }
  2946. else if(instrImplicitCallBailOutKind != IR::BailOutOnImplicitCalls && instrImplicitCallBailOutKind != IR::BailOutInvalid)
  2947. {
  2948. // This bailout kind (the value of 'instrImplicitCallBailOutKind') must guarantee that implicit calls will not happen.
  2949. // If it doesn't make such a guarantee, it must be possible to merge this bailout kind with an implicit call bailout
  2950. // kind, and therefore should be part of BailOutKindBits.
  2951. Assert(!needsBailOutOnImplicitCall);
  2952. return true;
  2953. }
  2954. if(instrImplicitCallBailOutKind == implicitCallBailOutKind)
  2955. {
  2956. return true;
  2957. }
  2958. const IR::BailOutKind newBailOutKind = instrBailOutKind - instrImplicitCallBailOutKind + implicitCallBailOutKind;
  2959. if(newBailOutKind == IR::BailOutInvalid)
  2960. {
  2961. return false;
  2962. }
  2963. instr->SetBailOutKind(newBailOutKind);
  2964. return true;
  2965. }
  2966. bool
  2967. BackwardPass::ProcessNoImplicitCallUses(IR::Instr *const instr)
  2968. {
  2969. Assert(instr);
  2970. if(instr->m_opcode != Js::OpCode::NoImplicitCallUses)
  2971. {
  2972. return false;
  2973. }
  2974. Assert(tag == Js::DeadStorePhase);
  2975. Assert(!instr->GetDst());
  2976. Assert(instr->GetSrc1());
  2977. Assert(instr->GetSrc1()->IsRegOpnd() || instr->GetSrc1()->IsSymOpnd());
  2978. Assert(!instr->GetSrc2() || instr->GetSrc2()->IsRegOpnd() || instr->GetSrc2()->IsSymOpnd());
  2979. if(IsCollectionPass())
  2980. {
  2981. return true;
  2982. }
  2983. IR::Opnd *const srcs[] = { instr->GetSrc1(), instr->GetSrc2() };
  2984. for(int i = 0; i < sizeof(srcs) / sizeof(srcs[0]) && srcs[i]; ++i)
  2985. {
  2986. IR::Opnd *const src = srcs[i];
  2987. IR::ArrayRegOpnd *arraySrc = nullptr;
  2988. Sym *sym = nullptr;
  2989. switch(src->GetKind())
  2990. {
  2991. case IR::OpndKindReg:
  2992. {
  2993. IR::RegOpnd *const regSrc = src->AsRegOpnd();
  2994. sym = regSrc->m_sym;
  2995. if(considerSymAsRealUseInNoImplicitCallUses && considerSymAsRealUseInNoImplicitCallUses == sym)
  2996. {
  2997. considerSymAsRealUseInNoImplicitCallUses = nullptr;
  2998. ProcessStackSymUse(sym->AsStackSym(), true);
  2999. }
  3000. if(regSrc->IsArrayRegOpnd())
  3001. {
  3002. arraySrc = regSrc->AsArrayRegOpnd();
  3003. }
  3004. break;
  3005. }
  3006. case IR::OpndKindSym:
  3007. sym = src->AsSymOpnd()->m_sym;
  3008. Assert(sym->IsPropertySym());
  3009. break;
  3010. default:
  3011. Assert(false);
  3012. __assume(false);
  3013. }
  3014. currentBlock->noImplicitCallUses->Set(sym->m_id);
  3015. const ValueType valueType(src->GetValueType());
  3016. if(valueType.IsArrayOrObjectWithArray())
  3017. {
  3018. if(valueType.HasNoMissingValues())
  3019. {
  3020. currentBlock->noImplicitCallNoMissingValuesUses->Set(sym->m_id);
  3021. }
  3022. if(!valueType.HasVarElements())
  3023. {
  3024. currentBlock->noImplicitCallNativeArrayUses->Set(sym->m_id);
  3025. }
  3026. if(arraySrc)
  3027. {
  3028. ProcessArrayRegOpndUse(instr, arraySrc);
  3029. }
  3030. }
  3031. }
  3032. if(!IsPrePass())
  3033. {
  3034. currentBlock->RemoveInstr(instr);
  3035. }
  3036. return true;
  3037. }
  3038. void
  3039. BackwardPass::ProcessNoImplicitCallDef(IR::Instr *const instr)
  3040. {
  3041. Assert(tag == Js::DeadStorePhase);
  3042. Assert(instr);
  3043. IR::Opnd *const dst = instr->GetDst();
  3044. if(!dst)
  3045. {
  3046. return;
  3047. }
  3048. Sym *dstSym;
  3049. switch(dst->GetKind())
  3050. {
  3051. case IR::OpndKindReg:
  3052. dstSym = dst->AsRegOpnd()->m_sym;
  3053. break;
  3054. case IR::OpndKindSym:
  3055. dstSym = dst->AsSymOpnd()->m_sym;
  3056. if(!dstSym->IsPropertySym())
  3057. {
  3058. return;
  3059. }
  3060. break;
  3061. default:
  3062. return;
  3063. }
  3064. if(!currentBlock->noImplicitCallUses->TestAndClear(dstSym->m_id))
  3065. {
  3066. Assert(!currentBlock->noImplicitCallNoMissingValuesUses->Test(dstSym->m_id));
  3067. Assert(!currentBlock->noImplicitCallNativeArrayUses->Test(dstSym->m_id));
  3068. Assert(!currentBlock->noImplicitCallJsArrayHeadSegmentSymUses->Test(dstSym->m_id));
  3069. Assert(!currentBlock->noImplicitCallArrayLengthSymUses->Test(dstSym->m_id));
  3070. return;
  3071. }
  3072. const bool transferNoMissingValuesUse = !!currentBlock->noImplicitCallNoMissingValuesUses->TestAndClear(dstSym->m_id);
  3073. const bool transferNativeArrayUse = !!currentBlock->noImplicitCallNativeArrayUses->TestAndClear(dstSym->m_id);
  3074. const bool transferJsArrayHeadSegmentSymUse =
  3075. !!currentBlock->noImplicitCallJsArrayHeadSegmentSymUses->TestAndClear(dstSym->m_id);
  3076. const bool transferArrayLengthSymUse = !!currentBlock->noImplicitCallArrayLengthSymUses->TestAndClear(dstSym->m_id);
  3077. IR::Opnd *const src = instr->GetSrc1();
  3078. if(!src || instr->GetSrc2())
  3079. {
  3080. return;
  3081. }
  3082. if(dst->IsRegOpnd() && src->IsRegOpnd())
  3083. {
  3084. if(!OpCodeAttr::NonIntTransfer(instr->m_opcode))
  3085. {
  3086. return;
  3087. }
  3088. }
  3089. else if(
  3090. !(
  3091. // LdFld or similar
  3092. (dst->IsRegOpnd() && src->IsSymOpnd() && src->AsSymOpnd()->m_sym->IsPropertySym()) ||
  3093. // StFld or similar. Don't transfer a field opnd from StFld into the reg opnd src unless the field's value type is
  3094. // definitely array or object with array, because only those value types require implicit calls to be disabled as
  3095. // long as they are live. Other definite value types only require implicit calls to be disabled as long as a live
  3096. // field holds the value, which is up to the StFld when going backwards.
  3097. (src->IsRegOpnd() && dst->GetValueType().IsArrayOrObjectWithArray())
  3098. ) ||
  3099. !instr->TransfersSrcValue())
  3100. {
  3101. return;
  3102. }
  3103. Sym *srcSym = nullptr;
  3104. switch(src->GetKind())
  3105. {
  3106. case IR::OpndKindReg:
  3107. srcSym = src->AsRegOpnd()->m_sym;
  3108. break;
  3109. case IR::OpndKindSym:
  3110. srcSym = src->AsSymOpnd()->m_sym;
  3111. Assert(srcSym->IsPropertySym());
  3112. break;
  3113. default:
  3114. Assert(false);
  3115. __assume(false);
  3116. }
  3117. currentBlock->noImplicitCallUses->Set(srcSym->m_id);
  3118. if(transferNoMissingValuesUse)
  3119. {
  3120. currentBlock->noImplicitCallNoMissingValuesUses->Set(srcSym->m_id);
  3121. }
  3122. if(transferNativeArrayUse)
  3123. {
  3124. currentBlock->noImplicitCallNativeArrayUses->Set(srcSym->m_id);
  3125. }
  3126. if(transferJsArrayHeadSegmentSymUse)
  3127. {
  3128. currentBlock->noImplicitCallJsArrayHeadSegmentSymUses->Set(srcSym->m_id);
  3129. }
  3130. if(transferArrayLengthSymUse)
  3131. {
  3132. currentBlock->noImplicitCallArrayLengthSymUses->Set(srcSym->m_id);
  3133. }
  3134. }
  3135. template<class F>
  3136. IR::Opnd *
  3137. BackwardPass::FindNoImplicitCallUse(
  3138. IR::Instr *const instr,
  3139. StackSym *const sym,
  3140. const F IsCheckedUse,
  3141. IR::Instr * *const noImplicitCallUsesInstrRef)
  3142. {
  3143. IR::RegOpnd *const opnd = IR::RegOpnd::New(sym, sym->GetType(), instr->m_func);
  3144. IR::Opnd *const use = FindNoImplicitCallUse(instr, opnd, IsCheckedUse, noImplicitCallUsesInstrRef);
  3145. opnd->FreeInternal(instr->m_func);
  3146. return use;
  3147. }
  3148. template<class F>
  3149. IR::Opnd *
  3150. BackwardPass::FindNoImplicitCallUse(
  3151. IR::Instr *const instr,
  3152. IR::Opnd *const opnd,
  3153. const F IsCheckedUse,
  3154. IR::Instr * *const noImplicitCallUsesInstrRef)
  3155. {
  3156. Assert(instr);
  3157. Assert(instr->m_opcode != Js::OpCode::NoImplicitCallUses);
  3158. // Skip byte-code uses
  3159. IR::Instr *prevInstr = instr->m_prev;
  3160. while(
  3161. prevInstr &&
  3162. !prevInstr->IsLabelInstr() &&
  3163. (!prevInstr->IsRealInstr() || prevInstr->IsByteCodeUsesInstr()) &&
  3164. prevInstr->m_opcode != Js::OpCode::NoImplicitCallUses)
  3165. {
  3166. prevInstr = prevInstr->m_prev;
  3167. }
  3168. // Find the corresponding use in a NoImplicitCallUses instruction
  3169. for(; prevInstr && prevInstr->m_opcode == Js::OpCode::NoImplicitCallUses; prevInstr = prevInstr->m_prev)
  3170. {
  3171. IR::Opnd *const checkedSrcs[] = { prevInstr->GetSrc1(), prevInstr->GetSrc2() };
  3172. for(int i = 0; i < sizeof(checkedSrcs) / sizeof(checkedSrcs[0]) && checkedSrcs[i]; ++i)
  3173. {
  3174. IR::Opnd *const checkedSrc = checkedSrcs[i];
  3175. if(checkedSrc->IsEqual(opnd) && IsCheckedUse(checkedSrc))
  3176. {
  3177. if(noImplicitCallUsesInstrRef)
  3178. {
  3179. *noImplicitCallUsesInstrRef = prevInstr;
  3180. }
  3181. return checkedSrc;
  3182. }
  3183. }
  3184. }
  3185. if(noImplicitCallUsesInstrRef)
  3186. {
  3187. *noImplicitCallUsesInstrRef = nullptr;
  3188. }
  3189. return nullptr;
  3190. }
  3191. void
  3192. BackwardPass::ProcessArrayRegOpndUse(IR::Instr *const instr, IR::ArrayRegOpnd *const arrayRegOpnd)
  3193. {
  3194. Assert(tag == Js::DeadStorePhase);
  3195. Assert(!IsCollectionPass());
  3196. Assert(instr);
  3197. Assert(arrayRegOpnd);
  3198. if(!(arrayRegOpnd->HeadSegmentSym() || arrayRegOpnd->HeadSegmentLengthSym() || arrayRegOpnd->LengthSym()))
  3199. {
  3200. return;
  3201. }
  3202. const ValueType arrayValueType(arrayRegOpnd->GetValueType());
  3203. const bool isJsArray = !arrayValueType.IsLikelyTypedArray();
  3204. Assert(isJsArray == arrayValueType.IsArrayOrObjectWithArray());
  3205. Assert(!isJsArray == arrayValueType.IsOptimizedTypedArray());
  3206. BasicBlock *const block = currentBlock;
  3207. if(!IsPrePass() &&
  3208. (arrayRegOpnd->HeadSegmentSym() || arrayRegOpnd->HeadSegmentLengthSym()) &&
  3209. (!isJsArray || instr->m_opcode != Js::OpCode::NoImplicitCallUses))
  3210. {
  3211. bool headSegmentIsLoadedButUnused =
  3212. instr->loadedArrayHeadSegment &&
  3213. arrayRegOpnd->HeadSegmentSym() &&
  3214. !block->upwardExposedUses->Test(arrayRegOpnd->HeadSegmentSym()->m_id);
  3215. const bool headSegmentLengthIsLoadedButUnused =
  3216. instr->loadedArrayHeadSegmentLength &&
  3217. arrayRegOpnd->HeadSegmentLengthSym() &&
  3218. !block->upwardExposedUses->Test(arrayRegOpnd->HeadSegmentLengthSym()->m_id);
  3219. if(headSegmentLengthIsLoadedButUnused && instr->extractedUpperBoundCheckWithoutHoisting)
  3220. {
  3221. // Find the upper bound check (index[src1] <= headSegmentLength[src2] + offset[dst])
  3222. IR::Instr *upperBoundCheck = this->globOpt->FindUpperBoundsCheckInstr(instr);
  3223. Assert(upperBoundCheck && upperBoundCheck != instr);
  3224. Assert(upperBoundCheck->GetSrc2()->AsRegOpnd()->m_sym == arrayRegOpnd->HeadSegmentLengthSym());
  3225. // Find the head segment length load
  3226. IR::Instr *headSegmentLengthLoad = this->globOpt->FindArraySegmentLoadInstr(upperBoundCheck);
  3227. Assert(headSegmentLengthLoad->GetDst()->AsRegOpnd()->m_sym == arrayRegOpnd->HeadSegmentLengthSym());
  3228. Assert(
  3229. headSegmentLengthLoad->GetSrc1()->AsIndirOpnd()->GetBaseOpnd()->m_sym ==
  3230. (isJsArray ? arrayRegOpnd->HeadSegmentSym() : arrayRegOpnd->m_sym));
  3231. // Fold the head segment length load into the upper bound check. Keep the load instruction there with a Nop so that
  3232. // the head segment length sym can be marked as unused before the Nop. The lowerer will remove it.
  3233. upperBoundCheck->ReplaceSrc2(headSegmentLengthLoad->UnlinkSrc1());
  3234. headSegmentLengthLoad->m_opcode = Js::OpCode::Nop;
  3235. if(isJsArray)
  3236. {
  3237. // The head segment length is on the head segment, so the bound check now uses the head segment sym
  3238. headSegmentIsLoadedButUnused = false;
  3239. }
  3240. }
  3241. if(headSegmentIsLoadedButUnused || headSegmentLengthIsLoadedButUnused)
  3242. {
  3243. // Check if the head segment / head segment length are being loaded here. If so, remove them and let the fast
  3244. // path load them since it does a better job.
  3245. IR::ArrayRegOpnd *noImplicitCallArrayUse = nullptr;
  3246. if(isJsArray)
  3247. {
  3248. IR::Opnd *const use =
  3249. FindNoImplicitCallUse(
  3250. instr,
  3251. arrayRegOpnd,
  3252. [&](IR::Opnd *const checkedSrc) -> bool
  3253. {
  3254. const ValueType checkedSrcValueType(checkedSrc->GetValueType());
  3255. if(!checkedSrcValueType.IsLikelyObject() ||
  3256. checkedSrcValueType.GetObjectType() != arrayValueType.GetObjectType())
  3257. {
  3258. return false;
  3259. }
  3260. IR::RegOpnd *const checkedRegSrc = checkedSrc->AsRegOpnd();
  3261. if(!checkedRegSrc->IsArrayRegOpnd())
  3262. {
  3263. return false;
  3264. }
  3265. IR::ArrayRegOpnd *const checkedArraySrc = checkedRegSrc->AsArrayRegOpnd();
  3266. if(headSegmentIsLoadedButUnused &&
  3267. checkedArraySrc->HeadSegmentSym() != arrayRegOpnd->HeadSegmentSym())
  3268. {
  3269. return false;
  3270. }
  3271. if(headSegmentLengthIsLoadedButUnused &&
  3272. checkedArraySrc->HeadSegmentLengthSym() != arrayRegOpnd->HeadSegmentLengthSym())
  3273. {
  3274. return false;
  3275. }
  3276. return true;
  3277. });
  3278. if(use)
  3279. {
  3280. noImplicitCallArrayUse = use->AsRegOpnd()->AsArrayRegOpnd();
  3281. }
  3282. }
  3283. else if(headSegmentLengthIsLoadedButUnused)
  3284. {
  3285. // A typed array's head segment length may be zeroed when the typed array's buffer is transferred to a web
  3286. // worker, so the head segment length sym use is included in a NoImplicitCallUses instruction. Since there
  3287. // are no forward uses of the head segment length sym, to allow removing the extracted head segment length
  3288. // load, the corresponding head segment length sym use in the NoImplicitCallUses instruction must also be
  3289. // removed.
  3290. IR::Instr *noImplicitCallUsesInstr;
  3291. IR::Opnd *const use =
  3292. FindNoImplicitCallUse(
  3293. instr,
  3294. arrayRegOpnd->HeadSegmentLengthSym(),
  3295. [&](IR::Opnd *const checkedSrc) -> bool
  3296. {
  3297. return checkedSrc->AsRegOpnd()->m_sym == arrayRegOpnd->HeadSegmentLengthSym();
  3298. },
  3299. &noImplicitCallUsesInstr);
  3300. if(use)
  3301. {
  3302. Assert(noImplicitCallUsesInstr);
  3303. Assert(!noImplicitCallUsesInstr->GetDst());
  3304. Assert(noImplicitCallUsesInstr->GetSrc1());
  3305. if(use == noImplicitCallUsesInstr->GetSrc1())
  3306. {
  3307. if(noImplicitCallUsesInstr->GetSrc2())
  3308. {
  3309. noImplicitCallUsesInstr->ReplaceSrc1(noImplicitCallUsesInstr->UnlinkSrc2());
  3310. }
  3311. else
  3312. {
  3313. noImplicitCallUsesInstr->FreeSrc1();
  3314. noImplicitCallUsesInstr->m_opcode = Js::OpCode::Nop;
  3315. }
  3316. }
  3317. else
  3318. {
  3319. Assert(use == noImplicitCallUsesInstr->GetSrc2());
  3320. noImplicitCallUsesInstr->FreeSrc2();
  3321. }
  3322. }
  3323. }
  3324. if(headSegmentIsLoadedButUnused &&
  3325. (!isJsArray || !arrayRegOpnd->HeadSegmentLengthSym() || headSegmentLengthIsLoadedButUnused))
  3326. {
  3327. // For JS arrays, the head segment length load is dependent on the head segment. So, only remove the head
  3328. // segment load if the head segment length load can also be removed.
  3329. arrayRegOpnd->RemoveHeadSegmentSym();
  3330. instr->loadedArrayHeadSegment = false;
  3331. if(noImplicitCallArrayUse)
  3332. {
  3333. noImplicitCallArrayUse->RemoveHeadSegmentSym();
  3334. }
  3335. }
  3336. if(headSegmentLengthIsLoadedButUnused)
  3337. {
  3338. arrayRegOpnd->RemoveHeadSegmentLengthSym();
  3339. instr->loadedArrayHeadSegmentLength = false;
  3340. if(noImplicitCallArrayUse)
  3341. {
  3342. noImplicitCallArrayUse->RemoveHeadSegmentLengthSym();
  3343. }
  3344. }
  3345. }
  3346. }
  3347. if(isJsArray && instr->m_opcode != Js::OpCode::NoImplicitCallUses)
  3348. {
  3349. // Only uses in NoImplicitCallUses instructions are counted toward liveness
  3350. return;
  3351. }
  3352. // Treat dependent syms as uses. For JS arrays, only uses in NoImplicitCallUses count because only then the assumptions made
  3353. // on the dependent syms are guaranteed to be valid. Similarly for typed arrays, a head segment length sym use counts toward
  3354. // liveness only in a NoImplicitCallUses instruction.
  3355. if(arrayRegOpnd->HeadSegmentSym())
  3356. {
  3357. ProcessStackSymUse(arrayRegOpnd->HeadSegmentSym(), true);
  3358. if(isJsArray)
  3359. {
  3360. block->noImplicitCallUses->Set(arrayRegOpnd->HeadSegmentSym()->m_id);
  3361. block->noImplicitCallJsArrayHeadSegmentSymUses->Set(arrayRegOpnd->HeadSegmentSym()->m_id);
  3362. }
  3363. }
  3364. if(arrayRegOpnd->HeadSegmentLengthSym())
  3365. {
  3366. if(isJsArray)
  3367. {
  3368. ProcessStackSymUse(arrayRegOpnd->HeadSegmentLengthSym(), true);
  3369. block->noImplicitCallUses->Set(arrayRegOpnd->HeadSegmentLengthSym()->m_id);
  3370. block->noImplicitCallJsArrayHeadSegmentSymUses->Set(arrayRegOpnd->HeadSegmentLengthSym()->m_id);
  3371. }
  3372. else
  3373. {
  3374. // ProcessNoImplicitCallUses automatically marks JS array reg opnds and their corresponding syms as live. A typed
  3375. // array's head segment length sym also needs to be marked as live at its use in the NoImplicitCallUses instruction,
  3376. // but it is just in a reg opnd. Flag the opnd to have the sym be marked as live when that instruction is processed.
  3377. Assert(!considerSymAsRealUseInNoImplicitCallUses);
  3378. IR::Opnd *const use =
  3379. FindNoImplicitCallUse(
  3380. instr,
  3381. arrayRegOpnd->HeadSegmentLengthSym(),
  3382. [&](IR::Opnd *const checkedSrc) -> bool
  3383. {
  3384. return checkedSrc->AsRegOpnd()->m_sym == arrayRegOpnd->HeadSegmentLengthSym();
  3385. });
  3386. if(use)
  3387. {
  3388. considerSymAsRealUseInNoImplicitCallUses = arrayRegOpnd->HeadSegmentLengthSym();
  3389. }
  3390. }
  3391. }
  3392. StackSym *const lengthSym = arrayRegOpnd->LengthSym();
  3393. if(lengthSym && lengthSym != arrayRegOpnd->HeadSegmentLengthSym())
  3394. {
  3395. ProcessStackSymUse(lengthSym, true);
  3396. Assert(arrayValueType.IsArray());
  3397. block->noImplicitCallUses->Set(lengthSym->m_id);
  3398. block->noImplicitCallArrayLengthSymUses->Set(lengthSym->m_id);
  3399. }
  3400. }
  3401. void
  3402. BackwardPass::ProcessNewScObject(IR::Instr* instr)
  3403. {
  3404. if (this->tag != Js::DeadStorePhase || IsCollectionPass())
  3405. {
  3406. return;
  3407. }
  3408. if (!instr->IsNewScObjectInstr())
  3409. {
  3410. return;
  3411. }
  3412. if (instr->HasBailOutInfo())
  3413. {
  3414. Assert(instr->IsProfiledInstr());
  3415. Assert(instr->GetBailOutKind() == IR::BailOutFailedCtorGuardCheck);
  3416. Assert(instr->GetDst()->IsRegOpnd());
  3417. BasicBlock * block = this->currentBlock;
  3418. StackSym* objSym = instr->GetDst()->AsRegOpnd()->GetStackSym();
  3419. if (block->upwardExposedUses->Test(objSym->m_id))
  3420. {
  3421. // If the object created here is used downstream, let's capture any property operations we must protect.
  3422. Assert(instr->GetDst()->AsRegOpnd()->GetStackSym()->HasObjectTypeSym());
  3423. JITTimeConstructorCache* ctorCache = instr->m_func->GetConstructorCache(static_cast<Js::ProfileId>(instr->AsProfiledInstr()->u.profileId));
  3424. if (block->stackSymToFinalType != nullptr)
  3425. {
  3426. // NewScObject is the origin of the object pointer. If we have a final type in hand, do the
  3427. // transition here.
  3428. AddPropertyCacheBucket *pBucket = block->stackSymToFinalType->Get(objSym->m_id);
  3429. if (pBucket &&
  3430. pBucket->GetInitialType() != nullptr &&
  3431. pBucket->GetFinalType() != pBucket->GetInitialType())
  3432. {
  3433. Assert(pBucket->GetInitialType() == ctorCache->GetType());
  3434. if (!this->IsPrePass())
  3435. {
  3436. this->InsertTypeTransition(instr->m_next, objSym, pBucket);
  3437. }
  3438. #if DBG
  3439. pBucket->deadStoreUnavailableInitialType = pBucket->GetInitialType();
  3440. if (pBucket->deadStoreUnavailableFinalType == nullptr)
  3441. {
  3442. pBucket->deadStoreUnavailableFinalType = pBucket->GetFinalType();
  3443. }
  3444. pBucket->SetInitialType(nullptr);
  3445. pBucket->SetFinalType(nullptr);
  3446. #else
  3447. block->stackSymToFinalType->Clear(objSym->m_id);
  3448. #endif
  3449. }
  3450. }
  3451. if (block->stackSymToGuardedProperties != nullptr)
  3452. {
  3453. ObjTypeGuardBucket* bucket = block->stackSymToGuardedProperties->Get(objSym->m_id);
  3454. if (bucket != nullptr)
  3455. {
  3456. BVSparse<JitArenaAllocator>* guardedPropertyOps = bucket->GetGuardedPropertyOps();
  3457. if (guardedPropertyOps != nullptr)
  3458. {
  3459. ctorCache->EnsureGuardedPropOps(this->func->m_alloc);
  3460. ctorCache->AddGuardedPropOps(guardedPropertyOps);
  3461. bucket->SetGuardedPropertyOps(nullptr);
  3462. JitAdelete(this->tempAlloc, guardedPropertyOps);
  3463. block->stackSymToGuardedProperties->Clear(objSym->m_id);
  3464. }
  3465. }
  3466. }
  3467. }
  3468. else
  3469. {
  3470. // If the object is not used downstream, let's remove the bailout and let the lowerer emit a fast path along with
  3471. // the fallback on helper, if the ctor cache ever became invalid.
  3472. instr->ClearBailOutInfo();
  3473. if (preOpBailOutInstrToProcess == instr)
  3474. {
  3475. preOpBailOutInstrToProcess = nullptr;
  3476. }
  3477. #if DBG
  3478. // We're creating a brand new object here, so no type check upstream could protect any properties of this
  3479. // object. Let's make sure we don't have any left to protect.
  3480. ObjTypeGuardBucket* bucket = block->stackSymToGuardedProperties != nullptr ?
  3481. block->stackSymToGuardedProperties->Get(objSym->m_id) : nullptr;
  3482. Assert(bucket == nullptr || bucket->GetGuardedPropertyOps()->IsEmpty());
  3483. #endif
  3484. }
  3485. }
  3486. }
  3487. void
  3488. BackwardPass::UpdateArrayValueTypes(IR::Instr *const instr, IR::Opnd *origOpnd)
  3489. {
  3490. Assert(tag == Js::DeadStorePhase);
  3491. Assert(!IsPrePass());
  3492. Assert(instr);
  3493. if(!origOpnd)
  3494. {
  3495. return;
  3496. }
  3497. IR::Instr *opndOwnerInstr = instr;
  3498. switch(instr->m_opcode)
  3499. {
  3500. case Js::OpCode::StElemC:
  3501. case Js::OpCode::StArrSegElemC:
  3502. // These may not be fixed if we are unsure about the type of the array they're storing to
  3503. // (because it relies on profile data) and we weren't able to hoist the array check.
  3504. return;
  3505. }
  3506. Sym *sym;
  3507. IR::Opnd* opnd = origOpnd;
  3508. IR::ArrayRegOpnd *arrayOpnd;
  3509. switch(opnd->GetKind())
  3510. {
  3511. case IR::OpndKindIndir:
  3512. opnd = opnd->AsIndirOpnd()->GetBaseOpnd();
  3513. // fall-through
  3514. case IR::OpndKindReg:
  3515. {
  3516. IR::RegOpnd *const regOpnd = opnd->AsRegOpnd();
  3517. sym = regOpnd->m_sym;
  3518. arrayOpnd = regOpnd->IsArrayRegOpnd() ? regOpnd->AsArrayRegOpnd() : nullptr;
  3519. break;
  3520. }
  3521. case IR::OpndKindSym:
  3522. sym = opnd->AsSymOpnd()->m_sym;
  3523. if(!sym->IsPropertySym())
  3524. {
  3525. return;
  3526. }
  3527. arrayOpnd = nullptr;
  3528. break;
  3529. default:
  3530. return;
  3531. }
  3532. const ValueType valueType(opnd->GetValueType());
  3533. if(!valueType.IsAnyOptimizedArray())
  3534. {
  3535. return;
  3536. }
  3537. const bool isJsArray = valueType.IsArrayOrObjectWithArray();
  3538. Assert(!isJsArray == valueType.IsOptimizedTypedArray());
  3539. const bool noForwardImplicitCallUses = currentBlock->noImplicitCallUses->IsEmpty();
  3540. bool changeArray = isJsArray && !opnd->IsValueTypeFixed() && noForwardImplicitCallUses;
  3541. bool changeNativeArray =
  3542. isJsArray &&
  3543. !opnd->IsValueTypeFixed() &&
  3544. !valueType.HasVarElements() &&
  3545. currentBlock->noImplicitCallNativeArrayUses->IsEmpty();
  3546. bool changeNoMissingValues =
  3547. isJsArray &&
  3548. !opnd->IsValueTypeFixed() &&
  3549. valueType.HasNoMissingValues() &&
  3550. currentBlock->noImplicitCallNoMissingValuesUses->IsEmpty();
  3551. const bool noForwardJsArrayHeadSegmentSymUses = currentBlock->noImplicitCallJsArrayHeadSegmentSymUses->IsEmpty();
  3552. bool removeHeadSegmentSym = isJsArray && arrayOpnd && arrayOpnd->HeadSegmentSym() && noForwardJsArrayHeadSegmentSymUses;
  3553. bool removeHeadSegmentLengthSym =
  3554. arrayOpnd &&
  3555. arrayOpnd->HeadSegmentLengthSym() &&
  3556. (isJsArray ? noForwardJsArrayHeadSegmentSymUses : noForwardImplicitCallUses);
  3557. Assert(!isJsArray || !arrayOpnd || !arrayOpnd->LengthSym() || valueType.IsArray());
  3558. bool removeLengthSym =
  3559. isJsArray &&
  3560. arrayOpnd &&
  3561. arrayOpnd->LengthSym() &&
  3562. currentBlock->noImplicitCallArrayLengthSymUses->IsEmpty();
  3563. if(!(changeArray || changeNoMissingValues || changeNativeArray || removeHeadSegmentSym || removeHeadSegmentLengthSym))
  3564. {
  3565. return;
  3566. }
  3567. // We have a definitely-array value type for the base, but either implicit calls are not currently being disabled for
  3568. // legally using the value type as a definite array, or we are not currently bailing out upon creating a missing value
  3569. // for legally using the value type as a definite array with no missing values.
  3570. // For source opnds, ensure that a NoImplicitCallUses immediately precedes this instruction. Otherwise, convert the value
  3571. // type to an appropriate version so that the lowerer doesn't incorrectly treat it as it says.
  3572. if(opnd != opndOwnerInstr->GetDst())
  3573. {
  3574. if(isJsArray)
  3575. {
  3576. IR::Opnd *const checkedSrc =
  3577. FindNoImplicitCallUse(
  3578. instr,
  3579. opnd,
  3580. [&](IR::Opnd *const checkedSrc) -> bool
  3581. {
  3582. const ValueType checkedSrcValueType(checkedSrc->GetValueType());
  3583. return
  3584. checkedSrcValueType.IsLikelyObject() &&
  3585. checkedSrcValueType.GetObjectType() == valueType.GetObjectType();
  3586. });
  3587. if(checkedSrc)
  3588. {
  3589. // Implicit calls will be disabled to the point immediately before this instruction
  3590. changeArray = false;
  3591. const ValueType checkedSrcValueType(checkedSrc->GetValueType());
  3592. if(changeNativeArray &&
  3593. !checkedSrcValueType.HasVarElements() &&
  3594. checkedSrcValueType.HasIntElements() == valueType.HasIntElements())
  3595. {
  3596. // If necessary, instructions before this will bail out on converting a native array
  3597. changeNativeArray = false;
  3598. }
  3599. if(changeNoMissingValues && checkedSrcValueType.HasNoMissingValues())
  3600. {
  3601. // If necessary, instructions before this will bail out on creating a missing value
  3602. changeNoMissingValues = false;
  3603. }
  3604. if((removeHeadSegmentSym || removeHeadSegmentLengthSym || removeLengthSym) && checkedSrc->IsRegOpnd())
  3605. {
  3606. IR::RegOpnd *const checkedRegSrc = checkedSrc->AsRegOpnd();
  3607. if(checkedRegSrc->IsArrayRegOpnd())
  3608. {
  3609. IR::ArrayRegOpnd *const checkedArraySrc = checkedSrc->AsRegOpnd()->AsArrayRegOpnd();
  3610. if(removeHeadSegmentSym && checkedArraySrc->HeadSegmentSym() == arrayOpnd->HeadSegmentSym())
  3611. {
  3612. // If necessary, instructions before this will bail out upon invalidating head segment sym
  3613. removeHeadSegmentSym = false;
  3614. }
  3615. if(removeHeadSegmentLengthSym &&
  3616. checkedArraySrc->HeadSegmentLengthSym() == arrayOpnd->HeadSegmentLengthSym())
  3617. {
  3618. // If necessary, instructions before this will bail out upon invalidating head segment length sym
  3619. removeHeadSegmentLengthSym = false;
  3620. }
  3621. if(removeLengthSym && checkedArraySrc->LengthSym() == arrayOpnd->LengthSym())
  3622. {
  3623. // If necessary, instructions before this will bail out upon invalidating a length sym
  3624. removeLengthSym = false;
  3625. }
  3626. }
  3627. }
  3628. }
  3629. }
  3630. else
  3631. {
  3632. Assert(removeHeadSegmentLengthSym);
  3633. // A typed array's head segment length may be zeroed when the typed array's buffer is transferred to a web worker,
  3634. // so the head segment length sym use is included in a NoImplicitCallUses instruction. Since there are no forward
  3635. // uses of any head segment length syms, to allow removing the extracted head segment length
  3636. // load, the corresponding head segment length sym use in the NoImplicitCallUses instruction must also be
  3637. // removed.
  3638. IR::Opnd *const use =
  3639. FindNoImplicitCallUse(
  3640. instr,
  3641. arrayOpnd->HeadSegmentLengthSym(),
  3642. [&](IR::Opnd *const checkedSrc) -> bool
  3643. {
  3644. return checkedSrc->AsRegOpnd()->m_sym == arrayOpnd->HeadSegmentLengthSym();
  3645. });
  3646. if(use)
  3647. {
  3648. // Implicit calls will be disabled to the point immediately before this instruction
  3649. removeHeadSegmentLengthSym = false;
  3650. }
  3651. }
  3652. }
  3653. if(changeArray || changeNativeArray)
  3654. {
  3655. if(arrayOpnd)
  3656. {
  3657. opnd = arrayOpnd->CopyAsRegOpnd(opndOwnerInstr->m_func);
  3658. if (origOpnd->IsIndirOpnd())
  3659. {
  3660. origOpnd->AsIndirOpnd()->ReplaceBaseOpnd(opnd->AsRegOpnd());
  3661. }
  3662. else
  3663. {
  3664. opndOwnerInstr->Replace(arrayOpnd, opnd);
  3665. }
  3666. arrayOpnd = nullptr;
  3667. }
  3668. opnd->SetValueType(valueType.ToLikely());
  3669. }
  3670. else
  3671. {
  3672. if(changeNoMissingValues)
  3673. {
  3674. opnd->SetValueType(valueType.SetHasNoMissingValues(false));
  3675. }
  3676. if(removeHeadSegmentSym)
  3677. {
  3678. Assert(arrayOpnd);
  3679. arrayOpnd->RemoveHeadSegmentSym();
  3680. }
  3681. if(removeHeadSegmentLengthSym)
  3682. {
  3683. Assert(arrayOpnd);
  3684. arrayOpnd->RemoveHeadSegmentLengthSym();
  3685. }
  3686. if(removeLengthSym)
  3687. {
  3688. Assert(arrayOpnd);
  3689. arrayOpnd->RemoveLengthSym();
  3690. }
  3691. }
  3692. }
  3693. void
  3694. BackwardPass::UpdateArrayBailOutKind(IR::Instr *const instr)
  3695. {
  3696. Assert(!IsPrePass());
  3697. Assert(instr);
  3698. Assert(instr->HasBailOutInfo());
  3699. if ((instr->m_opcode != Js::OpCode::StElemI_A && instr->m_opcode != Js::OpCode::StElemI_A_Strict &&
  3700. instr->m_opcode != Js::OpCode::Memcopy && instr->m_opcode != Js::OpCode::Memset) ||
  3701. !instr->GetDst()->IsIndirOpnd())
  3702. {
  3703. return;
  3704. }
  3705. IR::RegOpnd *const baseOpnd = instr->GetDst()->AsIndirOpnd()->GetBaseOpnd();
  3706. const ValueType baseValueType(baseOpnd->GetValueType());
  3707. if(baseValueType.IsNotArrayOrObjectWithArray())
  3708. {
  3709. return;
  3710. }
  3711. IR::BailOutKind includeBailOutKinds = IR::BailOutInvalid;
  3712. if(!baseValueType.IsNotNativeArray() &&
  3713. (!baseValueType.IsLikelyNativeArray() || instr->GetSrc1()->IsVar()) &&
  3714. !currentBlock->noImplicitCallNativeArrayUses->IsEmpty())
  3715. {
  3716. // There is an upwards-exposed use of a native array. Since the array referenced by this instruction can be aliased,
  3717. // this instruction needs to bail out if it converts the native array even if this array specifically is not
  3718. // upwards-exposed.
  3719. includeBailOutKinds |= IR::BailOutConvertedNativeArray;
  3720. }
  3721. if(baseOpnd->IsArrayRegOpnd() && baseOpnd->AsArrayRegOpnd()->EliminatedUpperBoundCheck())
  3722. {
  3723. if(instr->extractedUpperBoundCheckWithoutHoisting && !currentBlock->noImplicitCallJsArrayHeadSegmentSymUses->IsEmpty())
  3724. {
  3725. // See comment below regarding head segment invalidation. A failed upper bound check usually means that it will
  3726. // invalidate the head segment length, so change the bailout kind on the upper bound check to have it bail out for
  3727. // the right reason. Even though the store may actually occur in a non-head segment, which would not invalidate the
  3728. // head segment or length, any store outside the head segment bounds causes head segment load elimination to be
  3729. // turned off for the store, because the segment structure of the array is not guaranteed to be the same every time.
  3730. IR::Instr *upperBoundCheck = this->globOpt->FindUpperBoundsCheckInstr(instr);
  3731. Assert(upperBoundCheck && upperBoundCheck != instr);
  3732. if(upperBoundCheck->GetBailOutKind() == IR::BailOutOnArrayAccessHelperCall)
  3733. {
  3734. upperBoundCheck->SetBailOutKind(IR::BailOutOnInvalidatedArrayHeadSegment);
  3735. }
  3736. else
  3737. {
  3738. Assert(upperBoundCheck->GetBailOutKind() == IR::BailOutOnFailedHoistedBoundCheck);
  3739. }
  3740. }
  3741. }
  3742. else
  3743. {
  3744. if(!currentBlock->noImplicitCallJsArrayHeadSegmentSymUses->IsEmpty())
  3745. {
  3746. // There is an upwards-exposed use of a segment sym. Since the head segment syms referenced by this instruction can
  3747. // be aliased, this instruction needs to bail out if it changes the segment syms it references even if the ones it
  3748. // references specifically are not upwards-exposed. This bailout kind also guarantees that this element store will
  3749. // not create missing values.
  3750. includeBailOutKinds |= IR::BailOutOnInvalidatedArrayHeadSegment;
  3751. }
  3752. else if(
  3753. !currentBlock->noImplicitCallNoMissingValuesUses->IsEmpty() &&
  3754. !(instr->GetBailOutKind() & IR::BailOutOnArrayAccessHelperCall))
  3755. {
  3756. // There is an upwards-exposed use of an array with no missing values. Since the array referenced by this
  3757. // instruction can be aliased, this instruction needs to bail out if it creates a missing value in the array even if
  3758. // this array specifically is not upwards-exposed.
  3759. includeBailOutKinds |= IR::BailOutOnMissingValue;
  3760. }
  3761. if(!baseValueType.IsNotArray() && !currentBlock->noImplicitCallArrayLengthSymUses->IsEmpty())
  3762. {
  3763. // There is an upwards-exposed use of a length sym. Since the length sym referenced by this instruction can be
  3764. // aliased, this instruction needs to bail out if it changes the length sym it references even if the ones it
  3765. // references specifically are not upwards-exposed.
  3766. includeBailOutKinds |= IR::BailOutOnInvalidatedArrayLength;
  3767. }
  3768. }
  3769. if(!includeBailOutKinds)
  3770. {
  3771. return;
  3772. }
  3773. Assert(!(includeBailOutKinds & ~IR::BailOutKindBits));
  3774. instr->SetBailOutKind(instr->GetBailOutKind() | includeBailOutKinds);
  3775. }
  3776. bool
  3777. BackwardPass::ProcessStackSymUse(StackSym * stackSym, BOOLEAN isNonByteCodeUse)
  3778. {
  3779. BasicBlock * block = this->currentBlock;
  3780. if (this->DoByteCodeUpwardExposedUsed())
  3781. {
  3782. if (!isNonByteCodeUse && stackSym->HasByteCodeRegSlot())
  3783. {
  3784. // Always track the sym use on the var sym.
  3785. StackSym * byteCodeUseSym = stackSym;
  3786. if (byteCodeUseSym->IsTypeSpec())
  3787. {
  3788. // It has to have a var version for byte code regs
  3789. byteCodeUseSym = byteCodeUseSym->GetVarEquivSym(nullptr);
  3790. }
  3791. block->byteCodeUpwardExposedUsed->Set(byteCodeUseSym->m_id);
  3792. #if DBG
  3793. // We can only track first level function stack syms right now
  3794. if (byteCodeUseSym->GetByteCodeFunc() == this->func)
  3795. {
  3796. Js::RegSlot byteCodeRegSlot = byteCodeUseSym->GetByteCodeRegSlot();
  3797. if (block->byteCodeRestoreSyms[byteCodeRegSlot] != byteCodeUseSym)
  3798. {
  3799. AssertMsg(block->byteCodeRestoreSyms[byteCodeRegSlot] == nullptr,
  3800. "Can't have two active lifetime for the same byte code register");
  3801. block->byteCodeRestoreSyms[byteCodeRegSlot] = byteCodeUseSym;
  3802. }
  3803. }
  3804. #endif
  3805. }
  3806. }
  3807. if(IsCollectionPass())
  3808. {
  3809. return true;
  3810. }
  3811. if (this->DoMarkTempObjects())
  3812. {
  3813. Assert((block->loop != nullptr) == block->tempObjectTracker->HasTempTransferDependencies());
  3814. block->tempObjectTracker->ProcessUse(stackSym, this);
  3815. }
  3816. #if DBG
  3817. if (this->DoMarkTempObjectVerify())
  3818. {
  3819. Assert((block->loop != nullptr) == block->tempObjectVerifyTracker->HasTempTransferDependencies());
  3820. block->tempObjectVerifyTracker->ProcessUse(stackSym, this);
  3821. }
  3822. #endif
  3823. return !!block->upwardExposedUses->TestAndSet(stackSym->m_id);
  3824. }
  3825. bool
  3826. BackwardPass::ProcessSymUse(Sym * sym, bool isRegOpndUse, BOOLEAN isNonByteCodeUse)
  3827. {
  3828. BasicBlock * block = this->currentBlock;
  3829. if (CanDeadStoreInstrForScopeObjRemoval(sym))
  3830. {
  3831. return false;
  3832. }
  3833. if (sym->IsPropertySym())
  3834. {
  3835. PropertySym * propertySym = sym->AsPropertySym();
  3836. ProcessStackSymUse(propertySym->m_stackSym, isNonByteCodeUse);
  3837. if(IsCollectionPass())
  3838. {
  3839. return true;
  3840. }
  3841. Assert((block->fieldHoistCandidates != nullptr) == this->DoFieldHoistCandidates());
  3842. if (block->fieldHoistCandidates && this->currentInstr->TransfersSrcValue())
  3843. {
  3844. // If the instruction doesn't transfer the src value to dst, it will not be copyprop'd
  3845. // So we can't hoist those.
  3846. block->fieldHoistCandidates->Set(propertySym->m_id);
  3847. }
  3848. if (this->DoDeadStoreSlots())
  3849. {
  3850. block->slotDeadStoreCandidates->Clear(propertySym->m_id);
  3851. }
  3852. if (tag == Js::BackwardPhase)
  3853. {
  3854. // Backward phase tracks liveness of fields to tell GlobOpt where we may need bailout.
  3855. return this->ProcessPropertySymUse(propertySym);
  3856. }
  3857. else
  3858. {
  3859. // Dead-store phase tracks copy propped syms, so it only cares about ByteCodeUses we inserted,
  3860. // not live fields.
  3861. return false;
  3862. }
  3863. }
  3864. StackSym * stackSym = sym->AsStackSym();
  3865. bool isUsed = ProcessStackSymUse(stackSym, isNonByteCodeUse);
  3866. if (!IsCollectionPass() && isRegOpndUse && this->DoMarkTempNumbers())
  3867. {
  3868. // Collect mark temp number information
  3869. Assert((block->loop != nullptr) == block->tempNumberTracker->HasTempTransferDependencies());
  3870. block->tempNumberTracker->ProcessUse(stackSym, this);
  3871. }
  3872. return isUsed;
  3873. }
  3874. bool
  3875. BackwardPass::MayPropertyBeWrittenTo(Js::PropertyId propertyId)
  3876. {
  3877. return this->func->anyPropertyMayBeWrittenTo ||
  3878. (this->func->propertiesWrittenTo != nullptr && this->func->propertiesWrittenTo->ContainsKey(propertyId));
  3879. }
  3880. void
  3881. BackwardPass::ProcessPropertySymOpndUse(IR::PropertySymOpnd * opnd)
  3882. {
  3883. // If this operand doesn't participate in the type check sequence it's a pass-through.
  3884. // We will not set any bits on the operand and we will ignore them when lowering.
  3885. if (!opnd->IsTypeCheckSeqCandidate())
  3886. {
  3887. return;
  3888. }
  3889. AssertMsg(opnd->HasObjectTypeSym(), "Optimized property sym operand without a type sym?");
  3890. SymID typeSymId = opnd->GetObjectTypeSym()->m_id;
  3891. BasicBlock * block = this->currentBlock;
  3892. if (this->tag == Js::BackwardPhase)
  3893. {
  3894. // In the backward phase, we have no availability info, and we're trying to see
  3895. // where there are live fields so we can decide where to put bailouts.
  3896. Assert(opnd->MayNeedTypeCheckProtection());
  3897. block->upwardExposedFields->Set(typeSymId);
  3898. TrackObjTypeSpecWriteGuards(opnd, block);
  3899. }
  3900. else
  3901. {
  3902. // In the dead-store phase, we're trying to see where the lowered code needs to make sure to check
  3903. // types for downstream load/stores. We're also setting up the upward-exposed uses at loop headers
  3904. // so register allocation will be correct.
  3905. Assert(opnd->MayNeedTypeCheckProtection());
  3906. const bool isStore = opnd == this->currentInstr->GetDst();
  3907. // Note that we don't touch upwardExposedUses here.
  3908. if (opnd->IsTypeAvailable())
  3909. {
  3910. opnd->SetTypeDead(!block->upwardExposedFields->TestAndSet(typeSymId));
  3911. if (opnd->IsTypeChecked() && opnd->IsObjectHeaderInlined())
  3912. {
  3913. // The object's type must not change in a way that changes the layout.
  3914. // If we see a StFld with a type check bailout between here and the type check that guards this
  3915. // property, we must not dead-store the StFld's type check bailout, even if that operand's type appears
  3916. // dead, because that object may alias this one.
  3917. BVSparse<JitArenaAllocator>* bv = block->typesNeedingKnownObjectLayout;
  3918. if (bv == nullptr)
  3919. {
  3920. bv = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  3921. block->typesNeedingKnownObjectLayout = bv;
  3922. }
  3923. bv->Set(typeSymId);
  3924. }
  3925. }
  3926. else
  3927. {
  3928. opnd->SetTypeDead(
  3929. !block->upwardExposedFields->TestAndClear(typeSymId) &&
  3930. (
  3931. // Don't set the type dead if this is a store that may change the layout in a way that invalidates
  3932. // optimized load/stores downstream. Leave it non-dead in that case so the type check bailout
  3933. // is preserved and so that Lower will generate the bailout properly.
  3934. !isStore ||
  3935. !block->typesNeedingKnownObjectLayout ||
  3936. block->typesNeedingKnownObjectLayout->IsEmpty()
  3937. )
  3938. );
  3939. BVSparse<JitArenaAllocator>* bv = block->typesNeedingKnownObjectLayout;
  3940. if (bv != nullptr)
  3941. {
  3942. bv->Clear(typeSymId);
  3943. }
  3944. }
  3945. bool mayNeedTypeTransition = true;
  3946. if (!opnd->HasTypeMismatch() && func->DoGlobOpt())
  3947. {
  3948. mayNeedTypeTransition = !isStore;
  3949. }
  3950. if (mayNeedTypeTransition &&
  3951. !this->IsPrePass() &&
  3952. !this->currentInstr->HasBailOutInfo() &&
  3953. (opnd->NeedsPrimaryTypeCheck() ||
  3954. opnd->NeedsLocalTypeCheck() ||
  3955. opnd->NeedsLoadFromProtoTypeCheck()))
  3956. {
  3957. // This is a "checked" opnd that nevertheless will have some kind of type check generated for it.
  3958. // (Typical case is a load from prototype with no upstream guard.)
  3959. // If the type check fails, we will call a helper, which will require that the type be correct here.
  3960. // Final type can't be pushed up past this point. Do whatever type transition is required.
  3961. if (block->stackSymToFinalType != nullptr)
  3962. {
  3963. StackSym *baseSym = opnd->GetObjectSym();
  3964. AddPropertyCacheBucket *pBucket = block->stackSymToFinalType->Get(baseSym->m_id);
  3965. if (pBucket &&
  3966. pBucket->GetFinalType() != nullptr &&
  3967. pBucket->GetFinalType() != pBucket->GetInitialType())
  3968. {
  3969. this->InsertTypeTransition(this->currentInstr->m_next, baseSym, pBucket);
  3970. pBucket->SetFinalType(pBucket->GetInitialType());
  3971. }
  3972. }
  3973. }
  3974. if (!opnd->HasTypeMismatch() && func->DoGlobOpt())
  3975. {
  3976. // Do this after the above code, as the value of the final type may change there.
  3977. TrackAddPropertyTypes(opnd, block);
  3978. }
  3979. TrackObjTypeSpecProperties(opnd, block);
  3980. TrackObjTypeSpecWriteGuards(opnd, block);
  3981. }
  3982. }
  3983. void
  3984. BackwardPass::TrackObjTypeSpecProperties(IR::PropertySymOpnd *opnd, BasicBlock *block)
  3985. {
  3986. Assert(tag == Js::DeadStorePhase);
  3987. Assert(opnd->IsTypeCheckSeqCandidate());
  3988. // Now that we're in the dead store pass and we know definitively which operations will have a type
  3989. // check and which are protected by an upstream type check, we can push the lists of guarded properties
  3990. // up the flow graph and drop them on the type checks for the corresponding object symbol.
  3991. if (opnd->IsTypeCheckSeqParticipant())
  3992. {
  3993. // Add this operation to the list of guarded operations for this object symbol.
  3994. HashTable<ObjTypeGuardBucket>* stackSymToGuardedProperties = block->stackSymToGuardedProperties;
  3995. if (stackSymToGuardedProperties == nullptr)
  3996. {
  3997. stackSymToGuardedProperties = HashTable<ObjTypeGuardBucket>::New(this->tempAlloc, 8);
  3998. block->stackSymToGuardedProperties = stackSymToGuardedProperties;
  3999. }
  4000. StackSym* objSym = opnd->GetObjectSym();
  4001. ObjTypeGuardBucket* bucket = stackSymToGuardedProperties->FindOrInsertNew(objSym->m_id);
  4002. BVSparse<JitArenaAllocator>* guardedPropertyOps = bucket->GetGuardedPropertyOps();
  4003. if (guardedPropertyOps == nullptr)
  4004. {
  4005. // The bit vectors we push around the flow graph only need to live as long as this phase.
  4006. guardedPropertyOps = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  4007. bucket->SetGuardedPropertyOps(guardedPropertyOps);
  4008. }
  4009. #if DBG
  4010. FOREACH_BITSET_IN_SPARSEBV(propOpId, guardedPropertyOps)
  4011. {
  4012. ObjTypeSpecFldInfo* existingFldInfo = this->func->GetGlobalObjTypeSpecFldInfo(propOpId);
  4013. Assert(existingFldInfo != nullptr);
  4014. if (existingFldInfo->GetPropertyId() != opnd->GetPropertyId())
  4015. {
  4016. continue;
  4017. }
  4018. // It would be very nice to assert that the info we have for this property matches all properties guarded thus far.
  4019. // Unfortunately, in some cases of object pointer copy propagation into a loop, we may end up with conflicting
  4020. // information for the same property. We simply ignore the conflict and emit an equivalent type check, which
  4021. // will attempt to check for one property on two different slots, and obviously fail. Thus we may have a
  4022. // guaranteed bailout, but we'll simply re-JIT with equivalent object type spec disabled. To avoid this
  4023. // issue altogether, we would need to track the set of guarded properties along with the type value in the
  4024. // forward pass, and when a conflict is detected either not optimize the offending instruction, or correct
  4025. // its information based on the info from the property in the type value info.
  4026. //Assert(!existingFldInfo->IsPoly() || !opnd->IsPoly() || GlobOpt::AreTypeSetsIdentical(existingFldInfo->GetEquivalentTypeSet(), opnd->GetEquivalentTypeSet()));
  4027. //Assert(existingFldInfo->GetSlotIndex() == opnd->GetSlotIndex());
  4028. if (PHASE_TRACE(Js::EquivObjTypeSpecPhase, this->func) && !JITManager::GetJITManager()->IsJITServer())
  4029. {
  4030. if (existingFldInfo->IsPoly() && opnd->IsPoly() &&
  4031. (!GlobOpt::AreTypeSetsIdentical(existingFldInfo->GetEquivalentTypeSet(), opnd->GetEquivalentTypeSet()) ||
  4032. (existingFldInfo->GetSlotIndex() != opnd->GetSlotIndex())))
  4033. {
  4034. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  4035. Output::Print(_u("EquivObjTypeSpec: top function %s (%s): duplicate property clash on %s(#%d) on operation %u \n"),
  4036. this->func->GetJITFunctionBody()->GetDisplayName(), this->func->GetDebugNumberSet(debugStringBuffer),
  4037. this->func->GetInProcThreadContext()->GetPropertyRecord(opnd->GetPropertyId())->GetBuffer(), opnd->GetPropertyId(), opnd->GetObjTypeSpecFldId());
  4038. Output::Flush();
  4039. }
  4040. }
  4041. }
  4042. NEXT_BITSET_IN_SPARSEBV
  4043. #endif
  4044. bucket->AddToGuardedPropertyOps(opnd->GetObjTypeSpecFldId());
  4045. if (opnd->NeedsMonoCheck())
  4046. {
  4047. Assert(opnd->IsMono());
  4048. JITTypeHolder monoGuardType = opnd->IsInitialTypeChecked() ? opnd->GetInitialType() : opnd->GetType();
  4049. bucket->SetMonoGuardType(monoGuardType);
  4050. }
  4051. if (opnd->NeedsPrimaryTypeCheck())
  4052. {
  4053. // Grab the guarded properties which match this type check with respect to polymorphism and drop them
  4054. // on the operand. Only equivalent type checks can protect polymorphic properties to avoid a case where
  4055. // we have 1) a cache with type set {t1, t2} and property a, followed by 2) a cache with type t3 and
  4056. // property b, and 3) a cache with type set {t1, t2} and property c, where the slot index of property c
  4057. // on t1 and t2 is different than on t3. If cache 2 were to protect property c it would not verify that
  4058. // it resides on the correct slot for cache 3. Yes, an equivalent type check could protect monomorphic
  4059. // properties, but it would then unnecessarily verify their equivalence on the slow path.
  4060. // Also, make sure the guarded properties on the operand are allocated from the func's allocator to
  4061. // persists until lowering.
  4062. Assert(guardedPropertyOps != nullptr);
  4063. opnd->EnsureGuardedPropOps(this->func->m_alloc);
  4064. opnd->AddGuardedPropOps(guardedPropertyOps);
  4065. if (this->currentInstr->HasTypeCheckBailOut())
  4066. {
  4067. // Stop pushing the mono guard type up if it is being checked here.
  4068. if (bucket->NeedsMonoCheck())
  4069. {
  4070. if (this->currentInstr->HasEquivalentTypeCheckBailOut())
  4071. {
  4072. // Some instr protected by this one requires a monomorphic type check. (E.g., final type opt,
  4073. // fixed field not loaded from prototype.) Note the IsTypeAvailable test above: only do this at
  4074. // the initial type check that protects this path.
  4075. opnd->SetMonoGuardType(bucket->GetMonoGuardType());
  4076. this->currentInstr->ChangeEquivalentToMonoTypeCheckBailOut();
  4077. }
  4078. bucket->SetMonoGuardType(nullptr);
  4079. }
  4080. if (!opnd->IsTypeAvailable())
  4081. {
  4082. // Stop tracking the guarded properties if there's not another type check upstream.
  4083. bucket->SetGuardedPropertyOps(nullptr);
  4084. JitAdelete(this->tempAlloc, guardedPropertyOps);
  4085. block->stackSymToGuardedProperties->Clear(objSym->m_id);
  4086. }
  4087. }
  4088. #if DBG
  4089. {
  4090. // If there is no upstream type check that is live and could protect guarded properties, we better
  4091. // not have any properties remaining.
  4092. ObjTypeGuardBucket* objTypeGuardBucket = block->stackSymToGuardedProperties->Get(opnd->GetObjectSym()->m_id);
  4093. Assert(opnd->IsTypeAvailable() || objTypeGuardBucket == nullptr || objTypeGuardBucket->GetGuardedPropertyOps()->IsEmpty());
  4094. }
  4095. #endif
  4096. }
  4097. }
  4098. else if (opnd->NeedsLocalTypeCheck())
  4099. {
  4100. opnd->EnsureGuardedPropOps(this->func->m_alloc);
  4101. opnd->SetGuardedPropOp(opnd->GetObjTypeSpecFldId());
  4102. }
  4103. }
  4104. void
  4105. BackwardPass::TrackObjTypeSpecWriteGuards(IR::PropertySymOpnd *opnd, BasicBlock *block)
  4106. {
  4107. // TODO (ObjTypeSpec): Move write guard tracking to the forward pass, by recording on the type value
  4108. // which property IDs have been written since the last type check. This will result in more accurate
  4109. // tracking in cases when object pointer copy prop kicks in.
  4110. if (this->tag == Js::BackwardPhase)
  4111. {
  4112. // If this operation may need a write guard (load from proto or fixed field check) then add its
  4113. // write guard symbol to the map for this object. If it remains live (hasn't been written to)
  4114. // until the type check upstream, it will get recorded there so that the type check can be registered
  4115. // for invalidation on this property used in this operation.
  4116. // (ObjTypeSpec): Consider supporting polymorphic write guards as well. We can't currently distinguish between mono and
  4117. // poly write guards, and a type check can only protect operations matching with respect to polymorphism (see
  4118. // BackwardPass::TrackObjTypeSpecProperties for details), so for now we only target monomorphic operations.
  4119. if (opnd->IsMono() && opnd->MayNeedWriteGuardProtection())
  4120. {
  4121. if (block->stackSymToWriteGuardsMap == nullptr)
  4122. {
  4123. block->stackSymToWriteGuardsMap = HashTable<ObjWriteGuardBucket>::New(this->tempAlloc, 8);
  4124. }
  4125. ObjWriteGuardBucket* bucket = block->stackSymToWriteGuardsMap->FindOrInsertNew(opnd->GetObjectSym()->m_id);
  4126. BVSparse<JitArenaAllocator>* writeGuards = bucket->GetWriteGuards();
  4127. if (writeGuards == nullptr)
  4128. {
  4129. // The bit vectors we push around the flow graph only need to live as long as this phase.
  4130. writeGuards = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  4131. bucket->SetWriteGuards(writeGuards);
  4132. }
  4133. PropertySym *propertySym = opnd->m_sym->AsPropertySym();
  4134. Assert(propertySym->m_writeGuardSym != nullptr);
  4135. SymID writeGuardSymId = propertySym->m_writeGuardSym->m_id;
  4136. writeGuards->Set(writeGuardSymId);
  4137. }
  4138. // Record any live (upward exposed) write guards on this operation, if this operation may end up with
  4139. // a type check. If we ultimately don't need a type check here, we will simply ignore the guards, because
  4140. // an earlier type check will protect them.
  4141. if (!IsPrePass() && opnd->IsMono() && !opnd->IsTypeDead())
  4142. {
  4143. Assert(opnd->GetWriteGuards() == nullptr);
  4144. if (block->stackSymToWriteGuardsMap != nullptr)
  4145. {
  4146. ObjWriteGuardBucket* bucket = block->stackSymToWriteGuardsMap->Get(opnd->GetObjectSym()->m_id);
  4147. if (bucket != nullptr)
  4148. {
  4149. // Get all the write guards associated with this object sym and filter them down to those that
  4150. // are upward exposed. If we end up emitting a type check for this instruction, we will create
  4151. // a type property guard registered for all guarded proto properties and we will set the write
  4152. // guard syms live during forward pass, such that we can avoid unnecessary write guard type
  4153. // checks and bailouts on every proto property (as long as it hasn't been written to since the
  4154. // primary type check).
  4155. auto writeGuards = bucket->GetWriteGuards()->CopyNew(this->func->m_alloc);
  4156. writeGuards->And(block->upwardExposedFields);
  4157. opnd->SetWriteGuards(writeGuards);
  4158. }
  4159. }
  4160. }
  4161. }
  4162. else
  4163. {
  4164. // If we know this property has never been written to in this function (either on this object or any
  4165. // of its aliases) we don't need the local type check.
  4166. if (opnd->MayNeedWriteGuardProtection() && !opnd->IsWriteGuardChecked() && !MayPropertyBeWrittenTo(opnd->GetPropertyId()))
  4167. {
  4168. opnd->SetWriteGuardChecked(true);
  4169. }
  4170. // If we don't need a primary type check here let's clear the write guards. The primary type check upstream will
  4171. // register the type check for the corresponding properties.
  4172. if (!IsPrePass() && !opnd->NeedsPrimaryTypeCheck())
  4173. {
  4174. opnd->ClearWriteGuards();
  4175. }
  4176. }
  4177. }
  4178. void
  4179. BackwardPass::TrackAddPropertyTypes(IR::PropertySymOpnd *opnd, BasicBlock *block)
  4180. {
  4181. // Do the work of objtypespec add-property opt even if it's disabled by PHASE option, so that we have
  4182. // the dataflow info that can be inspected.
  4183. Assert(this->tag == Js::DeadStorePhase);
  4184. Assert(opnd->IsMono() || opnd->HasEquivalentTypeSet());
  4185. JITTypeHolder typeWithProperty = opnd->IsMono() ? opnd->GetType() : opnd->GetFirstEquivalentType();
  4186. JITTypeHolder typeWithoutProperty = opnd->HasInitialType() ? opnd->GetInitialType() : JITTypeHolder(nullptr);
  4187. if (typeWithoutProperty == nullptr ||
  4188. typeWithProperty == typeWithoutProperty ||
  4189. (opnd->IsTypeChecked() && !opnd->IsInitialTypeChecked()))
  4190. {
  4191. if (!this->IsPrePass() && block->stackSymToFinalType != nullptr && !this->currentInstr->HasBailOutInfo())
  4192. {
  4193. PropertySym *propertySym = opnd->m_sym->AsPropertySym();
  4194. AddPropertyCacheBucket *pBucket =
  4195. block->stackSymToFinalType->Get(propertySym->m_stackSym->m_id);
  4196. if (pBucket && pBucket->GetFinalType() != nullptr && pBucket->GetInitialType() != pBucket->GetFinalType())
  4197. {
  4198. opnd->SetFinalType(pBucket->GetFinalType());
  4199. }
  4200. }
  4201. return;
  4202. }
  4203. #if DBG
  4204. Assert(typeWithProperty != nullptr);
  4205. const JITTypeHandler * typeWithoutPropertyTypeHandler = typeWithoutProperty->GetTypeHandler();
  4206. const JITTypeHandler * typeWithPropertyTypeHandler = typeWithProperty->GetTypeHandler();
  4207. // TODO: OOP JIT, reenable assert
  4208. //Assert(typeWithoutPropertyTypeHandler->GetPropertyCount() + 1 == typeWithPropertyTypeHandler->GetPropertyCount());
  4209. AssertMsg(JITTypeHandler::IsTypeHandlerCompatibleForObjectHeaderInlining(typeWithoutPropertyTypeHandler, typeWithPropertyTypeHandler),
  4210. "TypeHandlers are not compatible for transition?");
  4211. Assert(typeWithoutPropertyTypeHandler->GetSlotCapacity() <= typeWithPropertyTypeHandler->GetSlotCapacity());
  4212. #endif
  4213. // If there's already a final type for this instance, record it on the operand.
  4214. // If not, start tracking it.
  4215. if (block->stackSymToFinalType == nullptr)
  4216. {
  4217. block->stackSymToFinalType = HashTable<AddPropertyCacheBucket>::New(this->tempAlloc, 8);
  4218. }
  4219. // Find or create the type-tracking record for this instance in this block.
  4220. PropertySym *propertySym = opnd->m_sym->AsPropertySym();
  4221. AddPropertyCacheBucket *pBucket =
  4222. block->stackSymToFinalType->FindOrInsertNew(propertySym->m_stackSym->m_id);
  4223. JITTypeHolder finalType(nullptr);
  4224. #if DBG
  4225. JITTypeHolder deadStoreUnavailableFinalType(nullptr);
  4226. #endif
  4227. if (pBucket->GetInitialType() == nullptr || opnd->GetType() != pBucket->GetInitialType())
  4228. {
  4229. #if DBG
  4230. if (opnd->GetType() == pBucket->deadStoreUnavailableInitialType)
  4231. {
  4232. deadStoreUnavailableFinalType = pBucket->deadStoreUnavailableFinalType;
  4233. }
  4234. #endif
  4235. // No info found, or the info was bad, so initialize it from this cache.
  4236. finalType = opnd->GetType();
  4237. pBucket->SetFinalType(finalType);
  4238. }
  4239. else
  4240. {
  4241. // Match: The type we push upward is now the typeWithoutProperty at this point,
  4242. // and the final type is the one we've been tracking.
  4243. finalType = pBucket->GetFinalType();
  4244. #if DBG
  4245. deadStoreUnavailableFinalType = pBucket->deadStoreUnavailableFinalType;
  4246. #endif
  4247. }
  4248. pBucket->SetInitialType(typeWithoutProperty);
  4249. if (!PHASE_OFF(Js::ObjTypeSpecStorePhase, this->func))
  4250. {
  4251. #if DBG
  4252. // We may regress in this case:
  4253. // if (b)
  4254. // t1 = {};
  4255. // o = t1;
  4256. // o.x =
  4257. // else
  4258. // t2 = {};
  4259. // o = t2;
  4260. // o.x =
  4261. // o.y =
  4262. //
  4263. // Where the backward pass will propagate the final type in o.y to o.x, then globopt will copy prop t1 and t2 to o.x.
  4264. // But not o.y (because of the merge). Then, in the dead store pass, o.y's final type will not propagate to t1.x and t2.x
  4265. // respectively, thus regression the final type. However, in both cases, the types of t1 and t2 are dead anyways.
  4266. //
  4267. // if the type is dead, we don't care if we have regressed the type, as no one is depending on it to skip type check anyways
  4268. if (!opnd->IsTypeDead())
  4269. {
  4270. // This is the type that would have been propagated if we didn't kill it because the type isn't available
  4271. JITTypeHolder checkFinalType = deadStoreUnavailableFinalType != nullptr ? deadStoreUnavailableFinalType : finalType;
  4272. if (opnd->HasFinalType() && opnd->GetFinalType() != checkFinalType)
  4273. {
  4274. // Final type discovery must be progressively better (unless we kill it in the deadstore pass
  4275. // when the type is not available during the forward pass)
  4276. const JITTypeHandler * oldFinalTypeHandler = opnd->GetFinalType()->GetTypeHandler();
  4277. const JITTypeHandler * checkFinalTypeHandler = checkFinalType->GetTypeHandler();
  4278. // TODO: OOP JIT, enable assert
  4279. //Assert(oldFinalTypeHandler->GetPropertyCount() < checkFinalTypeHandler->GetPropertyCount());
  4280. AssertMsg(JITTypeHandler::IsTypeHandlerCompatibleForObjectHeaderInlining(oldFinalTypeHandler, checkFinalTypeHandler),
  4281. "TypeHandlers should be compatible for transition.");
  4282. Assert(oldFinalTypeHandler->GetSlotCapacity() <= checkFinalTypeHandler->GetSlotCapacity());
  4283. }
  4284. }
  4285. #endif
  4286. Assert(opnd->IsBeingAdded());
  4287. if (!this->IsPrePass())
  4288. {
  4289. opnd->SetFinalType(finalType);
  4290. }
  4291. if (!opnd->IsTypeChecked())
  4292. {
  4293. // Transition from initial to final type will only happen at type check points.
  4294. if (opnd->IsTypeAvailable())
  4295. {
  4296. pBucket->SetFinalType(pBucket->GetInitialType());
  4297. }
  4298. }
  4299. }
  4300. #if DBG_DUMP
  4301. if (PHASE_TRACE(Js::ObjTypeSpecStorePhase, this->func))
  4302. {
  4303. Output::Print(_u("ObjTypeSpecStore: "));
  4304. this->currentInstr->Dump();
  4305. pBucket->Dump();
  4306. }
  4307. #endif
  4308. // In the dead-store pass, we have forward information that tells us whether a "final type"
  4309. // reached this point from an earlier store. If it didn't (i.e., it's not available here),
  4310. // remove it from the backward map so that upstream stores will use the final type that is
  4311. // live there. (This avoids unnecessary bailouts in cases where the final type is only live
  4312. // on one branch of an "if", a case that the initial backward pass can't detect.)
  4313. // An example:
  4314. // if (cond)
  4315. // o.x =
  4316. // o.y =
  4317. if (!opnd->IsTypeAvailable())
  4318. {
  4319. #if DBG
  4320. pBucket->deadStoreUnavailableInitialType = pBucket->GetInitialType();
  4321. if (pBucket->deadStoreUnavailableFinalType == nullptr)
  4322. {
  4323. pBucket->deadStoreUnavailableFinalType = pBucket->GetFinalType();
  4324. }
  4325. pBucket->SetInitialType(nullptr);
  4326. pBucket->SetFinalType(nullptr);
  4327. #else
  4328. block->stackSymToFinalType->Clear(propertySym->m_stackSym->m_id);
  4329. #endif
  4330. }
  4331. }
  4332. void
  4333. BackwardPass::InsertTypeTransition(IR::Instr *instrInsertBefore, int symId, AddPropertyCacheBucket *data)
  4334. {
  4335. StackSym *objSym = this->func->m_symTable->FindStackSym(symId);
  4336. Assert(objSym);
  4337. this->InsertTypeTransition(instrInsertBefore, objSym, data);
  4338. }
  4339. void
  4340. BackwardPass::InsertTypeTransition(IR::Instr *instrInsertBefore, StackSym *objSym, AddPropertyCacheBucket *data)
  4341. {
  4342. IR::RegOpnd *baseOpnd = IR::RegOpnd::New(objSym, TyMachReg, this->func);
  4343. baseOpnd->SetIsJITOptimizedReg(true);
  4344. IR::AddrOpnd *initialTypeOpnd =
  4345. IR::AddrOpnd::New(data->GetInitialType()->GetAddr(), IR::AddrOpndKindDynamicType, this->func);
  4346. initialTypeOpnd->m_metadata = data->GetInitialType().t;
  4347. IR::AddrOpnd *finalTypeOpnd =
  4348. IR::AddrOpnd::New(data->GetFinalType()->GetAddr(), IR::AddrOpndKindDynamicType, this->func);
  4349. finalTypeOpnd->m_metadata = data->GetFinalType().t;
  4350. IR::Instr *adjustTypeInstr =
  4351. IR::Instr::New(Js::OpCode::AdjustObjType, finalTypeOpnd, baseOpnd, initialTypeOpnd, this->func);
  4352. instrInsertBefore->InsertBefore(adjustTypeInstr);
  4353. }
  4354. void
  4355. BackwardPass::InsertTypeTransitionAfterInstr(IR::Instr *instr, int symId, AddPropertyCacheBucket *data)
  4356. {
  4357. if (!this->IsPrePass())
  4358. {
  4359. // Transition to the final type if we don't bail out.
  4360. if (instr->EndsBasicBlock())
  4361. {
  4362. // The instr with the bailout is something like a branch that may not fall through.
  4363. // Insert the transitions instead at the beginning of each successor block.
  4364. this->InsertTypeTransitionsAtPriorSuccessors(this->currentBlock, nullptr, symId, data);
  4365. }
  4366. else
  4367. {
  4368. this->InsertTypeTransition(instr->m_next, symId, data);
  4369. }
  4370. }
  4371. // Note: we could probably clear this entry out of the table, but I don't know
  4372. // whether it's worth it, because it's likely coming right back.
  4373. data->SetFinalType(data->GetInitialType());
  4374. }
  4375. void
  4376. BackwardPass::InsertTypeTransitionAtBlock(BasicBlock *block, int symId, AddPropertyCacheBucket *data)
  4377. {
  4378. bool inserted = false;
  4379. FOREACH_INSTR_IN_BLOCK(instr, block)
  4380. {
  4381. if (instr->IsRealInstr())
  4382. {
  4383. // Check for pre-existing type transition. There may be more than one AdjustObjType here,
  4384. // so look at them all.
  4385. if (instr->m_opcode == Js::OpCode::AdjustObjType)
  4386. {
  4387. if (instr->GetSrc1()->AsRegOpnd()->m_sym->m_id == (SymID)symId)
  4388. {
  4389. // This symbol already has a type transition at this point.
  4390. // It *must* be doing the same transition we're already trying to do.
  4391. Assert((intptr_t)instr->GetDst()->AsAddrOpnd()->m_address == data->GetFinalType()->GetAddr() &&
  4392. (intptr_t)instr->GetSrc2()->AsAddrOpnd()->m_address == data->GetInitialType()->GetAddr());
  4393. // Nothing to do.
  4394. return;
  4395. }
  4396. }
  4397. else
  4398. {
  4399. this->InsertTypeTransition(instr, symId, data);
  4400. inserted = true;
  4401. break;
  4402. }
  4403. }
  4404. }
  4405. NEXT_INSTR_IN_BLOCK;
  4406. if (!inserted)
  4407. {
  4408. Assert(block->GetLastInstr()->m_next);
  4409. this->InsertTypeTransition(block->GetLastInstr()->m_next, symId, data);
  4410. }
  4411. }
  4412. void
  4413. BackwardPass::InsertTypeTransitionsAtPriorSuccessors(
  4414. BasicBlock *block,
  4415. BasicBlock *blockSucc,
  4416. int symId,
  4417. AddPropertyCacheBucket *data)
  4418. {
  4419. // For each successor of block prior to blockSucc, adjust the type.
  4420. FOREACH_SUCCESSOR_BLOCK(blockFix, block)
  4421. {
  4422. if (blockFix == blockSucc)
  4423. {
  4424. return;
  4425. }
  4426. this->InsertTypeTransitionAtBlock(blockFix, symId, data);
  4427. }
  4428. NEXT_SUCCESSOR_BLOCK;
  4429. }
  4430. void
  4431. BackwardPass::InsertTypeTransitionsAtPotentialKills()
  4432. {
  4433. // Final types can't be pushed up past certain instructions.
  4434. IR::Instr *instr = this->currentInstr;
  4435. if (instr->HasBailOutInfo() || instr->m_opcode == Js::OpCode::UpdateNewScObjectCache)
  4436. {
  4437. // Final types can't be pushed up past a bailout point.
  4438. // Insert any transitions called for by the current state of add-property buckets.
  4439. // Also do this for ctor cache updates, to avoid putting a type in the ctor cache that extends past
  4440. // the end of the ctor that the cache covers.
  4441. this->ForEachAddPropertyCacheBucket([&](int symId, AddPropertyCacheBucket *data)->bool {
  4442. this->InsertTypeTransitionAfterInstr(instr, symId, data);
  4443. return false;
  4444. });
  4445. }
  4446. else
  4447. {
  4448. // If this is a load/store that expects an object-header-inlined type, don't push another sym's transition from
  4449. // object-header-inlined to non-object-header-inlined type past it, because the two syms may be aliases.
  4450. IR::PropertySymOpnd *propertySymOpnd = instr->GetPropertySymOpnd();
  4451. if (propertySymOpnd && propertySymOpnd->IsObjectHeaderInlined())
  4452. {
  4453. SymID opndId = propertySymOpnd->m_sym->AsPropertySym()->m_stackSym->m_id;
  4454. this->ForEachAddPropertyCacheBucket([&](int symId, AddPropertyCacheBucket *data)->bool {
  4455. if ((SymID)symId == opndId)
  4456. {
  4457. // This is the sym we're tracking. No aliasing to worry about.
  4458. return false;
  4459. }
  4460. if (propertySymOpnd->IsMono() && data->GetInitialType() != propertySymOpnd->GetType())
  4461. {
  4462. // Type mismatch in a monomorphic case -- no aliasing.
  4463. return false;
  4464. }
  4465. if (this->TransitionUndoesObjectHeaderInlining(data))
  4466. {
  4467. // We're transitioning from inlined to non-inlined, so we can't push it up any farther.
  4468. this->InsertTypeTransitionAfterInstr(instr, symId, data);
  4469. }
  4470. return false;
  4471. });
  4472. }
  4473. }
  4474. }
  4475. template<class Fn>
  4476. void
  4477. BackwardPass::ForEachAddPropertyCacheBucket(Fn fn)
  4478. {
  4479. BasicBlock *block = this->currentBlock;
  4480. if (block->stackSymToFinalType == nullptr)
  4481. {
  4482. return;
  4483. }
  4484. FOREACH_HASHTABLE_ENTRY(AddPropertyCacheBucket, bucket, block->stackSymToFinalType)
  4485. {
  4486. AddPropertyCacheBucket *data = &bucket.element;
  4487. if (data->GetInitialType() != nullptr &&
  4488. data->GetInitialType() != data->GetFinalType())
  4489. {
  4490. bool done = fn(bucket.value, data);
  4491. if (done)
  4492. {
  4493. break;
  4494. }
  4495. }
  4496. }
  4497. NEXT_HASHTABLE_ENTRY;
  4498. }
  4499. bool
  4500. BackwardPass::TransitionUndoesObjectHeaderInlining(AddPropertyCacheBucket *data) const
  4501. {
  4502. JITTypeHolder type = data->GetInitialType();
  4503. if (type == nullptr || !Js::DynamicType::Is(type->GetTypeId()))
  4504. {
  4505. return false;
  4506. }
  4507. if (!type->GetTypeHandler()->IsObjectHeaderInlinedTypeHandler())
  4508. {
  4509. return false;
  4510. }
  4511. type = data->GetFinalType();
  4512. if (type == nullptr || !Js::DynamicType::Is(type->GetTypeId()))
  4513. {
  4514. return false;
  4515. }
  4516. return !type->GetTypeHandler()->IsObjectHeaderInlinedTypeHandler();
  4517. }
  4518. void
  4519. BackwardPass::CollectCloneStrCandidate(IR::Opnd * opnd)
  4520. {
  4521. IR::RegOpnd *regOpnd = opnd->AsRegOpnd();
  4522. Assert(regOpnd != nullptr);
  4523. StackSym *sym = regOpnd->m_sym;
  4524. if (tag == Js::BackwardPhase
  4525. && currentInstr->m_opcode == Js::OpCode::Add_A
  4526. && currentInstr->GetSrc1() == opnd
  4527. && !this->IsPrePass()
  4528. && !this->IsCollectionPass()
  4529. && this->currentBlock->loop)
  4530. {
  4531. Assert(currentBlock->cloneStrCandidates != nullptr);
  4532. currentBlock->cloneStrCandidates->Set(sym->m_id);
  4533. }
  4534. }
  4535. void
  4536. BackwardPass::InvalidateCloneStrCandidate(IR::Opnd * opnd)
  4537. {
  4538. IR::RegOpnd *regOpnd = opnd->AsRegOpnd();
  4539. Assert(regOpnd != nullptr);
  4540. StackSym *sym = regOpnd->m_sym;
  4541. if (tag == Js::BackwardPhase &&
  4542. (currentInstr->m_opcode != Js::OpCode::Add_A || currentInstr->GetSrc1()->AsRegOpnd()->m_sym->m_id != sym->m_id) &&
  4543. !this->IsPrePass() &&
  4544. !this->IsCollectionPass() &&
  4545. this->currentBlock->loop)
  4546. {
  4547. currentBlock->cloneStrCandidates->Clear(sym->m_id);
  4548. }
  4549. }
  4550. void
  4551. BackwardPass::ProcessUse(IR::Opnd * opnd)
  4552. {
  4553. switch (opnd->GetKind())
  4554. {
  4555. case IR::OpndKindReg:
  4556. {
  4557. IR::RegOpnd *regOpnd = opnd->AsRegOpnd();
  4558. StackSym *sym = regOpnd->m_sym;
  4559. if (!IsCollectionPass())
  4560. {
  4561. // isTempLastUse is only used for string concat right now, so lets not mark it if it's not a string.
  4562. // If it's upward exposed, it is not it's last use.
  4563. if (regOpnd->m_isTempLastUse && (regOpnd->GetValueType().IsNotString() || this->currentBlock->upwardExposedUses->Test(sym->m_id) || sym->m_mayNotBeTempLastUse))
  4564. {
  4565. regOpnd->m_isTempLastUse = false;
  4566. }
  4567. this->CollectCloneStrCandidate(opnd);
  4568. }
  4569. this->DoSetDead(regOpnd, !this->ProcessSymUse(sym, true, regOpnd->GetIsJITOptimizedReg()));
  4570. if (IsCollectionPass())
  4571. {
  4572. break;
  4573. }
  4574. if (tag == Js::DeadStorePhase && regOpnd->IsArrayRegOpnd())
  4575. {
  4576. ProcessArrayRegOpndUse(currentInstr, regOpnd->AsArrayRegOpnd());
  4577. }
  4578. if (currentInstr->m_opcode == Js::OpCode::BailOnNotArray)
  4579. {
  4580. Assert(tag == Js::DeadStorePhase);
  4581. const ValueType valueType(regOpnd->GetValueType());
  4582. if(valueType.IsLikelyArrayOrObjectWithArray())
  4583. {
  4584. currentBlock->noImplicitCallUses->Clear(sym->m_id);
  4585. // We are being conservative here to always check for missing value
  4586. // if any of them expect no missing value. That is because we don't know
  4587. // what set of sym is equivalent (copied) from the one we are testing for right now.
  4588. if(valueType.HasNoMissingValues() &&
  4589. !currentBlock->noImplicitCallNoMissingValuesUses->IsEmpty() &&
  4590. !IsPrePass())
  4591. {
  4592. // There is a use of this sym that requires this array to have no missing values, so this instruction
  4593. // needs to bail out if the array has missing values.
  4594. Assert(currentInstr->GetBailOutKind() == IR::BailOutOnNotArray ||
  4595. currentInstr->GetBailOutKind() == IR::BailOutOnNotNativeArray);
  4596. currentInstr->SetBailOutKind(currentInstr->GetBailOutKind() | IR::BailOutOnMissingValue);
  4597. }
  4598. currentBlock->noImplicitCallNoMissingValuesUses->Clear(sym->m_id);
  4599. currentBlock->noImplicitCallNativeArrayUses->Clear(sym->m_id);
  4600. }
  4601. }
  4602. }
  4603. break;
  4604. case IR::OpndKindSym:
  4605. {
  4606. IR::SymOpnd *symOpnd = opnd->AsSymOpnd();
  4607. Sym * sym = symOpnd->m_sym;
  4608. this->DoSetDead(symOpnd, !this->ProcessSymUse(sym, false, opnd->GetIsJITOptimizedReg()));
  4609. if (IsCollectionPass())
  4610. {
  4611. break;
  4612. }
  4613. if (sym->IsPropertySym())
  4614. {
  4615. // TODO: We don't have last use info for property sym
  4616. // and we don't set the last use of the stacksym inside the property sym
  4617. if (tag == Js::BackwardPhase)
  4618. {
  4619. if (opnd->AsSymOpnd()->IsPropertySymOpnd())
  4620. {
  4621. this->globOpt->PreparePropertySymOpndForTypeCheckSeq(symOpnd->AsPropertySymOpnd(), this->currentInstr, this->currentBlock->loop);
  4622. }
  4623. }
  4624. if (this->DoMarkTempNumbersOnTempObjects())
  4625. {
  4626. this->currentBlock->tempNumberTracker->ProcessPropertySymUse(symOpnd, this->currentInstr, this);
  4627. }
  4628. if (symOpnd->IsPropertySymOpnd())
  4629. {
  4630. this->ProcessPropertySymOpndUse(symOpnd->AsPropertySymOpnd());
  4631. }
  4632. }
  4633. }
  4634. break;
  4635. case IR::OpndKindIndir:
  4636. {
  4637. IR::IndirOpnd * indirOpnd = opnd->AsIndirOpnd();
  4638. IR::RegOpnd * baseOpnd = indirOpnd->GetBaseOpnd();
  4639. this->DoSetDead(baseOpnd, !this->ProcessSymUse(baseOpnd->m_sym, false, baseOpnd->GetIsJITOptimizedReg()));
  4640. IR::RegOpnd * indexOpnd = indirOpnd->GetIndexOpnd();
  4641. if (indexOpnd)
  4642. {
  4643. this->DoSetDead(indexOpnd, !this->ProcessSymUse(indexOpnd->m_sym, false, indexOpnd->GetIsJITOptimizedReg()));
  4644. }
  4645. if(IsCollectionPass())
  4646. {
  4647. break;
  4648. }
  4649. if (this->DoMarkTempNumbersOnTempObjects())
  4650. {
  4651. this->currentBlock->tempNumberTracker->ProcessIndirUse(indirOpnd, currentInstr, this);
  4652. }
  4653. if(tag == Js::DeadStorePhase && baseOpnd->IsArrayRegOpnd())
  4654. {
  4655. ProcessArrayRegOpndUse(currentInstr, baseOpnd->AsArrayRegOpnd());
  4656. }
  4657. }
  4658. break;
  4659. }
  4660. }
  4661. bool
  4662. BackwardPass::ProcessPropertySymUse(PropertySym *propertySym)
  4663. {
  4664. Assert(this->tag == Js::BackwardPhase);
  4665. BasicBlock *block = this->currentBlock;
  4666. bool isLive = !!block->upwardExposedFields->TestAndSet(propertySym->m_id);
  4667. if (propertySym->m_propertyEquivSet)
  4668. {
  4669. block->upwardExposedFields->Or(propertySym->m_propertyEquivSet);
  4670. }
  4671. return isLive;
  4672. }
  4673. void
  4674. BackwardPass::MarkTemp(StackSym * sym)
  4675. {
  4676. Assert(!IsCollectionPass());
  4677. // Don't care about type specialized syms
  4678. if (!sym->IsVar())
  4679. {
  4680. return;
  4681. }
  4682. BasicBlock * block = this->currentBlock;
  4683. if (this->DoMarkTempNumbers())
  4684. {
  4685. Assert((block->loop != nullptr) == block->tempNumberTracker->HasTempTransferDependencies());
  4686. block->tempNumberTracker->MarkTemp(sym, this);
  4687. }
  4688. if (this->DoMarkTempObjects())
  4689. {
  4690. Assert((block->loop != nullptr) == block->tempObjectTracker->HasTempTransferDependencies());
  4691. block->tempObjectTracker->MarkTemp(sym, this);
  4692. }
  4693. #if DBG
  4694. if (this->DoMarkTempObjectVerify())
  4695. {
  4696. Assert((block->loop != nullptr) == block->tempObjectVerifyTracker->HasTempTransferDependencies());
  4697. block->tempObjectVerifyTracker->MarkTemp(sym, this);
  4698. }
  4699. #endif
  4700. }
  4701. void
  4702. BackwardPass::MarkTempProcessInstr(IR::Instr * instr)
  4703. {
  4704. Assert(!IsCollectionPass());
  4705. if (this->currentBlock->isDead)
  4706. {
  4707. return;
  4708. }
  4709. BasicBlock * block;
  4710. block = this->currentBlock;
  4711. if (this->DoMarkTempNumbers())
  4712. {
  4713. block->tempNumberTracker->ProcessInstr(instr, this);
  4714. }
  4715. if (this->DoMarkTempObjects())
  4716. {
  4717. block->tempObjectTracker->ProcessInstr(instr);
  4718. }
  4719. #if DBG
  4720. if (this->DoMarkTempObjectVerify())
  4721. {
  4722. block->tempObjectVerifyTracker->ProcessInstr(instr, this);
  4723. }
  4724. #endif
  4725. }
  4726. #if DBG_DUMP
  4727. void
  4728. BackwardPass::DumpMarkTemp()
  4729. {
  4730. Assert(!IsCollectionPass());
  4731. BasicBlock * block = this->currentBlock;
  4732. if (this->DoMarkTempNumbers())
  4733. {
  4734. block->tempNumberTracker->Dump();
  4735. }
  4736. if (this->DoMarkTempObjects())
  4737. {
  4738. block->tempObjectTracker->Dump();
  4739. }
  4740. #if DBG
  4741. if (this->DoMarkTempObjectVerify())
  4742. {
  4743. block->tempObjectVerifyTracker->Dump();
  4744. }
  4745. #endif
  4746. }
  4747. #endif
  4748. void
  4749. BackwardPass::SetSymIsUsedOnlyInNumberIfLastUse(IR::Opnd *const opnd)
  4750. {
  4751. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  4752. if (stackSym && !currentBlock->upwardExposedUses->Test(stackSym->m_id))
  4753. {
  4754. symUsedOnlyForNumberBySymId->Set(stackSym->m_id);
  4755. }
  4756. }
  4757. void
  4758. BackwardPass::SetSymIsNotUsedOnlyInNumber(IR::Opnd *const opnd)
  4759. {
  4760. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  4761. if (stackSym)
  4762. {
  4763. symUsedOnlyForNumberBySymId->Clear(stackSym->m_id);
  4764. }
  4765. }
  4766. void
  4767. BackwardPass::SetSymIsUsedOnlyInBitOpsIfLastUse(IR::Opnd *const opnd)
  4768. {
  4769. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  4770. if (stackSym && !currentBlock->upwardExposedUses->Test(stackSym->m_id))
  4771. {
  4772. symUsedOnlyForBitOpsBySymId->Set(stackSym->m_id);
  4773. }
  4774. }
  4775. void
  4776. BackwardPass::SetSymIsNotUsedOnlyInBitOps(IR::Opnd *const opnd)
  4777. {
  4778. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  4779. if (stackSym)
  4780. {
  4781. symUsedOnlyForBitOpsBySymId->Clear(stackSym->m_id);
  4782. }
  4783. }
  4784. void
  4785. BackwardPass::TrackBitWiseOrNumberOp(IR::Instr *const instr)
  4786. {
  4787. Assert(instr);
  4788. const bool trackBitWiseop = DoTrackBitOpsOrNumber();
  4789. const bool trackNumberop = trackBitWiseop;
  4790. const Js::OpCode opcode = instr->m_opcode;
  4791. StackSym *const dstSym = IR::RegOpnd::TryGetStackSym(instr->GetDst());
  4792. if (!trackBitWiseop && !trackNumberop)
  4793. {
  4794. return;
  4795. }
  4796. if (!instr->IsRealInstr())
  4797. {
  4798. return;
  4799. }
  4800. if (dstSym)
  4801. {
  4802. // For a dst where the def is in this block, transfer the current info into the instruction
  4803. if (trackBitWiseop && symUsedOnlyForBitOpsBySymId->TestAndClear(dstSym->m_id))
  4804. {
  4805. instr->dstIsAlwaysConvertedToInt32 = true;
  4806. }
  4807. if (trackNumberop && symUsedOnlyForNumberBySymId->TestAndClear(dstSym->m_id))
  4808. {
  4809. instr->dstIsAlwaysConvertedToNumber = true;
  4810. }
  4811. }
  4812. // If the instruction can cause src values to escape the local scope, the srcs can't be optimized
  4813. if (OpCodeAttr::NonTempNumberSources(opcode))
  4814. {
  4815. if (trackBitWiseop)
  4816. {
  4817. SetSymIsNotUsedOnlyInBitOps(instr->GetSrc1());
  4818. SetSymIsNotUsedOnlyInBitOps(instr->GetSrc2());
  4819. }
  4820. if (trackNumberop)
  4821. {
  4822. SetSymIsNotUsedOnlyInNumber(instr->GetSrc1());
  4823. SetSymIsNotUsedOnlyInNumber(instr->GetSrc2());
  4824. }
  4825. return;
  4826. }
  4827. if (trackBitWiseop)
  4828. {
  4829. switch (opcode)
  4830. {
  4831. // Instructions that can cause src values to escape the local scope have already been excluded
  4832. case Js::OpCode::Not_A:
  4833. case Js::OpCode::And_A:
  4834. case Js::OpCode::Or_A:
  4835. case Js::OpCode::Xor_A:
  4836. case Js::OpCode::Shl_A:
  4837. case Js::OpCode::Shr_A:
  4838. case Js::OpCode::Not_I4:
  4839. case Js::OpCode::And_I4:
  4840. case Js::OpCode::Or_I4:
  4841. case Js::OpCode::Xor_I4:
  4842. case Js::OpCode::Shl_I4:
  4843. case Js::OpCode::Shr_I4:
  4844. // These instructions don't generate -0, and their behavior is the same for any src that is -0 or +0
  4845. SetSymIsUsedOnlyInBitOpsIfLastUse(instr->GetSrc1());
  4846. SetSymIsUsedOnlyInBitOpsIfLastUse(instr->GetSrc2());
  4847. break;
  4848. default:
  4849. SetSymIsNotUsedOnlyInBitOps(instr->GetSrc1());
  4850. SetSymIsNotUsedOnlyInBitOps(instr->GetSrc2());
  4851. break;
  4852. }
  4853. }
  4854. if (trackNumberop)
  4855. {
  4856. switch (opcode)
  4857. {
  4858. // Instructions that can cause src values to escape the local scope have already been excluded
  4859. case Js::OpCode::Conv_Num:
  4860. case Js::OpCode::Div_A:
  4861. case Js::OpCode::Mul_A:
  4862. case Js::OpCode::Sub_A:
  4863. case Js::OpCode::Rem_A:
  4864. case Js::OpCode::Incr_A:
  4865. case Js::OpCode::Decr_A:
  4866. case Js::OpCode::Neg_A:
  4867. case Js::OpCode::Not_A:
  4868. case Js::OpCode::ShrU_A:
  4869. case Js::OpCode::ShrU_I4:
  4870. case Js::OpCode::And_A:
  4871. case Js::OpCode::Or_A:
  4872. case Js::OpCode::Xor_A:
  4873. case Js::OpCode::Shl_A:
  4874. case Js::OpCode::Shr_A:
  4875. // These instructions don't generate -0, and their behavior is the same for any src that is -0 or +0
  4876. SetSymIsUsedOnlyInNumberIfLastUse(instr->GetSrc1());
  4877. SetSymIsUsedOnlyInNumberIfLastUse(instr->GetSrc2());
  4878. break;
  4879. default:
  4880. SetSymIsNotUsedOnlyInNumber(instr->GetSrc1());
  4881. SetSymIsNotUsedOnlyInNumber(instr->GetSrc2());
  4882. break;
  4883. }
  4884. }
  4885. }
  4886. void
  4887. BackwardPass::RemoveNegativeZeroBailout(IR::Instr* instr)
  4888. {
  4889. Assert(instr->HasBailOutInfo() && (instr->GetBailOutKind() & IR::BailOutOnNegativeZero));
  4890. IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  4891. bailOutKind = bailOutKind & ~IR::BailOutOnNegativeZero;
  4892. if (bailOutKind)
  4893. {
  4894. instr->SetBailOutKind(bailOutKind);
  4895. }
  4896. else
  4897. {
  4898. instr->ClearBailOutInfo();
  4899. if (preOpBailOutInstrToProcess == instr)
  4900. {
  4901. preOpBailOutInstrToProcess = nullptr;
  4902. }
  4903. }
  4904. }
  4905. void
  4906. BackwardPass::TrackIntUsage(IR::Instr *const instr)
  4907. {
  4908. Assert(instr);
  4909. const bool trackNegativeZero = DoTrackNegativeZero();
  4910. const bool trackIntOverflow = DoTrackIntOverflow();
  4911. const bool trackCompoundedIntOverflow = DoTrackCompoundedIntOverflow();
  4912. const bool trackNon32BitOverflow = DoTrackNon32BitOverflow();
  4913. if(!(trackNegativeZero || trackIntOverflow || trackCompoundedIntOverflow))
  4914. {
  4915. return;
  4916. }
  4917. const Js::OpCode opcode = instr->m_opcode;
  4918. if(trackCompoundedIntOverflow && opcode == Js::OpCode::StatementBoundary && instr->AsPragmaInstr()->m_statementIndex == 0)
  4919. {
  4920. // Cannot bail out before the first statement boundary, so the range cannot extend beyond this instruction
  4921. Assert(!instr->ignoreIntOverflowInRange);
  4922. EndIntOverflowDoesNotMatterRange();
  4923. return;
  4924. }
  4925. if(!instr->IsRealInstr())
  4926. {
  4927. return;
  4928. }
  4929. StackSym *const dstSym = IR::RegOpnd::TryGetStackSym(instr->GetDst());
  4930. bool ignoreIntOverflowCandidate = false;
  4931. if(dstSym)
  4932. {
  4933. // For a dst where the def is in this block, transfer the current info into the instruction
  4934. if(trackNegativeZero)
  4935. {
  4936. if (negativeZeroDoesNotMatterBySymId->Test(dstSym->m_id))
  4937. {
  4938. instr->ignoreNegativeZero = true;
  4939. }
  4940. if (tag == Js::DeadStorePhase)
  4941. {
  4942. if (negativeZeroDoesNotMatterBySymId->TestAndClear(dstSym->m_id))
  4943. {
  4944. if (instr->HasBailOutInfo())
  4945. {
  4946. IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  4947. if (bailOutKind & IR::BailOutOnNegativeZero)
  4948. {
  4949. RemoveNegativeZeroBailout(instr);
  4950. }
  4951. }
  4952. }
  4953. else
  4954. {
  4955. if (instr->HasBailOutInfo())
  4956. {
  4957. if (instr->GetBailOutKind() & IR::BailOutOnNegativeZero)
  4958. {
  4959. if (this->currentBlock->couldRemoveNegZeroBailoutForDef->TestAndClear(dstSym->m_id))
  4960. {
  4961. RemoveNegativeZeroBailout(instr);
  4962. }
  4963. }
  4964. // This instruction could potentially bail out. Hence, we cannot reliably remove negative zero
  4965. // bailouts upstream. If we did, and the operation actually produced a -0, and this instruction
  4966. // bailed out, we'd use +0 instead of -0 in the interpreter.
  4967. this->currentBlock->couldRemoveNegZeroBailoutForDef->ClearAll();
  4968. }
  4969. }
  4970. }
  4971. else
  4972. {
  4973. this->negativeZeroDoesNotMatterBySymId->Clear(dstSym->m_id);
  4974. }
  4975. }
  4976. if(trackIntOverflow)
  4977. {
  4978. ignoreIntOverflowCandidate = !!intOverflowDoesNotMatterBySymId->TestAndClear(dstSym->m_id);
  4979. if(trackCompoundedIntOverflow)
  4980. {
  4981. instr->ignoreIntOverflowInRange = !!intOverflowDoesNotMatterInRangeBySymId->TestAndClear(dstSym->m_id);
  4982. }
  4983. }
  4984. }
  4985. // If the instruction can cause src values to escape the local scope, the srcs can't be optimized
  4986. if(OpCodeAttr::NonTempNumberSources(opcode))
  4987. {
  4988. if(trackNegativeZero)
  4989. {
  4990. SetNegativeZeroMatters(instr->GetSrc1());
  4991. SetNegativeZeroMatters(instr->GetSrc2());
  4992. }
  4993. if(trackIntOverflow)
  4994. {
  4995. SetIntOverflowMatters(instr->GetSrc1());
  4996. SetIntOverflowMatters(instr->GetSrc2());
  4997. if(trackCompoundedIntOverflow)
  4998. {
  4999. instr->ignoreIntOverflowInRange = false;
  5000. SetIntOverflowMattersInRange(instr->GetSrc1());
  5001. SetIntOverflowMattersInRange(instr->GetSrc2());
  5002. EndIntOverflowDoesNotMatterRange();
  5003. }
  5004. }
  5005. return;
  5006. }
  5007. // -0 tracking
  5008. if(trackNegativeZero)
  5009. {
  5010. switch(opcode)
  5011. {
  5012. // Instructions that can cause src values to escape the local scope have already been excluded
  5013. case Js::OpCode::FromVar:
  5014. case Js::OpCode::Conv_Prim:
  5015. Assert(dstSym);
  5016. Assert(instr->GetSrc1());
  5017. Assert(!instr->GetSrc2());
  5018. if(instr->GetDst()->IsInt32())
  5019. {
  5020. // Conversion to int32 that is either explicit, or has a bailout check ensuring that it's an int value
  5021. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5022. break;
  5023. }
  5024. // fall-through
  5025. default:
  5026. if(dstSym && !instr->ignoreNegativeZero)
  5027. {
  5028. // -0 matters for dst, so -0 also matters for srcs
  5029. SetNegativeZeroMatters(instr->GetSrc1());
  5030. SetNegativeZeroMatters(instr->GetSrc2());
  5031. break;
  5032. }
  5033. if(opcode == Js::OpCode::Div_A || opcode == Js::OpCode::Div_I4)
  5034. {
  5035. // src1 is being divided by src2, so -0 matters for src2
  5036. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5037. SetNegativeZeroMatters(instr->GetSrc2());
  5038. break;
  5039. }
  5040. // fall-through
  5041. case Js::OpCode::Incr_A:
  5042. case Js::OpCode::Decr_A:
  5043. // Adding 1 to something or subtracting 1 from something does not generate -0
  5044. case Js::OpCode::Not_A:
  5045. case Js::OpCode::And_A:
  5046. case Js::OpCode::Or_A:
  5047. case Js::OpCode::Xor_A:
  5048. case Js::OpCode::Shl_A:
  5049. case Js::OpCode::Shr_A:
  5050. case Js::OpCode::ShrU_A:
  5051. case Js::OpCode::Not_I4:
  5052. case Js::OpCode::And_I4:
  5053. case Js::OpCode::Or_I4:
  5054. case Js::OpCode::Xor_I4:
  5055. case Js::OpCode::Shl_I4:
  5056. case Js::OpCode::Shr_I4:
  5057. case Js::OpCode::ShrU_I4:
  5058. case Js::OpCode::Conv_Str:
  5059. case Js::OpCode::Coerce_Str:
  5060. case Js::OpCode::Coerce_Regex:
  5061. case Js::OpCode::Coerce_StrOrRegex:
  5062. case Js::OpCode::Conv_PrimStr:
  5063. // These instructions don't generate -0, and their behavior is the same for any src that is -0 or +0
  5064. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5065. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc2());
  5066. break;
  5067. case Js::OpCode::Add_I4:
  5068. {
  5069. Assert(dstSym);
  5070. Assert(instr->GetSrc1());
  5071. Assert(instr->GetSrc1()->IsRegOpnd() || instr->GetSrc1()->IsImmediateOpnd());
  5072. Assert(instr->GetSrc2());
  5073. Assert(instr->GetSrc2()->IsRegOpnd() || instr->GetSrc2()->IsImmediateOpnd());
  5074. if (instr->ignoreNegativeZero ||
  5075. (instr->GetSrc1()->IsImmediateOpnd() && instr->GetSrc1()->GetImmediateValue(func) != 0) ||
  5076. (instr->GetSrc2()->IsImmediateOpnd() && instr->GetSrc2()->GetImmediateValue(func) != 0))
  5077. {
  5078. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5079. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc2());
  5080. break;
  5081. }
  5082. // -0 + -0 == -0. As long as one src is guaranteed to not be -0, -0 does not matter for the other src. Pick a
  5083. // src for which to ignore negative zero, based on which sym is last-use. If both syms are last-use, src2 is
  5084. // picked arbitrarily.
  5085. SetNegativeZeroMatters(instr->GetSrc1());
  5086. SetNegativeZeroMatters(instr->GetSrc2());
  5087. if (tag == Js::DeadStorePhase)
  5088. {
  5089. if (instr->GetSrc2()->IsRegOpnd() &&
  5090. !currentBlock->upwardExposedUses->Test(instr->GetSrc2()->AsRegOpnd()->m_sym->m_id))
  5091. {
  5092. SetCouldRemoveNegZeroBailoutForDefIfLastUse(instr->GetSrc2());
  5093. }
  5094. else
  5095. {
  5096. SetCouldRemoveNegZeroBailoutForDefIfLastUse(instr->GetSrc1());
  5097. }
  5098. }
  5099. break;
  5100. }
  5101. case Js::OpCode::Add_A:
  5102. Assert(dstSym);
  5103. Assert(instr->GetSrc1());
  5104. Assert(instr->GetSrc1()->IsRegOpnd() || instr->GetSrc1()->IsAddrOpnd());
  5105. Assert(instr->GetSrc2());
  5106. Assert(instr->GetSrc2()->IsRegOpnd() || instr->GetSrc2()->IsAddrOpnd());
  5107. if(instr->ignoreNegativeZero || instr->GetSrc1()->IsAddrOpnd() || instr->GetSrc2()->IsAddrOpnd())
  5108. {
  5109. // -0 does not matter for dst, or this instruction does not generate -0 since one of the srcs is not -0
  5110. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5111. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc2());
  5112. break;
  5113. }
  5114. SetNegativeZeroMatters(instr->GetSrc1());
  5115. SetNegativeZeroMatters(instr->GetSrc2());
  5116. break;
  5117. case Js::OpCode::Sub_I4:
  5118. {
  5119. Assert(dstSym);
  5120. Assert(instr->GetSrc1());
  5121. Assert(instr->GetSrc1()->IsRegOpnd() || instr->GetSrc1()->IsImmediateOpnd());
  5122. Assert(instr->GetSrc2());
  5123. Assert(instr->GetSrc2()->IsRegOpnd() || instr->GetSrc2()->IsImmediateOpnd());
  5124. if (instr->ignoreNegativeZero ||
  5125. (instr->GetSrc1()->IsImmediateOpnd() && instr->GetSrc1()->GetImmediateValue(func) != 0) ||
  5126. (instr->GetSrc2()->IsImmediateOpnd() && instr->GetSrc2()->GetImmediateValue(func) != 0))
  5127. {
  5128. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5129. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc2());
  5130. }
  5131. else
  5132. {
  5133. goto NegativeZero_Sub_Default;
  5134. }
  5135. break;
  5136. }
  5137. case Js::OpCode::Sub_A:
  5138. Assert(dstSym);
  5139. Assert(instr->GetSrc1());
  5140. Assert(instr->GetSrc1()->IsRegOpnd() || instr->GetSrc1()->IsAddrOpnd());
  5141. Assert(instr->GetSrc2());
  5142. Assert(instr->GetSrc2()->IsRegOpnd() || instr->GetSrc2()->IsAddrOpnd() || instr->GetSrc2()->IsIntConstOpnd());
  5143. if(instr->ignoreNegativeZero ||
  5144. instr->GetSrc1()->IsAddrOpnd() ||
  5145. (
  5146. instr->GetSrc2()->IsAddrOpnd() &&
  5147. instr->GetSrc2()->AsAddrOpnd()->IsVar() &&
  5148. Js::TaggedInt::ToInt32(instr->GetSrc2()->AsAddrOpnd()->m_address) != 0
  5149. ))
  5150. {
  5151. // At least one of the following is true:
  5152. // - -0 does not matter for dst
  5153. // - Src1 is not -0, and so this instruction cannot generate -0
  5154. // - Src2 is a nonzero tagged int constant, and so this instruction cannot generate -0
  5155. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5156. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc2());
  5157. break;
  5158. }
  5159. // fall-through
  5160. NegativeZero_Sub_Default:
  5161. // -0 - 0 == -0. As long as src1 is guaranteed to not be -0, -0 does not matter for src2.
  5162. SetNegativeZeroMatters(instr->GetSrc1());
  5163. SetNegativeZeroMatters(instr->GetSrc2());
  5164. if (this->tag == Js::DeadStorePhase)
  5165. {
  5166. SetCouldRemoveNegZeroBailoutForDefIfLastUse(instr->GetSrc2());
  5167. }
  5168. break;
  5169. case Js::OpCode::BrEq_I4:
  5170. case Js::OpCode::BrTrue_I4:
  5171. case Js::OpCode::BrFalse_I4:
  5172. case Js::OpCode::BrGe_I4:
  5173. case Js::OpCode::BrUnGe_I4:
  5174. case Js::OpCode::BrGt_I4:
  5175. case Js::OpCode::BrUnGt_I4:
  5176. case Js::OpCode::BrLt_I4:
  5177. case Js::OpCode::BrUnLt_I4:
  5178. case Js::OpCode::BrLe_I4:
  5179. case Js::OpCode::BrUnLe_I4:
  5180. case Js::OpCode::BrNeq_I4:
  5181. // Int-specialized branches may prove that one of the src must be zero purely based on the int range, in which
  5182. // case they rely on prior -0 bailouts to guarantee that the src cannot be -0. So, consider that -0 matters for
  5183. // the srcs.
  5184. // fall-through
  5185. case Js::OpCode::InlineMathAtan2:
  5186. // Atan(y,x) - signs of y, x is used to determine the quadrant of the result
  5187. SetNegativeZeroMatters(instr->GetSrc1());
  5188. SetNegativeZeroMatters(instr->GetSrc2());
  5189. break;
  5190. case Js::OpCode::Expo_A:
  5191. case Js::OpCode::InlineMathPow:
  5192. // Negative zero matters for src1
  5193. // Pow( 0, <neg>) is Infinity
  5194. // Pow(-0, <neg>) is -Infinity
  5195. SetNegativeZeroMatters(instr->GetSrc1());
  5196. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc2());
  5197. break;
  5198. case Js::OpCode::LdElemI_A:
  5199. // There is an implicit ToString on the index operand, which doesn't differentiate -0 from +0
  5200. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1()->AsIndirOpnd()->GetIndexOpnd());
  5201. break;
  5202. case Js::OpCode::StElemI_A:
  5203. case Js::OpCode::StElemI_A_Strict:
  5204. // There is an implicit ToString on the index operand, which doesn't differentiate -0 from +0
  5205. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetDst()->AsIndirOpnd()->GetIndexOpnd());
  5206. break;
  5207. }
  5208. }
  5209. // Int overflow tracking
  5210. if(!trackIntOverflow)
  5211. {
  5212. return;
  5213. }
  5214. switch(opcode)
  5215. {
  5216. // Instructions that can cause src values to escape the local scope have already been excluded
  5217. default:
  5218. // Unlike the -0 tracking, we use an inclusion list of op-codes for overflow tracking rather than an exclusion list.
  5219. // Assume for any instructions other than those listed above, that int-overflowed values in the srcs are
  5220. // insufficient.
  5221. ignoreIntOverflowCandidate = false;
  5222. // fall-through
  5223. case Js::OpCode::Incr_A:
  5224. case Js::OpCode::Decr_A:
  5225. case Js::OpCode::Add_A:
  5226. case Js::OpCode::Sub_A:
  5227. // The sources are not guaranteed to be converted to int32. Let the compounded int overflow tracking handle this.
  5228. SetIntOverflowMatters(instr->GetSrc1());
  5229. SetIntOverflowMatters(instr->GetSrc2());
  5230. break;
  5231. case Js::OpCode::Mul_A:
  5232. if (trackNon32BitOverflow)
  5233. {
  5234. if (ignoreIntOverflowCandidate)
  5235. instr->ignoreOverflowBitCount = 53;
  5236. }
  5237. else
  5238. {
  5239. ignoreIntOverflowCandidate = false;
  5240. }
  5241. SetIntOverflowMatters(instr->GetSrc1());
  5242. SetIntOverflowMatters(instr->GetSrc2());
  5243. break;
  5244. case Js::OpCode::Neg_A:
  5245. case Js::OpCode::Ld_A:
  5246. case Js::OpCode::Conv_Num:
  5247. case Js::OpCode::ShrU_A:
  5248. if(!ignoreIntOverflowCandidate)
  5249. {
  5250. // Int overflow matters for dst, so int overflow also matters for srcs
  5251. SetIntOverflowMatters(instr->GetSrc1());
  5252. SetIntOverflowMatters(instr->GetSrc2());
  5253. break;
  5254. }
  5255. // fall-through
  5256. case Js::OpCode::Not_A:
  5257. case Js::OpCode::And_A:
  5258. case Js::OpCode::Or_A:
  5259. case Js::OpCode::Xor_A:
  5260. case Js::OpCode::Shl_A:
  5261. case Js::OpCode::Shr_A:
  5262. // These instructions convert their srcs to int32s, and hence don't care about int-overflowed values in the srcs (as
  5263. // long as the overflowed values did not overflow the 53 bits that 'double' values have to precisely represent
  5264. // ints). ShrU_A is not included here because it converts its srcs to uint32 rather than int32, so it would make a
  5265. // difference if the srcs have int32-overflowed values.
  5266. SetIntOverflowDoesNotMatterIfLastUse(instr->GetSrc1());
  5267. SetIntOverflowDoesNotMatterIfLastUse(instr->GetSrc2());
  5268. break;
  5269. }
  5270. if(ignoreIntOverflowCandidate)
  5271. {
  5272. instr->ignoreIntOverflow = true;
  5273. }
  5274. // Compounded int overflow tracking
  5275. if(!trackCompoundedIntOverflow)
  5276. {
  5277. return;
  5278. }
  5279. if(instr->GetByteCodeOffset() == Js::Constants::NoByteCodeOffset)
  5280. {
  5281. // The forward pass may need to insert conversions with bailouts before the first instruction in the range. Since this
  5282. // instruction does not have a valid byte code offset for bailout purposes, end the current range now.
  5283. instr->ignoreIntOverflowInRange = false;
  5284. SetIntOverflowMattersInRange(instr->GetSrc1());
  5285. SetIntOverflowMattersInRange(instr->GetSrc2());
  5286. EndIntOverflowDoesNotMatterRange();
  5287. return;
  5288. }
  5289. if(ignoreIntOverflowCandidate)
  5290. {
  5291. instr->ignoreIntOverflowInRange = true;
  5292. if(dstSym)
  5293. {
  5294. dstSym->scratch.globOpt.numCompoundedAddSubUses = 0;
  5295. }
  5296. }
  5297. bool lossy = false;
  5298. switch(opcode)
  5299. {
  5300. // Instructions that can cause src values to escape the local scope have already been excluded
  5301. case Js::OpCode::Incr_A:
  5302. case Js::OpCode::Decr_A:
  5303. case Js::OpCode::Add_A:
  5304. case Js::OpCode::Sub_A:
  5305. {
  5306. if(!instr->ignoreIntOverflowInRange)
  5307. {
  5308. // Int overflow matters for dst, so int overflow also matters for srcs
  5309. SetIntOverflowMattersInRange(instr->GetSrc1());
  5310. SetIntOverflowMattersInRange(instr->GetSrc2());
  5311. break;
  5312. }
  5313. AnalysisAssert(dstSym);
  5314. // The number of compounded add/sub uses of each src is at least the number of compounded add/sub uses of the dst,
  5315. // + 1 for the current instruction
  5316. Assert(dstSym->scratch.globOpt.numCompoundedAddSubUses >= 0);
  5317. Assert(dstSym->scratch.globOpt.numCompoundedAddSubUses <= MaxCompoundedUsesInAddSubForIgnoringIntOverflow);
  5318. const int addSubUses = dstSym->scratch.globOpt.numCompoundedAddSubUses + 1;
  5319. if(addSubUses > MaxCompoundedUsesInAddSubForIgnoringIntOverflow)
  5320. {
  5321. // There are too many compounded add/sub uses of the srcs. There is a possibility that combined, the number
  5322. // eventually overflows the 53 bits that 'double' values have to precisely represent ints
  5323. instr->ignoreIntOverflowInRange = false;
  5324. SetIntOverflowMattersInRange(instr->GetSrc1());
  5325. SetIntOverflowMattersInRange(instr->GetSrc2());
  5326. break;
  5327. }
  5328. TransferCompoundedAddSubUsesToSrcs(instr, addSubUses);
  5329. break;
  5330. }
  5331. case Js::OpCode::Neg_A:
  5332. case Js::OpCode::Ld_A:
  5333. case Js::OpCode::Conv_Num:
  5334. case Js::OpCode::ShrU_A:
  5335. {
  5336. if(!instr->ignoreIntOverflowInRange)
  5337. {
  5338. // Int overflow matters for dst, so int overflow also matters for srcs
  5339. SetIntOverflowMattersInRange(instr->GetSrc1());
  5340. SetIntOverflowMattersInRange(instr->GetSrc2());
  5341. break;
  5342. }
  5343. AnalysisAssert(dstSym);
  5344. TransferCompoundedAddSubUsesToSrcs(instr, dstSym->scratch.globOpt.numCompoundedAddSubUses);
  5345. lossy = opcode == Js::OpCode::ShrU_A;
  5346. break;
  5347. }
  5348. case Js::OpCode::Not_A:
  5349. case Js::OpCode::And_A:
  5350. case Js::OpCode::Or_A:
  5351. case Js::OpCode::Xor_A:
  5352. case Js::OpCode::Shl_A:
  5353. case Js::OpCode::Shr_A:
  5354. // These instructions convert their srcs to int32s, and hence don't care about int-overflowed values in the srcs (as
  5355. // long as the overflowed values did not overflow the 53 bits that 'double' values have to precisely represent
  5356. // ints). ShrU_A is not included here because it converts its srcs to uint32 rather than int32, so it would make a
  5357. // difference if the srcs have int32-overflowed values.
  5358. instr->ignoreIntOverflowInRange = true;
  5359. lossy = true;
  5360. SetIntOverflowDoesNotMatterInRangeIfLastUse(instr->GetSrc1(), 0);
  5361. SetIntOverflowDoesNotMatterInRangeIfLastUse(instr->GetSrc2(), 0);
  5362. break;
  5363. case Js::OpCode::LdSlotArr:
  5364. case Js::OpCode::LdSlot:
  5365. {
  5366. Assert(dstSym);
  5367. Assert(!instr->GetSrc2()); // at the moment, this list contains only unary operations
  5368. if(intOverflowCurrentlyMattersInRange)
  5369. {
  5370. // These instructions will not begin a range, so just return. They don't begin a range because their initial
  5371. // value may not be available until after the instruction is processed in the forward pass.
  5372. Assert(!instr->ignoreIntOverflowInRange);
  5373. return;
  5374. }
  5375. Assert(currentBlock->intOverflowDoesNotMatterRange);
  5376. // Int overflow does not matter for dst, so the srcs need to be tracked as inputs into the region of
  5377. // instructions where int overflow does not matter. Since these instructions will not begin or end a range, they
  5378. // are tracked in separate candidates bit-vectors and once we have confirmed that they don't begin the range,
  5379. // they will be transferred to 'SymsRequiredToBe[Lossy]Int'. Furthermore, once this instruction is included in
  5380. // the range, its dst sym has to be removed. Since this instructions may not be included in the range, add the
  5381. // dst sym to the candidates bit-vectors. If they are included, the process of transferring will remove the dst
  5382. // syms and add the src syms.
  5383. // Remove the dst using the candidate bit-vectors
  5384. Assert(
  5385. !instr->ignoreIntOverflowInRange ||
  5386. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Test(dstSym->m_id));
  5387. if(instr->ignoreIntOverflowInRange ||
  5388. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Test(dstSym->m_id))
  5389. {
  5390. candidateSymsRequiredToBeInt->Set(dstSym->m_id);
  5391. if(currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Test(dstSym->m_id))
  5392. {
  5393. candidateSymsRequiredToBeLossyInt->Set(dstSym->m_id);
  5394. }
  5395. }
  5396. if(!instr->ignoreIntOverflowInRange)
  5397. {
  5398. // These instructions will not end a range, so just return. They may be included in the middle of a range, but
  5399. // since int overflow matters for the dst, the src does not need to be counted as an input into the range.
  5400. return;
  5401. }
  5402. instr->ignoreIntOverflowInRange = false;
  5403. // Add the src using the candidate bit-vectors. The src property sym may already be included in the range or as
  5404. // a candidate. The xor of the final bit-vector with the candidate is the set of syms required to be int,
  5405. // assuming all instructions up to and not including this one are included in the range.
  5406. const SymID srcSymId = instr->GetSrc1()->AsSymOpnd()->m_sym->m_id;
  5407. const bool srcIncluded =
  5408. !!currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Test(srcSymId) ^
  5409. !!candidateSymsRequiredToBeInt->Test(srcSymId);
  5410. const bool srcIncludedAsLossy =
  5411. srcIncluded &&
  5412. !!currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Test(srcSymId) ^
  5413. !!candidateSymsRequiredToBeLossyInt->Test(srcSymId);
  5414. const bool srcNeedsToBeLossless =
  5415. !currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Test(dstSym->m_id) ||
  5416. (srcIncluded && !srcIncludedAsLossy);
  5417. if(srcIncluded)
  5418. {
  5419. if(srcIncludedAsLossy && srcNeedsToBeLossless)
  5420. {
  5421. candidateSymsRequiredToBeLossyInt->Compliment(srcSymId);
  5422. }
  5423. }
  5424. else
  5425. {
  5426. candidateSymsRequiredToBeInt->Compliment(srcSymId);
  5427. if(!srcNeedsToBeLossless)
  5428. {
  5429. candidateSymsRequiredToBeLossyInt->Compliment(srcSymId);
  5430. }
  5431. }
  5432. // These instructions will not end a range, so just return. They may be included in the middle of a range, and the
  5433. // src has been included as a candidate input into the range.
  5434. return;
  5435. }
  5436. case Js::OpCode::Mul_A:
  5437. if (trackNon32BitOverflow)
  5438. {
  5439. // MULs will always be at the start of a range. Either included in the range if int32 overflow is ignored, or excluded if int32 overflow matters. Even if int32 can be ignored, MULs can still bailout on 53-bit.
  5440. // That's why it cannot be in the middle of a range.
  5441. if (instr->ignoreIntOverflowInRange)
  5442. {
  5443. AnalysisAssert(dstSym);
  5444. Assert(dstSym->scratch.globOpt.numCompoundedAddSubUses >= 0);
  5445. Assert(dstSym->scratch.globOpt.numCompoundedAddSubUses <= MaxCompoundedUsesInAddSubForIgnoringIntOverflow);
  5446. instr->ignoreOverflowBitCount = (uint8) (53 - dstSym->scratch.globOpt.numCompoundedAddSubUses);
  5447. // We have the max number of compounded adds/subs. 32-bit overflow cannot be ignored.
  5448. if (instr->ignoreOverflowBitCount == 32)
  5449. {
  5450. instr->ignoreIntOverflowInRange = false;
  5451. }
  5452. }
  5453. SetIntOverflowMattersInRange(instr->GetSrc1());
  5454. SetIntOverflowMattersInRange(instr->GetSrc2());
  5455. break;
  5456. }
  5457. // fall-through
  5458. default:
  5459. // Unlike the -0 tracking, we use an inclusion list of op-codes for overflow tracking rather than an exclusion list.
  5460. // Assume for any instructions other than those listed above, that int-overflowed values in the srcs are
  5461. // insufficient.
  5462. instr->ignoreIntOverflowInRange = false;
  5463. SetIntOverflowMattersInRange(instr->GetSrc1());
  5464. SetIntOverflowMattersInRange(instr->GetSrc2());
  5465. break;
  5466. }
  5467. if(!instr->ignoreIntOverflowInRange)
  5468. {
  5469. EndIntOverflowDoesNotMatterRange();
  5470. return;
  5471. }
  5472. if(intOverflowCurrentlyMattersInRange)
  5473. {
  5474. // This is the last instruction in a new range of instructions where int overflow does not matter
  5475. intOverflowCurrentlyMattersInRange = false;
  5476. IR::Instr *const boundaryInstr = IR::PragmaInstr::New(Js::OpCode::NoIntOverflowBoundary, 0, instr->m_func);
  5477. boundaryInstr->SetByteCodeOffset(instr);
  5478. currentBlock->InsertInstrAfter(boundaryInstr, instr);
  5479. currentBlock->intOverflowDoesNotMatterRange =
  5480. IntOverflowDoesNotMatterRange::New(
  5481. globOpt->alloc,
  5482. instr,
  5483. boundaryInstr,
  5484. currentBlock->intOverflowDoesNotMatterRange);
  5485. }
  5486. else
  5487. {
  5488. Assert(currentBlock->intOverflowDoesNotMatterRange);
  5489. // Extend the current range of instructions where int overflow does not matter, to include this instruction. We also need to
  5490. // include the tracked syms for instructions that have not yet been included in the range, which are tracked in the range's
  5491. // bit-vector. 'SymsRequiredToBeInt' will contain both the dst and src syms of instructions not yet included in the range;
  5492. // the xor will remove the dst syms and add the src syms.
  5493. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Xor(candidateSymsRequiredToBeInt);
  5494. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Xor(candidateSymsRequiredToBeLossyInt);
  5495. candidateSymsRequiredToBeInt->ClearAll();
  5496. candidateSymsRequiredToBeLossyInt->ClearAll();
  5497. currentBlock->intOverflowDoesNotMatterRange->SetFirstInstr(instr);
  5498. }
  5499. // Track syms that are inputs into the range based on the current instruction, which was just added to the range. The dst
  5500. // sym is obtaining a new value so it isn't required to be an int at the start of the range, but the srcs are.
  5501. if(dstSym)
  5502. {
  5503. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Clear(dstSym->m_id);
  5504. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Clear(dstSym->m_id);
  5505. }
  5506. IR::Opnd *const srcs[] = { instr->GetSrc1(), instr->GetSrc2() };
  5507. for(int i = 0; i < sizeof(srcs) / sizeof(srcs[0]) && srcs[i]; ++i)
  5508. {
  5509. StackSym *srcSym = IR::RegOpnd::TryGetStackSym(srcs[i]);
  5510. if(!srcSym)
  5511. {
  5512. continue;
  5513. }
  5514. if(currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->TestAndSet(srcSym->m_id))
  5515. {
  5516. if(!lossy)
  5517. {
  5518. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Clear(srcSym->m_id);
  5519. }
  5520. }
  5521. else if(lossy)
  5522. {
  5523. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Set(srcSym->m_id);
  5524. }
  5525. }
  5526. // If the last instruction included in the range is a MUL, we have to end the range.
  5527. // MULs with ignoreIntOverflow can still bailout on 53-bit overflow, so they cannot be in the middle of a range
  5528. if (trackNon32BitOverflow && instr->m_opcode == Js::OpCode::Mul_A)
  5529. {
  5530. // range would have ended already if int32 overflow matters
  5531. Assert(instr->ignoreIntOverflowInRange && instr->ignoreOverflowBitCount != 32);
  5532. EndIntOverflowDoesNotMatterRange();
  5533. }
  5534. }
  5535. void
  5536. BackwardPass::SetNegativeZeroDoesNotMatterIfLastUse(IR::Opnd *const opnd)
  5537. {
  5538. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5539. if(stackSym && !currentBlock->upwardExposedUses->Test(stackSym->m_id))
  5540. {
  5541. negativeZeroDoesNotMatterBySymId->Set(stackSym->m_id);
  5542. }
  5543. }
  5544. void
  5545. BackwardPass::SetNegativeZeroMatters(IR::Opnd *const opnd)
  5546. {
  5547. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5548. if(stackSym)
  5549. {
  5550. negativeZeroDoesNotMatterBySymId->Clear(stackSym->m_id);
  5551. }
  5552. }
  5553. void
  5554. BackwardPass::SetCouldRemoveNegZeroBailoutForDefIfLastUse(IR::Opnd *const opnd)
  5555. {
  5556. StackSym * stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5557. if (stackSym && !this->currentBlock->upwardExposedUses->Test(stackSym->m_id))
  5558. {
  5559. this->currentBlock->couldRemoveNegZeroBailoutForDef->Set(stackSym->m_id);
  5560. }
  5561. }
  5562. void
  5563. BackwardPass::SetIntOverflowDoesNotMatterIfLastUse(IR::Opnd *const opnd)
  5564. {
  5565. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5566. if(stackSym && !currentBlock->upwardExposedUses->Test(stackSym->m_id))
  5567. {
  5568. intOverflowDoesNotMatterBySymId->Set(stackSym->m_id);
  5569. }
  5570. }
  5571. void
  5572. BackwardPass::SetIntOverflowMatters(IR::Opnd *const opnd)
  5573. {
  5574. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5575. if(stackSym)
  5576. {
  5577. intOverflowDoesNotMatterBySymId->Clear(stackSym->m_id);
  5578. }
  5579. }
  5580. bool
  5581. BackwardPass::SetIntOverflowDoesNotMatterInRangeIfLastUse(IR::Opnd *const opnd, const int addSubUses)
  5582. {
  5583. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5584. return stackSym && SetIntOverflowDoesNotMatterInRangeIfLastUse(stackSym, addSubUses);
  5585. }
  5586. bool
  5587. BackwardPass::SetIntOverflowDoesNotMatterInRangeIfLastUse(StackSym *const stackSym, const int addSubUses)
  5588. {
  5589. Assert(stackSym);
  5590. Assert(addSubUses >= 0);
  5591. Assert(addSubUses <= MaxCompoundedUsesInAddSubForIgnoringIntOverflow);
  5592. if(currentBlock->upwardExposedUses->Test(stackSym->m_id))
  5593. {
  5594. return false;
  5595. }
  5596. intOverflowDoesNotMatterInRangeBySymId->Set(stackSym->m_id);
  5597. stackSym->scratch.globOpt.numCompoundedAddSubUses = addSubUses;
  5598. return true;
  5599. }
  5600. void
  5601. BackwardPass::SetIntOverflowMattersInRange(IR::Opnd *const opnd)
  5602. {
  5603. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5604. if(stackSym)
  5605. {
  5606. intOverflowDoesNotMatterInRangeBySymId->Clear(stackSym->m_id);
  5607. }
  5608. }
  5609. void
  5610. BackwardPass::TransferCompoundedAddSubUsesToSrcs(IR::Instr *const instr, const int addSubUses)
  5611. {
  5612. Assert(instr);
  5613. Assert(addSubUses >= 0);
  5614. Assert(addSubUses <= MaxCompoundedUsesInAddSubForIgnoringIntOverflow);
  5615. IR::Opnd *const srcs[] = { instr->GetSrc1(), instr->GetSrc2() };
  5616. for(int i = 0; i < _countof(srcs) && srcs[i]; ++i)
  5617. {
  5618. StackSym *const srcSym = IR::RegOpnd::TryGetStackSym(srcs[i]);
  5619. if(!srcSym)
  5620. {
  5621. // Int overflow tracking is only done for StackSyms in RegOpnds. Int overflow matters for the src, so it is
  5622. // guaranteed to be in the int range at this point if the instruction is int-specialized.
  5623. continue;
  5624. }
  5625. Assert(srcSym->scratch.globOpt.numCompoundedAddSubUses >= 0);
  5626. Assert(srcSym->scratch.globOpt.numCompoundedAddSubUses <= MaxCompoundedUsesInAddSubForIgnoringIntOverflow);
  5627. if(SetIntOverflowDoesNotMatterInRangeIfLastUse(srcSym, addSubUses))
  5628. {
  5629. // This is the last use of the src
  5630. continue;
  5631. }
  5632. if(intOverflowDoesNotMatterInRangeBySymId->Test(srcSym->m_id))
  5633. {
  5634. // Since a src may be compounded through different chains of add/sub instructions, the greater number must be
  5635. // preserved
  5636. srcSym->scratch.globOpt.numCompoundedAddSubUses =
  5637. max(srcSym->scratch.globOpt.numCompoundedAddSubUses, addSubUses);
  5638. }
  5639. else
  5640. {
  5641. // Int overflow matters for the src, so it is guaranteed to be in the int range at this point if the instruction is
  5642. // int-specialized
  5643. }
  5644. }
  5645. }
  5646. void
  5647. BackwardPass::EndIntOverflowDoesNotMatterRange()
  5648. {
  5649. if(intOverflowCurrentlyMattersInRange)
  5650. {
  5651. return;
  5652. }
  5653. intOverflowCurrentlyMattersInRange = true;
  5654. if(currentBlock->intOverflowDoesNotMatterRange->FirstInstr()->m_next ==
  5655. currentBlock->intOverflowDoesNotMatterRange->LastInstr())
  5656. {
  5657. // Don't need a range for a single-instruction range
  5658. IntOverflowDoesNotMatterRange *const rangeToDelete = currentBlock->intOverflowDoesNotMatterRange;
  5659. currentBlock->intOverflowDoesNotMatterRange = currentBlock->intOverflowDoesNotMatterRange->Next();
  5660. currentBlock->RemoveInstr(rangeToDelete->LastInstr());
  5661. rangeToDelete->Delete(globOpt->alloc);
  5662. }
  5663. else
  5664. {
  5665. // End the current range of instructions where int overflow does not matter
  5666. IR::Instr *const boundaryInstr =
  5667. IR::PragmaInstr::New(
  5668. Js::OpCode::NoIntOverflowBoundary,
  5669. 0,
  5670. currentBlock->intOverflowDoesNotMatterRange->FirstInstr()->m_func);
  5671. boundaryInstr->SetByteCodeOffset(currentBlock->intOverflowDoesNotMatterRange->FirstInstr());
  5672. currentBlock->InsertInstrBefore(boundaryInstr, currentBlock->intOverflowDoesNotMatterRange->FirstInstr());
  5673. currentBlock->intOverflowDoesNotMatterRange->SetFirstInstr(boundaryInstr);
  5674. #if DBG_DUMP
  5675. if(PHASE_TRACE(Js::TrackCompoundedIntOverflowPhase, func))
  5676. {
  5677. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5678. Output::Print(
  5679. _u("TrackCompoundedIntOverflow - Top function: %s (%s), Phase: %s, Block: %u\n"),
  5680. func->GetJITFunctionBody()->GetDisplayName(),
  5681. func->GetDebugNumberSet(debugStringBuffer),
  5682. Js::PhaseNames[Js::BackwardPhase],
  5683. currentBlock->GetBlockNum());
  5684. Output::Print(_u(" Input syms to be int-specialized (lossless): "));
  5685. candidateSymsRequiredToBeInt->Minus(
  5686. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt(),
  5687. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()); // candidate bit-vectors are cleared below anyway
  5688. candidateSymsRequiredToBeInt->Dump();
  5689. Output::Print(_u(" Input syms to be converted to int (lossy): "));
  5690. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Dump();
  5691. Output::Print(_u(" First instr: "));
  5692. currentBlock->intOverflowDoesNotMatterRange->FirstInstr()->m_next->Dump();
  5693. Output::Flush();
  5694. }
  5695. #endif
  5696. }
  5697. // Reset candidates for the next range
  5698. candidateSymsRequiredToBeInt->ClearAll();
  5699. candidateSymsRequiredToBeLossyInt->ClearAll();
  5700. // Syms are not tracked across different ranges of instructions where int overflow does not matter, since instructions
  5701. // between the ranges may bail out. The value of the dst of an int operation where overflow is ignored is incorrect until
  5702. // the last use of that sym is converted to int. If the int operation and the last use of the sym are in different ranges
  5703. // and an instruction between the ranges bails out, other inputs into the second range are no longer guaranteed to be ints,
  5704. // so the incorrect value of the sym may be used in non-int operations.
  5705. intOverflowDoesNotMatterInRangeBySymId->ClearAll();
  5706. }
  5707. void
  5708. BackwardPass::TrackFloatSymEquivalence(IR::Instr *const instr)
  5709. {
  5710. /*
  5711. This function determines sets of float-specialized syms where any two syms in a set may have the same value number at some
  5712. point in the function. Conversely, if two float-specialized syms are not in the same set, it guarantees that those two syms
  5713. will never have the same value number. These sets are referred to as equivalence classes here.
  5714. The equivalence class for a sym is used to determine whether a bailout FromVar generating a float value for the sym needs to
  5715. bail out on any non-number value. For instance, for syms s1 and s5 in an equivalence class (say we have s5 = s1 at some
  5716. point), if there's a FromVar that generates a float value for s1 but only bails out on strings or non-primitives, and s5 is
  5717. returned from the function, it has to be ensured that s5 is not converted to Var. If the source of the FromVar was null, the
  5718. FromVar would not have bailed out, and s1 and s5 would have the value +0. When s5 is returned, we need to return null and
  5719. not +0, so the equivalence class is used to determine that since s5 requires a bailout on any non-number value, so does s1.
  5720. The tracking is very conservative because the bit that says "I require bailout on any non-number value" is on the sym itself
  5721. (referred to as non-number bailout bit below).
  5722. Data:
  5723. - BackwardPass::floatSymEquivalenceMap
  5724. - hash table mapping a float sym ID to its equivalence class
  5725. - FloatSymEquivalenceClass
  5726. - bit vector of float sym IDs that are in the equivalence class
  5727. - one non-number bailout bit for all syms in the equivalence class
  5728. Algorithm:
  5729. - In a loop prepass or when not in loop:
  5730. - For a float sym transfer (s0.f = s1.f), add both syms to an equivalence class (set the syms in a bit vector)
  5731. - If either sym requires bailout on any non-number value, set the equivalence class' non-number bailout bit
  5732. - If one of the syms is already in an equivalence class, merge the two equivalence classes by OR'ing the two bit vectors
  5733. and the non-number bailout bit.
  5734. - Note that for functions with a loop, dependency tracking is done using equivalence classes and that information is not
  5735. transferred back into each sym's non-number bailout bit
  5736. - In a loop non-prepass or when not in loop, for a FromVar instruction that requires bailout only on strings and
  5737. non-primitives:
  5738. - If the destination float sym's non-number bailout bit is set, or the sym is in an equivalence class whose non-number
  5739. bailout bit is set, change the bailout to bail out on any non-number value
  5740. The result is that if a float-specialized sym's value is used in a way in which it would be invalid to use the float value
  5741. through any other float-specialized sym that acquires the value, the FromVar generating the float value will be modified to
  5742. bail out on any non-number value.
  5743. */
  5744. Assert(instr);
  5745. if(tag != Js::DeadStorePhase || instr->GetSrc2() || !instr->m_func->hasBailout)
  5746. {
  5747. return;
  5748. }
  5749. if(!instr->GetDst() || !instr->GetDst()->IsRegOpnd())
  5750. {
  5751. return;
  5752. }
  5753. const auto dst = instr->GetDst()->AsRegOpnd()->m_sym;
  5754. if(!dst->IsFloat64())
  5755. {
  5756. return;
  5757. }
  5758. if(!instr->GetSrc1() || !instr->GetSrc1()->IsRegOpnd())
  5759. {
  5760. return;
  5761. }
  5762. const auto src = instr->GetSrc1()->AsRegOpnd()->m_sym;
  5763. if(OpCodeAttr::NonIntTransfer(instr->m_opcode) && (!currentBlock->loop || IsPrePass()))
  5764. {
  5765. Assert(src->IsFloat64()); // dst is specialized, and since this is a float transfer, src must be specialized too
  5766. if(dst == src)
  5767. {
  5768. return;
  5769. }
  5770. if(!func->m_fg->hasLoop)
  5771. {
  5772. // Special case for functions with no loops, since there can only be in-order dependencies. Just merge the two
  5773. // non-number bailout bits and put the result in the source.
  5774. if(dst->m_requiresBailOnNotNumber)
  5775. {
  5776. src->m_requiresBailOnNotNumber = true;
  5777. }
  5778. return;
  5779. }
  5780. FloatSymEquivalenceClass *dstEquivalenceClass = nullptr, *srcEquivalenceClass = nullptr;
  5781. const bool dstHasEquivalenceClass = floatSymEquivalenceMap->TryGetValue(dst->m_id, &dstEquivalenceClass);
  5782. const bool srcHasEquivalenceClass = floatSymEquivalenceMap->TryGetValue(src->m_id, &srcEquivalenceClass);
  5783. if(!dstHasEquivalenceClass)
  5784. {
  5785. if(srcHasEquivalenceClass)
  5786. {
  5787. // Just add the destination into the source's equivalence class
  5788. srcEquivalenceClass->Set(dst);
  5789. floatSymEquivalenceMap->Add(dst->m_id, srcEquivalenceClass);
  5790. return;
  5791. }
  5792. dstEquivalenceClass = JitAnew(tempAlloc, FloatSymEquivalenceClass, tempAlloc);
  5793. dstEquivalenceClass->Set(dst);
  5794. floatSymEquivalenceMap->Add(dst->m_id, dstEquivalenceClass);
  5795. }
  5796. if(!srcHasEquivalenceClass)
  5797. {
  5798. // Just add the source into the destination's equivalence class
  5799. dstEquivalenceClass->Set(src);
  5800. floatSymEquivalenceMap->Add(src->m_id, dstEquivalenceClass);
  5801. return;
  5802. }
  5803. if(dstEquivalenceClass == srcEquivalenceClass)
  5804. {
  5805. return;
  5806. }
  5807. Assert(!dstEquivalenceClass->Bv()->Test(src->m_id));
  5808. Assert(!srcEquivalenceClass->Bv()->Test(dst->m_id));
  5809. // Merge the two equivalence classes. The source's equivalence class is typically smaller, so it's merged into the
  5810. // destination's equivalence class. To save space and prevent a potential explosion of bit vector size,
  5811. // 'floatSymEquivalenceMap' is updated for syms in the source's equivalence class to map to the destination's now merged
  5812. // equivalence class, and the source's equivalence class is discarded.
  5813. dstEquivalenceClass->Or(srcEquivalenceClass);
  5814. FOREACH_BITSET_IN_SPARSEBV(id, srcEquivalenceClass->Bv())
  5815. {
  5816. floatSymEquivalenceMap->Item(id, dstEquivalenceClass);
  5817. } NEXT_BITSET_IN_SPARSEBV;
  5818. JitAdelete(tempAlloc, srcEquivalenceClass);
  5819. return;
  5820. }
  5821. // Not a float transfer, and non-prepass (not necessarily in a loop)
  5822. if(!instr->HasBailOutInfo() || instr->GetBailOutKind() != IR::BailOutPrimitiveButString)
  5823. {
  5824. return;
  5825. }
  5826. Assert(instr->m_opcode == Js::OpCode::FromVar);
  5827. // If either the destination or its equivalence class says it requires bailout on any non-number value, adjust the bailout
  5828. // kind on the instruction. Both are checked because in functions without loops, equivalence tracking is not done and only
  5829. // the sym's non-number bailout bit will have the information, and in functions with loops, equivalence tracking is done
  5830. // throughout the function and checking just the sym's non-number bailout bit is insufficient.
  5831. FloatSymEquivalenceClass *dstEquivalenceClass = nullptr;
  5832. if(dst->m_requiresBailOnNotNumber ||
  5833. (floatSymEquivalenceMap->TryGetValue(dst->m_id, &dstEquivalenceClass) && dstEquivalenceClass->RequiresBailOnNotNumber()))
  5834. {
  5835. instr->SetBailOutKind(IR::BailOutNumberOnly);
  5836. }
  5837. }
  5838. bool
  5839. BackwardPass::ProcessDef(IR::Opnd * opnd)
  5840. {
  5841. BOOLEAN isJITOptimizedReg = false;
  5842. Sym * sym;
  5843. if (opnd->IsRegOpnd())
  5844. {
  5845. sym = opnd->AsRegOpnd()->m_sym;
  5846. isJITOptimizedReg = opnd->GetIsJITOptimizedReg();
  5847. if (!IsCollectionPass())
  5848. {
  5849. this->InvalidateCloneStrCandidate(opnd);
  5850. }
  5851. }
  5852. else if (opnd->IsSymOpnd())
  5853. {
  5854. sym = opnd->AsSymOpnd()->m_sym;
  5855. isJITOptimizedReg = opnd->GetIsJITOptimizedReg();
  5856. }
  5857. else
  5858. {
  5859. if (opnd->IsIndirOpnd())
  5860. {
  5861. this->ProcessUse(opnd);
  5862. }
  5863. return false;
  5864. }
  5865. BasicBlock * block = this->currentBlock;
  5866. BOOLEAN isUsed = true;
  5867. BOOLEAN keepSymLiveForException = false;
  5868. BOOLEAN keepVarSymLiveForException = false;
  5869. IR::Instr * instr = this->currentInstr;
  5870. Assert(!instr->IsByteCodeUsesInstr());
  5871. if (sym->IsPropertySym())
  5872. {
  5873. if(IsCollectionPass())
  5874. {
  5875. return false;
  5876. }
  5877. Assert((block->fieldHoistCandidates != nullptr) == this->DoFieldHoistCandidates());
  5878. if (block->fieldHoistCandidates)
  5879. {
  5880. block->fieldHoistCandidates->Clear(sym->m_id);
  5881. }
  5882. PropertySym *propertySym = sym->AsPropertySym();
  5883. if (this->DoDeadStoreSlots())
  5884. {
  5885. if (propertySym->m_fieldKind == PropertyKindLocalSlots || propertySym->m_fieldKind == PropertyKindSlots)
  5886. {
  5887. BOOLEAN isPropertySymUsed = !block->slotDeadStoreCandidates->TestAndSet(propertySym->m_id);
  5888. // we should not do any dead slots in asmjs loop body
  5889. Assert(!(this->func->GetJITFunctionBody()->IsAsmJsMode() && this->func->IsLoopBody() && !isPropertySymUsed));
  5890. Assert(isPropertySymUsed || !block->upwardExposedUses->Test(propertySym->m_id));
  5891. isUsed = isPropertySymUsed || block->upwardExposedUses->Test(propertySym->m_stackSym->m_id);
  5892. }
  5893. }
  5894. this->DoSetDead(opnd, !block->upwardExposedFields->TestAndClear(propertySym->m_id));
  5895. ProcessStackSymUse(propertySym->m_stackSym, isJITOptimizedReg);
  5896. if (tag == Js::BackwardPhase)
  5897. {
  5898. if (opnd->AsSymOpnd()->IsPropertySymOpnd())
  5899. {
  5900. this->globOpt->PreparePropertySymOpndForTypeCheckSeq(opnd->AsPropertySymOpnd(), instr, this->currentBlock->loop);
  5901. }
  5902. }
  5903. if (opnd->AsSymOpnd()->IsPropertySymOpnd())
  5904. {
  5905. this->ProcessPropertySymOpndUse(opnd->AsPropertySymOpnd());
  5906. }
  5907. }
  5908. else
  5909. {
  5910. Assert(!instr->IsByteCodeUsesInstr());
  5911. if (this->DoByteCodeUpwardExposedUsed())
  5912. {
  5913. if (sym->AsStackSym()->HasByteCodeRegSlot())
  5914. {
  5915. StackSym * varSym = sym->AsStackSym();
  5916. if (varSym->IsTypeSpec())
  5917. {
  5918. // It has to have a var version for byte code regs
  5919. varSym = varSym->GetVarEquivSym(nullptr);
  5920. }
  5921. if (this->currentRegion)
  5922. {
  5923. keepSymLiveForException = this->CheckWriteThroughSymInRegion(this->currentRegion, sym->AsStackSym());
  5924. keepVarSymLiveForException = this->CheckWriteThroughSymInRegion(this->currentRegion, varSym);
  5925. }
  5926. if (!isJITOptimizedReg)
  5927. {
  5928. if (!DoDeadStore(this->func, sym->AsStackSym()))
  5929. {
  5930. // Don't deadstore the bytecodereg sym, so that we could do write to get the locals inspection
  5931. if (opnd->IsRegOpnd())
  5932. {
  5933. opnd->AsRegOpnd()->m_dontDeadStore = true;
  5934. }
  5935. }
  5936. // write through symbols should not be cleared from the byteCodeUpwardExposedUsed BV upon defs in the Try region:
  5937. // try
  5938. // x =
  5939. // <bailout> <-- this bailout should restore x from its first def. This would not happen if x is cleared
  5940. // from byteCodeUpwardExposedUsed when we process its second def
  5941. // <exception>
  5942. // x =
  5943. // catch
  5944. // = x
  5945. if (!keepVarSymLiveForException)
  5946. {
  5947. // Always track the sym use on the var sym.
  5948. block->byteCodeUpwardExposedUsed->Clear(varSym->m_id);
  5949. #if DBG
  5950. // TODO: We can only track first level function stack syms right now
  5951. if (varSym->GetByteCodeFunc() == this->func)
  5952. {
  5953. block->byteCodeRestoreSyms[varSym->GetByteCodeRegSlot()] = nullptr;
  5954. }
  5955. #endif
  5956. }
  5957. }
  5958. }
  5959. }
  5960. if(IsCollectionPass())
  5961. {
  5962. return false;
  5963. }
  5964. // Don't care about property sym for mark temps
  5965. if (opnd->IsRegOpnd())
  5966. {
  5967. this->MarkTemp(sym->AsStackSym());
  5968. }
  5969. if (this->tag == Js::BackwardPhase &&
  5970. instr->m_opcode == Js::OpCode::Ld_A &&
  5971. instr->GetSrc1()->IsRegOpnd() &&
  5972. block->upwardExposedFields->Test(sym->m_id))
  5973. {
  5974. block->upwardExposedFields->Set(instr->GetSrc1()->AsRegOpnd()->m_sym->m_id);
  5975. }
  5976. if (!keepSymLiveForException)
  5977. {
  5978. isUsed = block->upwardExposedUses->TestAndClear(sym->m_id);
  5979. }
  5980. }
  5981. if (isUsed || !this->DoDeadStore())
  5982. {
  5983. return false;
  5984. }
  5985. // FromVar on a primitive value has no side-effects
  5986. // TODO: There may be more cases where FromVars can be dead-stored, such as cases where they have a bailout that would bail
  5987. // out on non-primitive vars, thereby causing no side effects anyway. However, it needs to be ensured that no assumptions
  5988. // that depend on the bailout are made later in the function.
  5989. // Special case StFld for trackable fields
  5990. bool hasSideEffects = instr->HasAnySideEffects()
  5991. && instr->m_opcode != Js::OpCode::StFld
  5992. && instr->m_opcode != Js::OpCode::StRootFld
  5993. && instr->m_opcode != Js::OpCode::StFldStrict
  5994. && instr->m_opcode != Js::OpCode::StRootFldStrict;
  5995. if (this->IsPrePass() || hasSideEffects)
  5996. {
  5997. return false;
  5998. }
  5999. if (opnd->IsRegOpnd() && opnd->AsRegOpnd()->m_dontDeadStore)
  6000. {
  6001. return false;
  6002. }
  6003. if (instr->HasBailOutInfo())
  6004. {
  6005. // A bailout inserted for aggressive or lossy int type specialization causes assumptions to be made on the value of
  6006. // the instruction's destination later on, as though the bailout did not happen. If the value is an int constant and
  6007. // that value is propagated forward, it can cause the bailout instruction to become a dead store and be removed,
  6008. // thereby invalidating the assumptions made. Or for lossy int type specialization, the lossy conversion to int32
  6009. // may have side effects and so cannot be dead-store-removed. As one way of solving that problem, bailout
  6010. // instructions resulting from aggressive or lossy int type spec are not dead-stored.
  6011. const auto bailOutKind = instr->GetBailOutKind();
  6012. if(bailOutKind & IR::BailOutOnResultConditions)
  6013. {
  6014. return false;
  6015. }
  6016. switch(bailOutKind & ~IR::BailOutKindBits)
  6017. {
  6018. case IR::BailOutIntOnly:
  6019. case IR::BailOutNumberOnly:
  6020. case IR::BailOutExpectingInteger:
  6021. case IR::BailOutPrimitiveButString:
  6022. case IR::BailOutExpectingString:
  6023. case IR::BailOutOnNotPrimitive:
  6024. case IR::BailOutFailedInlineTypeCheck:
  6025. case IR::BailOutOnFloor:
  6026. case IR::BailOnModByPowerOf2:
  6027. case IR::BailOnDivResultNotInt:
  6028. case IR::BailOnIntMin:
  6029. return false;
  6030. }
  6031. }
  6032. // Dead store
  6033. DeadStoreInstr(instr);
  6034. return true;
  6035. }
  6036. bool
  6037. BackwardPass::DeadStoreInstr(IR::Instr *instr)
  6038. {
  6039. BasicBlock * block = this->currentBlock;
  6040. #if DBG_DUMP
  6041. if (this->IsTraceEnabled())
  6042. {
  6043. Output::Print(_u("Deadstore instr: "));
  6044. instr->Dump();
  6045. }
  6046. this->numDeadStore++;
  6047. #endif
  6048. // Before we remove the dead store, we need to track the byte code uses
  6049. if (this->DoByteCodeUpwardExposedUsed())
  6050. {
  6051. #if DBG
  6052. BVSparse<JitArenaAllocator> tempBv(this->tempAlloc);
  6053. tempBv.Copy(this->currentBlock->byteCodeUpwardExposedUsed);
  6054. #endif
  6055. PropertySym *unusedPropertySym = nullptr;
  6056. GlobOpt::TrackByteCodeSymUsed(instr, this->currentBlock->byteCodeUpwardExposedUsed, &unusedPropertySym);
  6057. #if DBG
  6058. BVSparse<JitArenaAllocator> tempBv2(this->tempAlloc);
  6059. tempBv2.Copy(this->currentBlock->byteCodeUpwardExposedUsed);
  6060. tempBv2.Minus(&tempBv);
  6061. FOREACH_BITSET_IN_SPARSEBV(symId, &tempBv2)
  6062. {
  6063. StackSym * stackSym = this->func->m_symTable->FindStackSym(symId);
  6064. Assert(stackSym->GetType() == TyVar);
  6065. // TODO: We can only track first level function stack syms right now
  6066. if (stackSym->GetByteCodeFunc() == this->func)
  6067. {
  6068. Js::RegSlot byteCodeRegSlot = stackSym->GetByteCodeRegSlot();
  6069. Assert(byteCodeRegSlot != Js::Constants::NoRegister);
  6070. if (this->currentBlock->byteCodeRestoreSyms[byteCodeRegSlot] != stackSym)
  6071. {
  6072. AssertMsg(this->currentBlock->byteCodeRestoreSyms[byteCodeRegSlot] == nullptr,
  6073. "Can't have two active lifetime for the same byte code register");
  6074. this->currentBlock->byteCodeRestoreSyms[byteCodeRegSlot] = stackSym;
  6075. }
  6076. }
  6077. }
  6078. NEXT_BITSET_IN_SPARSEBV;
  6079. #endif
  6080. }
  6081. // If this is a pre-op bailout instruction, we may have saved it for bailout info processing. It's being removed now, so no
  6082. // need to process the bailout info anymore.
  6083. Assert(!preOpBailOutInstrToProcess || preOpBailOutInstrToProcess == instr);
  6084. preOpBailOutInstrToProcess = nullptr;
  6085. #if DBG
  6086. if (this->DoMarkTempObjectVerify())
  6087. {
  6088. this->currentBlock->tempObjectVerifyTracker->NotifyDeadStore(instr, this);
  6089. }
  6090. #endif
  6091. if (instr->m_opcode == Js::OpCode::ArgIn_A)
  6092. {
  6093. //Ignore tracking ArgIn for "this", as argInsCount only tracks other params - unless it is a asmjs function(which doesn't have a "this").
  6094. if (instr->GetSrc1()->AsSymOpnd()->m_sym->AsStackSym()->GetParamSlotNum() != 1 || func->GetJITFunctionBody()->IsAsmJsMode())
  6095. {
  6096. Assert(this->func->argInsCount > 0);
  6097. this->func->argInsCount--;
  6098. }
  6099. }
  6100. TraceDeadStoreOfInstrsForScopeObjectRemoval();
  6101. block->RemoveInstr(instr);
  6102. return true;
  6103. }
  6104. void
  6105. BackwardPass::ProcessTransfers(IR::Instr * instr)
  6106. {
  6107. if (this->tag == Js::DeadStorePhase &&
  6108. this->currentBlock->upwardExposedFields &&
  6109. instr->m_opcode == Js::OpCode::Ld_A &&
  6110. instr->GetDst()->GetStackSym() &&
  6111. !instr->GetDst()->GetStackSym()->IsTypeSpec() &&
  6112. instr->GetDst()->GetStackSym()->HasObjectInfo() &&
  6113. instr->GetSrc1() &&
  6114. instr->GetSrc1()->GetStackSym() &&
  6115. !instr->GetSrc1()->GetStackSym()->IsTypeSpec() &&
  6116. instr->GetSrc1()->GetStackSym()->HasObjectInfo())
  6117. {
  6118. StackSym * dstStackSym = instr->GetDst()->GetStackSym();
  6119. PropertySym * dstPropertySym = dstStackSym->GetObjectInfo()->m_propertySymList;
  6120. BVSparse<JitArenaAllocator> transferFields(this->tempAlloc);
  6121. while (dstPropertySym != nullptr)
  6122. {
  6123. Assert(dstPropertySym->m_stackSym == dstStackSym);
  6124. transferFields.Set(dstPropertySym->m_id);
  6125. dstPropertySym = dstPropertySym->m_nextInStackSymList;
  6126. }
  6127. StackSym * srcStackSym = instr->GetSrc1()->GetStackSym();
  6128. PropertySym * srcPropertySym = srcStackSym->GetObjectInfo()->m_propertySymList;
  6129. BVSparse<JitArenaAllocator> equivFields(this->tempAlloc);
  6130. while (srcPropertySym != nullptr && !transferFields.IsEmpty())
  6131. {
  6132. Assert(srcPropertySym->m_stackSym == srcStackSym);
  6133. if (srcPropertySym->m_propertyEquivSet)
  6134. {
  6135. equivFields.And(&transferFields, srcPropertySym->m_propertyEquivSet);
  6136. if (!equivFields.IsEmpty())
  6137. {
  6138. transferFields.Minus(&equivFields);
  6139. this->currentBlock->upwardExposedFields->Set(srcPropertySym->m_id);
  6140. }
  6141. }
  6142. srcPropertySym = srcPropertySym->m_nextInStackSymList;
  6143. }
  6144. }
  6145. }
  6146. void
  6147. BackwardPass::ProcessFieldKills(IR::Instr * instr)
  6148. {
  6149. if (this->currentBlock->upwardExposedFields)
  6150. {
  6151. this->globOpt->ProcessFieldKills(instr, this->currentBlock->upwardExposedFields, false);
  6152. }
  6153. this->ClearBucketsOnFieldKill(instr, currentBlock->stackSymToFinalType);
  6154. this->ClearBucketsOnFieldKill(instr, currentBlock->stackSymToGuardedProperties);
  6155. }
  6156. template<typename T>
  6157. void
  6158. BackwardPass::ClearBucketsOnFieldKill(IR::Instr *instr, HashTable<T> *table)
  6159. {
  6160. if (table)
  6161. {
  6162. if (instr->UsesAllFields())
  6163. {
  6164. table->ClearAll();
  6165. }
  6166. else
  6167. {
  6168. IR::Opnd *dst = instr->GetDst();
  6169. if (dst && dst->IsRegOpnd())
  6170. {
  6171. table->Clear(dst->AsRegOpnd()->m_sym->m_id);
  6172. }
  6173. }
  6174. }
  6175. }
  6176. void
  6177. BackwardPass::ProcessFieldHoistKills(IR::Instr * instr)
  6178. {
  6179. // The backward pass, we optimistically will not kill on a[] access
  6180. // So that the field hoist candidate will be more then what can be hoisted
  6181. // The root prepass will figure out the exact set of field that is hoisted
  6182. this->globOpt->ProcessFieldKills(instr, this->currentBlock->fieldHoistCandidates, false);
  6183. switch (instr->m_opcode)
  6184. {
  6185. case Js::OpCode::BrOnHasProperty:
  6186. case Js::OpCode::BrOnNoProperty:
  6187. // Should not hoist pass these instructions
  6188. this->currentBlock->fieldHoistCandidates->Clear(instr->GetSrc1()->AsSymOpnd()->m_sym->m_id);
  6189. break;
  6190. }
  6191. }
  6192. bool
  6193. BackwardPass::TrackNoImplicitCallInlinees(IR::Instr *instr)
  6194. {
  6195. if (this->tag != Js::DeadStorePhase || this->IsPrePass())
  6196. {
  6197. return false;
  6198. }
  6199. if (instr->HasBailOutInfo()
  6200. || OpCodeAttr::CallInstr(instr->m_opcode)
  6201. || instr->CallsAccessor()
  6202. || GlobOpt::MayNeedBailOnImplicitCall(instr, nullptr, nullptr)
  6203. || instr->HasAnyLoadHeapArgsOpCode()
  6204. || instr->m_opcode == Js::OpCode::LdFuncExpr)
  6205. {
  6206. // This func has instrs with bailouts or implicit calls
  6207. Assert(instr->m_opcode != Js::OpCode::InlineeStart);
  6208. instr->m_func->SetHasImplicitCallsOnSelfAndParents();
  6209. return false;
  6210. }
  6211. if (instr->m_opcode == Js::OpCode::InlineeStart)
  6212. {
  6213. if (!instr->GetSrc1())
  6214. {
  6215. Assert(instr->m_func->m_hasInlineArgsOpt);
  6216. return false;
  6217. }
  6218. return this->ProcessInlineeStart(instr);
  6219. }
  6220. return false;
  6221. }
  6222. bool
  6223. BackwardPass::ProcessInlineeStart(IR::Instr* inlineeStart)
  6224. {
  6225. inlineeStart->m_func->SetFirstArgOffset(inlineeStart);
  6226. IR::Instr* startCallInstr = nullptr;
  6227. bool noImplicitCallsInInlinee = false;
  6228. // Inlinee has no bailouts or implicit calls. Get rid of the inline overhead.
  6229. auto removeInstr = [&](IR::Instr* argInstr)
  6230. {
  6231. Assert(argInstr->m_opcode == Js::OpCode::InlineeStart || argInstr->m_opcode == Js::OpCode::ArgOut_A || argInstr->m_opcode == Js::OpCode::ArgOut_A_Inline);
  6232. IR::Opnd *opnd = argInstr->GetSrc1();
  6233. StackSym *sym = opnd->GetStackSym();
  6234. if (!opnd->GetIsJITOptimizedReg() && sym && sym->HasByteCodeRegSlot())
  6235. {
  6236. // Replace instrs with bytecodeUses
  6237. IR::ByteCodeUsesInstr *bytecodeUse = IR::ByteCodeUsesInstr::New(argInstr);
  6238. bytecodeUse->Set(opnd);
  6239. argInstr->InsertBefore(bytecodeUse);
  6240. }
  6241. startCallInstr = argInstr->GetSrc2()->GetStackSym()->m_instrDef;
  6242. FlowGraph::SafeRemoveInstr(argInstr);
  6243. return false;
  6244. };
  6245. // If there are no implicit calls - bailouts/throws - we can remove all inlining overhead.
  6246. if (!inlineeStart->m_func->GetHasImplicitCalls())
  6247. {
  6248. noImplicitCallsInInlinee = true;
  6249. inlineeStart->IterateArgInstrs(removeInstr);
  6250. inlineeStart->IterateMetaArgs([](IR::Instr* metArg)
  6251. {
  6252. FlowGraph::SafeRemoveInstr(metArg);
  6253. return false;
  6254. });
  6255. inlineeStart->m_func->m_hasInlineArgsOpt = false;
  6256. removeInstr(inlineeStart);
  6257. return true;
  6258. }
  6259. if (!inlineeStart->m_func->m_hasInlineArgsOpt)
  6260. {
  6261. PHASE_PRINT_TESTTRACE(Js::InlineArgsOptPhase, func, _u("%s[%d]: Skipping inline args optimization: %s[%d] HasCalls: %s 'arguments' access: %s Can do inlinee args opt: %s\n"),
  6262. func->GetJITFunctionBody()->GetDisplayName(), func->GetJITFunctionBody()->GetFunctionNumber(),
  6263. inlineeStart->m_func->GetJITFunctionBody()->GetDisplayName(), inlineeStart->m_func->GetJITFunctionBody()->GetFunctionNumber(),
  6264. IsTrueOrFalse(inlineeStart->m_func->GetHasCalls()),
  6265. IsTrueOrFalse(inlineeStart->m_func->GetHasUnoptimizedArgumentsAccess()),
  6266. IsTrueOrFalse(inlineeStart->m_func->m_canDoInlineArgsOpt));
  6267. return false;
  6268. }
  6269. if (!inlineeStart->m_func->frameInfo->isRecorded)
  6270. {
  6271. PHASE_PRINT_TESTTRACE(Js::InlineArgsOptPhase, func, _u("%s[%d]: InlineeEnd not found - usually due to a throw or a BailOnNoProfile (stressed, most likely)\n"),
  6272. func->GetJITFunctionBody()->GetDisplayName(), func->GetJITFunctionBody()->GetFunctionNumber());
  6273. inlineeStart->m_func->DisableCanDoInlineArgOpt();
  6274. return false;
  6275. }
  6276. inlineeStart->IterateArgInstrs(removeInstr);
  6277. int i = 0;
  6278. inlineeStart->IterateMetaArgs([&](IR::Instr* metaArg)
  6279. {
  6280. if (i == Js::Constants::InlineeMetaArgIndex_ArgumentsObject &&
  6281. inlineeStart->m_func->GetJITFunctionBody()->UsesArgumentsObject())
  6282. {
  6283. Assert(!inlineeStart->m_func->GetHasUnoptimizedArgumentsAccess());
  6284. // Do not remove arguments object meta arg if there is a reference to arguments object
  6285. }
  6286. else
  6287. {
  6288. FlowGraph::SafeRemoveInstr(metaArg);
  6289. }
  6290. i++;
  6291. return false;
  6292. });
  6293. IR::Opnd *src1 = inlineeStart->GetSrc1();
  6294. StackSym *sym = src1->GetStackSym();
  6295. if (!src1->GetIsJITOptimizedReg() && sym && sym->HasByteCodeRegSlot())
  6296. {
  6297. // Replace instrs with bytecodeUses
  6298. IR::ByteCodeUsesInstr *bytecodeUse = IR::ByteCodeUsesInstr::New(inlineeStart);
  6299. bytecodeUse->Set(src1);
  6300. inlineeStart->InsertBefore(bytecodeUse);
  6301. }
  6302. // This indicates to the lowerer that this inlinee has been optimized
  6303. // and it should not be lowered - Now this instruction is used to mark inlineeStart
  6304. inlineeStart->FreeSrc1();
  6305. inlineeStart->FreeSrc2();
  6306. inlineeStart->FreeDst();
  6307. return true;
  6308. }
  6309. void
  6310. BackwardPass::ProcessInlineeEnd(IR::Instr* instr)
  6311. {
  6312. if (this->IsPrePass())
  6313. {
  6314. return;
  6315. }
  6316. if (this->tag == Js::BackwardPhase)
  6317. {
  6318. if (!GlobOpt::DoInlineArgsOpt(instr->m_func))
  6319. {
  6320. return;
  6321. }
  6322. // This adds a use for function sym as part of InlineeStart & all the syms referenced by the args.
  6323. // It ensure they do not get cleared from the copy prop sym map.
  6324. instr->IterateArgInstrs([=](IR::Instr* argInstr){
  6325. if (argInstr->GetSrc1()->IsRegOpnd())
  6326. {
  6327. this->currentBlock->upwardExposedUses->Set(argInstr->GetSrc1()->AsRegOpnd()->m_sym->m_id);
  6328. }
  6329. return false;
  6330. });
  6331. }
  6332. else if (this->tag == Js::DeadStorePhase)
  6333. {
  6334. if (instr->m_func->m_hasInlineArgsOpt)
  6335. {
  6336. Assert(instr->m_func->frameInfo);
  6337. instr->m_func->frameInfo->IterateSyms([=](StackSym* argSym)
  6338. {
  6339. this->currentBlock->upwardExposedUses->Set(argSym->m_id);
  6340. });
  6341. }
  6342. }
  6343. }
  6344. bool
  6345. BackwardPass::ProcessBailOnNoProfile(IR::Instr *instr, BasicBlock *block)
  6346. {
  6347. Assert(this->tag == Js::BackwardPhase);
  6348. Assert(instr->m_opcode == Js::OpCode::BailOnNoProfile);
  6349. Assert(!instr->HasBailOutInfo());
  6350. AnalysisAssert(block);
  6351. if (this->IsPrePass())
  6352. {
  6353. return false;
  6354. }
  6355. IR::Instr *curInstr = instr->m_prev;
  6356. if (curInstr->IsLabelInstr() && curInstr->AsLabelInstr()->isOpHelper)
  6357. {
  6358. // Already processed
  6359. if (this->DoMarkTempObjects())
  6360. {
  6361. block->tempObjectTracker->ProcessBailOnNoProfile(instr);
  6362. }
  6363. return false;
  6364. }
  6365. // Don't hoist if we see calls with profile data (recursive calls)
  6366. while(!curInstr->StartsBasicBlock())
  6367. {
  6368. // If a function was inlined, it must have had profile info.
  6369. if (curInstr->m_opcode == Js::OpCode::InlineeEnd || curInstr->m_opcode == Js::OpCode::InlineBuiltInEnd || curInstr->m_opcode == Js::OpCode::InlineNonTrackingBuiltInEnd
  6370. || curInstr->m_opcode == Js::OpCode::InlineeStart || curInstr->m_opcode == Js::OpCode::EndCallForPolymorphicInlinee)
  6371. {
  6372. break;
  6373. }
  6374. else if (OpCodeAttr::CallInstr(curInstr->m_opcode))
  6375. {
  6376. if (curInstr->m_prev->m_opcode != Js::OpCode::BailOnNoProfile)
  6377. {
  6378. break;
  6379. }
  6380. }
  6381. curInstr = curInstr->m_prev;
  6382. }
  6383. // Didn't get to the top of the block, delete this BailOnNoProfile.
  6384. if (!curInstr->IsLabelInstr())
  6385. {
  6386. block->RemoveInstr(instr);
  6387. return true;
  6388. }
  6389. // Save the head instruction for later use.
  6390. IR::LabelInstr *blockHeadInstr = curInstr->AsLabelInstr();
  6391. // We can't bail in the middle of a "tmp = CmEq s1, s2; BrTrue tmp" turned into a "BrEq s1, s2",
  6392. // because the bailout wouldn't be able to restore tmp.
  6393. IR::Instr *curNext = curInstr->GetNextRealInstrOrLabel();
  6394. IR::Instr *instrNope = nullptr;
  6395. if (curNext->m_opcode == Js::OpCode::Ld_A && curNext->GetDst()->IsRegOpnd() && curNext->GetDst()->AsRegOpnd()->m_fgPeepTmp)
  6396. {
  6397. block->RemoveInstr(instr);
  6398. return true;
  6399. /*while (curNext->m_opcode == Js::OpCode::Ld_A && curNext->GetDst()->IsRegOpnd() && curNext->GetDst()->AsRegOpnd()->m_fgPeepTmp)
  6400. {
  6401. // Instead of just giving up, we can be a little trickier. We can instead treat the tmp declaration(s) as a
  6402. // part of the block prefix, and put the bailonnoprofile immediately after them. This has the added benefit
  6403. // that we can still merge up blocks beginning with bailonnoprofile, even if they would otherwise not allow
  6404. // us to, due to the fact that these tmp declarations would be pre-empted by the higher-level bailout.
  6405. instrNope = curNext;
  6406. curNext = curNext->GetNextRealInstrOrLabel();
  6407. }*/
  6408. }
  6409. curInstr = instr->m_prev;
  6410. // Move to top of block (but just below any fgpeeptemp lds).
  6411. while(!curInstr->StartsBasicBlock() && curInstr != instrNope)
  6412. {
  6413. // Delete redundant BailOnNoProfile
  6414. if (curInstr->m_opcode == Js::OpCode::BailOnNoProfile)
  6415. {
  6416. Assert(!curInstr->HasBailOutInfo());
  6417. curInstr = curInstr->m_next;
  6418. curInstr->m_prev->Remove();
  6419. }
  6420. curInstr = curInstr->m_prev;
  6421. }
  6422. if (instr == block->GetLastInstr())
  6423. {
  6424. block->SetLastInstr(instr->m_prev);
  6425. }
  6426. instr->Unlink();
  6427. // Now try to move this up the flowgraph to the predecessor blocks
  6428. FOREACH_PREDECESSOR_BLOCK(pred, block)
  6429. {
  6430. bool hoistBailToPred = true;
  6431. if (block->isLoopHeader && pred->loop == block->loop)
  6432. {
  6433. // Skip loop back-edges
  6434. continue;
  6435. }
  6436. // If all successors of this predecessor start with a BailOnNoProfile, we should be
  6437. // okay to hoist this bail to the predecessor.
  6438. FOREACH_SUCCESSOR_BLOCK(predSucc, pred)
  6439. {
  6440. if (predSucc == block)
  6441. {
  6442. continue;
  6443. }
  6444. if (!predSucc->beginsBailOnNoProfile)
  6445. {
  6446. hoistBailToPred = false;
  6447. break;
  6448. }
  6449. } NEXT_SUCCESSOR_BLOCK;
  6450. if (hoistBailToPred)
  6451. {
  6452. IR::Instr *predInstr = pred->GetLastInstr();
  6453. IR::Instr *instrCopy = instr->Copy();
  6454. if (predInstr->EndsBasicBlock())
  6455. {
  6456. if (predInstr->m_prev->m_opcode == Js::OpCode::BailOnNoProfile)
  6457. {
  6458. // We already have one, we don't need a second.
  6459. instrCopy->Free();
  6460. }
  6461. else if (!predInstr->AsBranchInstr()->m_isSwitchBr)
  6462. {
  6463. // Don't put a bailout in the middle of a switch dispatch sequence.
  6464. // The bytecode offsets are not in order, and it would lead to incorrect
  6465. // bailout info.
  6466. instrCopy->m_func = predInstr->m_func;
  6467. predInstr->InsertBefore(instrCopy);
  6468. }
  6469. }
  6470. else
  6471. {
  6472. if (predInstr->m_opcode == Js::OpCode::BailOnNoProfile)
  6473. {
  6474. // We already have one, we don't need a second.
  6475. instrCopy->Free();
  6476. }
  6477. else
  6478. {
  6479. instrCopy->m_func = predInstr->m_func;
  6480. predInstr->InsertAfter(instrCopy);
  6481. pred->SetLastInstr(instrCopy);
  6482. }
  6483. }
  6484. }
  6485. } NEXT_PREDECESSOR_BLOCK;
  6486. // If we have a BailOnNoProfile in the first block, there must have been at least one path out of this block that always throws.
  6487. // Don't bother keeping the bailout in the first block as there are some issues in restoring the ArgIn bytecode registers on bailout
  6488. // and throw case should be rare enough that it won't matter for perf.
  6489. if (block->GetBlockNum() != 0)
  6490. {
  6491. blockHeadInstr->isOpHelper = true;
  6492. #if DBG
  6493. blockHeadInstr->m_noHelperAssert = true;
  6494. #endif
  6495. block->beginsBailOnNoProfile = true;
  6496. instr->m_func = curInstr->m_func;
  6497. curInstr->InsertAfter(instr);
  6498. bool setLastInstr = (curInstr == block->GetLastInstr());
  6499. if (setLastInstr)
  6500. {
  6501. block->SetLastInstr(instr);
  6502. }
  6503. if (this->DoMarkTempObjects())
  6504. {
  6505. block->tempObjectTracker->ProcessBailOnNoProfile(instr);
  6506. }
  6507. return false;
  6508. }
  6509. else
  6510. {
  6511. instr->Free();
  6512. return true;
  6513. }
  6514. }
  6515. bool
  6516. BackwardPass::ReverseCopyProp(IR::Instr *instr)
  6517. {
  6518. // Look for :
  6519. //
  6520. // t1 = instr
  6521. // [bytecodeuse t1]
  6522. // t2 = Ld_A t1 >> t1 !upwardExposed
  6523. //
  6524. // Transform into:
  6525. //
  6526. // t2 = instr
  6527. //
  6528. if (PHASE_OFF(Js::ReverseCopyPropPhase, this->func))
  6529. {
  6530. return false;
  6531. }
  6532. if (this->tag != Js::DeadStorePhase || this->IsPrePass() || this->IsCollectionPass())
  6533. {
  6534. return false;
  6535. }
  6536. if (this->func->HasTry())
  6537. {
  6538. // UpwardExposedUsed info can't be relied on
  6539. return false;
  6540. }
  6541. // Find t2 = Ld_A t1
  6542. switch (instr->m_opcode)
  6543. {
  6544. case Js::OpCode::Ld_A:
  6545. case Js::OpCode::Ld_I4:
  6546. break;
  6547. default:
  6548. return false;
  6549. }
  6550. if (!instr->GetDst()->IsRegOpnd())
  6551. {
  6552. return false;
  6553. }
  6554. if (!instr->GetSrc1()->IsRegOpnd())
  6555. {
  6556. return false;
  6557. }
  6558. if (instr->HasBailOutInfo())
  6559. {
  6560. return false;
  6561. }
  6562. IR::RegOpnd *dst = instr->GetDst()->AsRegOpnd();
  6563. IR::RegOpnd *src = instr->GetSrc1()->AsRegOpnd();
  6564. IR::Instr *instrPrev = instr->GetPrevRealInstrOrLabel();
  6565. IR::ByteCodeUsesInstr *byteCodeUseInstr = nullptr;
  6566. StackSym *varSym = src->m_sym;
  6567. if (varSym->IsTypeSpec())
  6568. {
  6569. varSym = varSym->GetVarEquivSym(this->func);
  6570. }
  6571. // SKip ByteCodeUse instr if possible
  6572. // [bytecodeuse t1]
  6573. if (!instrPrev->GetDst())
  6574. {
  6575. if (instrPrev->m_opcode == Js::OpCode::ByteCodeUses)
  6576. {
  6577. byteCodeUseInstr = instrPrev->AsByteCodeUsesInstr();
  6578. const BVSparse<JitArenaAllocator>* byteCodeUpwardExposedUsed = byteCodeUseInstr->GetByteCodeUpwardExposedUsed();
  6579. if (byteCodeUpwardExposedUsed && byteCodeUpwardExposedUsed->Test(varSym->m_id) && byteCodeUpwardExposedUsed->Count() == 1)
  6580. {
  6581. instrPrev = byteCodeUseInstr->GetPrevRealInstrOrLabel();
  6582. if (!instrPrev->GetDst())
  6583. {
  6584. return false;
  6585. }
  6586. }
  6587. else
  6588. {
  6589. return false;
  6590. }
  6591. }
  6592. else
  6593. {
  6594. return false;
  6595. }
  6596. }
  6597. // The fast-path for these doesn't handle dst == src.
  6598. // REVIEW: I believe the fast-path for LdElemI_A has been fixed... Nope, still broken for "i = A[i]" for prejit
  6599. switch (instrPrev->m_opcode)
  6600. {
  6601. case Js::OpCode::LdElemI_A:
  6602. case Js::OpCode::IsInst:
  6603. case Js::OpCode::ByteCodeUses:
  6604. return false;
  6605. }
  6606. // Can't do it if post-op bailout would need result
  6607. // REVIEW: enable for pre-opt bailout?
  6608. if (instrPrev->HasBailOutInfo() && instrPrev->GetByteCodeOffset() != instrPrev->GetBailOutInfo()->bailOutOffset)
  6609. {
  6610. return false;
  6611. }
  6612. // Make sure src of Ld_A == dst of instr
  6613. // t1 = instr
  6614. if (!instrPrev->GetDst()->IsEqual(src))
  6615. {
  6616. return false;
  6617. }
  6618. // Make sure t1 isn't used later
  6619. if (this->currentBlock->upwardExposedUses->Test(src->m_sym->m_id))
  6620. {
  6621. return false;
  6622. }
  6623. if (this->currentBlock->byteCodeUpwardExposedUsed && this->currentBlock->byteCodeUpwardExposedUsed->Test(varSym->m_id))
  6624. {
  6625. return false;
  6626. }
  6627. // Make sure we can dead-store this sym (debugger mode?)
  6628. if (!this->DoDeadStore(this->func, src->m_sym))
  6629. {
  6630. return false;
  6631. }
  6632. StackSym *const dstSym = dst->m_sym;
  6633. if(instrPrev->HasBailOutInfo() && dstSym->IsInt32() && dstSym->IsTypeSpec())
  6634. {
  6635. StackSym *const prevDstSym = IR::RegOpnd::TryGetStackSym(instrPrev->GetDst());
  6636. if(instrPrev->GetBailOutKind() & IR::BailOutOnResultConditions &&
  6637. prevDstSym &&
  6638. prevDstSym->IsInt32() &&
  6639. prevDstSym->IsTypeSpec() &&
  6640. instrPrev->GetSrc1() &&
  6641. !instrPrev->GetDst()->IsEqual(instrPrev->GetSrc1()) &&
  6642. !(instrPrev->GetSrc2() && instrPrev->GetDst()->IsEqual(instrPrev->GetSrc2())))
  6643. {
  6644. // The previous instruction's dst value may be trashed by the time of the pre-op bailout. Skip reverse copy-prop if
  6645. // it would replace the previous instruction's dst with a sym that bailout had decided to use to restore a value for
  6646. // the pre-op bailout, which can't be trashed before bailout. See big comment in ProcessBailOutCopyProps for the
  6647. // reasoning behind the tests above.
  6648. FOREACH_SLISTBASE_ENTRY(
  6649. CopyPropSyms,
  6650. usedCopyPropSym,
  6651. &instrPrev->GetBailOutInfo()->usedCapturedValues.copyPropSyms)
  6652. {
  6653. if(dstSym == usedCopyPropSym.Value())
  6654. {
  6655. return false;
  6656. }
  6657. } NEXT_SLISTBASE_ENTRY;
  6658. }
  6659. }
  6660. if (byteCodeUseInstr)
  6661. {
  6662. if (this->currentBlock->byteCodeUpwardExposedUsed && instrPrev->GetDst()->AsRegOpnd()->GetIsJITOptimizedReg() && varSym->HasByteCodeRegSlot())
  6663. {
  6664. if(varSym->HasByteCodeRegSlot())
  6665. {
  6666. this->currentBlock->byteCodeUpwardExposedUsed->Set(varSym->m_id);
  6667. }
  6668. if (src->IsEqual(dst) && instrPrev->GetDst()->GetIsJITOptimizedReg())
  6669. {
  6670. // s2(s1).i32 = FromVar s1.var #0000 Bailout: #0000 (BailOutIntOnly)
  6671. // ByteCodeUses s1
  6672. // s2(s1).i32 = Ld_A s2(s1).i32
  6673. //
  6674. // Since the dst on the FromVar is marked JITOptimized, we need to set it on the new dst as well,
  6675. // or we'll change the bytecode liveness of s1
  6676. dst->SetIsJITOptimizedReg(true);
  6677. }
  6678. }
  6679. byteCodeUseInstr->Remove();
  6680. }
  6681. else if (instrPrev->GetDst()->AsRegOpnd()->GetIsJITOptimizedReg() && !src->GetIsJITOptimizedReg() && varSym->HasByteCodeRegSlot())
  6682. {
  6683. this->currentBlock->byteCodeUpwardExposedUsed->Set(varSym->m_id);
  6684. }
  6685. #if DBG
  6686. if (this->DoMarkTempObjectVerify())
  6687. {
  6688. this->currentBlock->tempObjectVerifyTracker->NotifyReverseCopyProp(instrPrev);
  6689. }
  6690. #endif
  6691. dst->SetValueType(instrPrev->GetDst()->GetValueType());
  6692. instrPrev->ReplaceDst(dst);
  6693. instr->Remove();
  6694. return true;
  6695. }
  6696. bool
  6697. BackwardPass::FoldCmBool(IR::Instr *instr)
  6698. {
  6699. Assert(instr->m_opcode == Js::OpCode::Conv_Bool);
  6700. if (this->tag != Js::DeadStorePhase || this->IsPrePass() || this->IsCollectionPass())
  6701. {
  6702. return false;
  6703. }
  6704. if (this->func->HasTry())
  6705. {
  6706. // UpwardExposedUsed info can't be relied on
  6707. return false;
  6708. }
  6709. IR::RegOpnd *intOpnd = instr->GetSrc1()->AsRegOpnd();
  6710. Assert(intOpnd->m_sym->IsInt32());
  6711. if (!intOpnd->m_sym->IsSingleDef())
  6712. {
  6713. return false;
  6714. }
  6715. IR::Instr *cmInstr = intOpnd->m_sym->GetInstrDef();
  6716. // Should be a Cm instr...
  6717. if (!cmInstr->GetSrc2())
  6718. {
  6719. return false;
  6720. }
  6721. IR::Instr *instrPrev = instr->GetPrevRealInstrOrLabel();
  6722. if (instrPrev != cmInstr)
  6723. {
  6724. return false;
  6725. }
  6726. switch (cmInstr->m_opcode)
  6727. {
  6728. case Js::OpCode::CmEq_A:
  6729. case Js::OpCode::CmGe_A:
  6730. case Js::OpCode::CmUnGe_A:
  6731. case Js::OpCode::CmGt_A:
  6732. case Js::OpCode::CmUnGt_A:
  6733. case Js::OpCode::CmLt_A:
  6734. case Js::OpCode::CmUnLt_A:
  6735. case Js::OpCode::CmLe_A:
  6736. case Js::OpCode::CmUnLe_A:
  6737. case Js::OpCode::CmNeq_A:
  6738. case Js::OpCode::CmSrEq_A:
  6739. case Js::OpCode::CmSrNeq_A:
  6740. case Js::OpCode::CmEq_I4:
  6741. case Js::OpCode::CmNeq_I4:
  6742. case Js::OpCode::CmLt_I4:
  6743. case Js::OpCode::CmLe_I4:
  6744. case Js::OpCode::CmGt_I4:
  6745. case Js::OpCode::CmGe_I4:
  6746. case Js::OpCode::CmUnLt_I4:
  6747. case Js::OpCode::CmUnLe_I4:
  6748. case Js::OpCode::CmUnGt_I4:
  6749. case Js::OpCode::CmUnGe_I4:
  6750. break;
  6751. default:
  6752. return false;
  6753. }
  6754. IR::RegOpnd *varDst = instr->GetDst()->AsRegOpnd();
  6755. if (this->currentBlock->upwardExposedUses->Test(intOpnd->m_sym->m_id) || !this->currentBlock->upwardExposedUses->Test(varDst->m_sym->m_id))
  6756. {
  6757. return false;
  6758. }
  6759. varDst = instr->UnlinkDst()->AsRegOpnd();
  6760. cmInstr->ReplaceDst(varDst);
  6761. this->currentBlock->RemoveInstr(instr);
  6762. return true;
  6763. }
  6764. void
  6765. BackwardPass::SetWriteThroughSymbolsSetForRegion(BasicBlock * catchOrFinallyBlock, Region * tryRegion)
  6766. {
  6767. tryRegion->writeThroughSymbolsSet = JitAnew(this->func->m_alloc, BVSparse<JitArenaAllocator>, this->func->m_alloc);
  6768. if (this->DoByteCodeUpwardExposedUsed())
  6769. {
  6770. Assert(catchOrFinallyBlock->byteCodeUpwardExposedUsed);
  6771. if (!catchOrFinallyBlock->byteCodeUpwardExposedUsed->IsEmpty())
  6772. {
  6773. FOREACH_BITSET_IN_SPARSEBV(id, catchOrFinallyBlock->byteCodeUpwardExposedUsed)
  6774. {
  6775. tryRegion->writeThroughSymbolsSet->Set(id);
  6776. }
  6777. NEXT_BITSET_IN_SPARSEBV
  6778. }
  6779. #if DBG
  6780. // Symbols write-through in the parent try region should be marked as write-through in the current try region as well.
  6781. // x =
  6782. // try{
  6783. // try{
  6784. // x = <-- x needs to be write-through here. With the current mechanism of not clearing a write-through
  6785. // symbol from the bytecode upward-exposed on a def, x should be marked as write-through as
  6786. // write-through symbols for a try are basically the bytecode upward exposed symbols at the
  6787. // beginning of the corresponding catch block).
  6788. // Verify that it still holds.
  6789. // <exception>
  6790. // }
  6791. // catch(){}
  6792. // x =
  6793. // }
  6794. // catch(){}
  6795. // = x
  6796. if (tryRegion->GetParent()->GetType() == RegionTypeTry)
  6797. {
  6798. Region * parentTry = tryRegion->GetParent();
  6799. Assert(parentTry->writeThroughSymbolsSet);
  6800. FOREACH_BITSET_IN_SPARSEBV(id, parentTry->writeThroughSymbolsSet)
  6801. {
  6802. Assert(tryRegion->writeThroughSymbolsSet->Test(id));
  6803. }
  6804. NEXT_BITSET_IN_SPARSEBV
  6805. }
  6806. #endif
  6807. }
  6808. else
  6809. {
  6810. // this can happen with -off:globopt
  6811. return;
  6812. }
  6813. }
  6814. bool
  6815. BackwardPass::CheckWriteThroughSymInRegion(Region* region, StackSym* sym)
  6816. {
  6817. if (region->GetType() == RegionTypeRoot)
  6818. {
  6819. return false;
  6820. }
  6821. // if the current region is a try region, check in its write-through set,
  6822. // otherwise (current = catch region) look in the first try ancestor's write-through set
  6823. Region * selfOrFirstTryAncestor = region->GetSelfOrFirstTryAncestor();
  6824. if (!selfOrFirstTryAncestor)
  6825. {
  6826. return false;
  6827. }
  6828. Assert(selfOrFirstTryAncestor->GetType() == RegionTypeTry);
  6829. return selfOrFirstTryAncestor->writeThroughSymbolsSet && selfOrFirstTryAncestor->writeThroughSymbolsSet->Test(sym->m_id);
  6830. }
  6831. bool
  6832. BackwardPass::DoDeadStoreLdStForMemop(IR::Instr *instr)
  6833. {
  6834. Assert(this->tag == Js::DeadStorePhase && this->currentBlock->loop != nullptr);
  6835. Loop *loop = this->currentBlock->loop;
  6836. if (globOpt->HasMemOp(loop))
  6837. {
  6838. if (instr->m_opcode == Js::OpCode::StElemI_A && instr->GetDst()->IsIndirOpnd())
  6839. {
  6840. SymID base = this->globOpt->GetVarSymID(instr->GetDst()->AsIndirOpnd()->GetBaseOpnd()->GetStackSym());
  6841. SymID index = this->globOpt->GetVarSymID(instr->GetDst()->AsIndirOpnd()->GetIndexOpnd()->GetStackSym());
  6842. FOREACH_MEMOP_CANDIDATES(candidate, loop)
  6843. {
  6844. if (base == candidate->base && index == candidate->index)
  6845. {
  6846. return true;
  6847. }
  6848. } NEXT_MEMOP_CANDIDATE
  6849. }
  6850. else if (instr->m_opcode == Js::OpCode::LdElemI_A && instr->GetSrc1()->IsIndirOpnd())
  6851. {
  6852. SymID base = this->globOpt->GetVarSymID(instr->GetSrc1()->AsIndirOpnd()->GetBaseOpnd()->GetStackSym());
  6853. SymID index = this->globOpt->GetVarSymID(instr->GetSrc1()->AsIndirOpnd()->GetIndexOpnd()->GetStackSym());
  6854. FOREACH_MEMCOPY_CANDIDATES(candidate, loop)
  6855. {
  6856. if (base == candidate->ldBase && index == candidate->index)
  6857. {
  6858. return true;
  6859. }
  6860. } NEXT_MEMCOPY_CANDIDATE
  6861. }
  6862. }
  6863. return false;
  6864. }
  6865. void
  6866. BackwardPass::RestoreInductionVariableValuesAfterMemOp(Loop *loop)
  6867. {
  6868. const auto RestoreInductionVariable = [&](SymID symId, Loop::InductionVariableChangeInfo inductionVariableChangeInfo, Loop *loop)
  6869. {
  6870. Js::OpCode opCode = Js::OpCode::Add_I4;
  6871. if (!inductionVariableChangeInfo.isIncremental)
  6872. {
  6873. opCode = Js::OpCode::Sub_I4;
  6874. }
  6875. Func *localFunc = loop->GetFunc();
  6876. StackSym *sym = localFunc->m_symTable->FindStackSym(symId)->GetInt32EquivSym(localFunc);
  6877. IR::Opnd *inductionVariableOpnd = IR::RegOpnd::New(sym, IRType::TyInt32, localFunc);
  6878. IR::Opnd *sizeOpnd = globOpt->GenerateInductionVariableChangeForMemOp(loop, inductionVariableChangeInfo.unroll);
  6879. loop->landingPad->InsertAfter(IR::Instr::New(opCode, inductionVariableOpnd, inductionVariableOpnd, sizeOpnd, loop->GetFunc()));
  6880. };
  6881. for (auto it = loop->memOpInfo->inductionVariableChangeInfoMap->GetIterator(); it.IsValid(); it.MoveNext())
  6882. {
  6883. Loop::InductionVariableChangeInfo iv = it.CurrentValue();
  6884. SymID sym = it.CurrentKey();
  6885. if (iv.unroll != Js::Constants::InvalidLoopUnrollFactor)
  6886. {
  6887. // if the variable is being used after the loop restore it
  6888. if (loop->memOpInfo->inductionVariablesUsedAfterLoop->Test(sym))
  6889. {
  6890. RestoreInductionVariable(sym, iv, loop);
  6891. }
  6892. }
  6893. }
  6894. }
  6895. bool
  6896. BackwardPass::IsEmptyLoopAfterMemOp(Loop *loop)
  6897. {
  6898. if (globOpt->HasMemOp(loop))
  6899. {
  6900. const auto IsInductionVariableUse = [&](IR::Opnd *opnd) -> bool
  6901. {
  6902. Loop::InductionVariableChangeInfo inductionVariableChangeInfo = { 0, 0 };
  6903. return (opnd &&
  6904. opnd->GetStackSym() &&
  6905. loop->memOpInfo->inductionVariableChangeInfoMap->ContainsKey(this->globOpt->GetVarSymID(opnd->GetStackSym())) &&
  6906. (((Loop::InductionVariableChangeInfo)
  6907. loop->memOpInfo->inductionVariableChangeInfoMap->
  6908. LookupWithKey(this->globOpt->GetVarSymID(opnd->GetStackSym()), inductionVariableChangeInfo)).unroll != Js::Constants::InvalidLoopUnrollFactor));
  6909. };
  6910. Assert(loop->blockList.HasTwo());
  6911. FOREACH_BLOCK_IN_LOOP(bblock, loop)
  6912. {
  6913. FOREACH_INSTR_IN_BLOCK_EDITING(instr, instrPrev, bblock)
  6914. {
  6915. if (instr->IsLabelInstr() || !instr->IsRealInstr() || instr->m_opcode == Js::OpCode::IncrLoopBodyCount || instr->m_opcode == Js::OpCode::StLoopBodyCount
  6916. || (instr->IsBranchInstr() && instr->AsBranchInstr()->IsUnconditional()))
  6917. {
  6918. continue;
  6919. }
  6920. else
  6921. {
  6922. switch (instr->m_opcode)
  6923. {
  6924. case Js::OpCode::Nop:
  6925. break;
  6926. case Js::OpCode::Ld_I4:
  6927. case Js::OpCode::Add_I4:
  6928. case Js::OpCode::Sub_I4:
  6929. if (!IsInductionVariableUse(instr->GetDst()))
  6930. {
  6931. Assert(instr->GetDst());
  6932. if (instr->GetDst()->GetStackSym()
  6933. && loop->memOpInfo->inductionVariablesUsedAfterLoop->Test(globOpt->GetVarSymID(instr->GetDst()->GetStackSym())))
  6934. {
  6935. // We have use after the loop for a variable defined inside the loop. So the loop can't be removed.
  6936. return false;
  6937. }
  6938. }
  6939. break;
  6940. case Js::OpCode::Decr_A:
  6941. case Js::OpCode::Incr_A:
  6942. if (!IsInductionVariableUse(instr->GetSrc1()))
  6943. {
  6944. return false;
  6945. }
  6946. break;
  6947. default:
  6948. if (instr->IsBranchInstr())
  6949. {
  6950. if (IsInductionVariableUse(instr->GetSrc1()) || IsInductionVariableUse(instr->GetSrc2()))
  6951. {
  6952. break;
  6953. }
  6954. }
  6955. return false;
  6956. }
  6957. }
  6958. }
  6959. NEXT_INSTR_IN_BLOCK_EDITING;
  6960. }NEXT_BLOCK_IN_LIST;
  6961. return true;
  6962. }
  6963. return false;
  6964. }
  6965. void
  6966. BackwardPass::RemoveEmptyLoops()
  6967. {
  6968. if (PHASE_OFF(Js::MemOpPhase, this->func))
  6969. {
  6970. return;
  6971. }
  6972. const auto DeleteMemOpInfo = [&](Loop *loop)
  6973. {
  6974. JitArenaAllocator *alloc = this->func->GetTopFunc()->m_fg->alloc;
  6975. if (!loop->memOpInfo)
  6976. {
  6977. return;
  6978. }
  6979. if (loop->memOpInfo->candidates)
  6980. {
  6981. loop->memOpInfo->candidates->Clear();
  6982. JitAdelete(alloc, loop->memOpInfo->candidates);
  6983. }
  6984. if (loop->memOpInfo->inductionVariableChangeInfoMap)
  6985. {
  6986. loop->memOpInfo->inductionVariableChangeInfoMap->Clear();
  6987. JitAdelete(alloc, loop->memOpInfo->inductionVariableChangeInfoMap);
  6988. }
  6989. if (loop->memOpInfo->inductionVariableOpndPerUnrollMap)
  6990. {
  6991. loop->memOpInfo->inductionVariableOpndPerUnrollMap->Clear();
  6992. JitAdelete(alloc, loop->memOpInfo->inductionVariableOpndPerUnrollMap);
  6993. }
  6994. if (loop->memOpInfo->inductionVariablesUsedAfterLoop)
  6995. {
  6996. JitAdelete(this->tempAlloc, loop->memOpInfo->inductionVariablesUsedAfterLoop);
  6997. }
  6998. JitAdelete(alloc, loop->memOpInfo);
  6999. };
  7000. FOREACH_LOOP_IN_FUNC_EDITING(loop, this->func)
  7001. {
  7002. if (IsEmptyLoopAfterMemOp(loop))
  7003. {
  7004. RestoreInductionVariableValuesAfterMemOp(loop);
  7005. RemoveEmptyLoopAfterMemOp(loop);
  7006. }
  7007. // Remove memop info as we don't need them after this point.
  7008. DeleteMemOpInfo(loop);
  7009. } NEXT_LOOP_IN_FUNC_EDITING;
  7010. }
  7011. void
  7012. BackwardPass::RemoveEmptyLoopAfterMemOp(Loop *loop)
  7013. {
  7014. BasicBlock *head = loop->GetHeadBlock();
  7015. BasicBlock *tail = head->next;
  7016. BasicBlock *landingPad = loop->landingPad;
  7017. BasicBlock *outerBlock = nullptr;
  7018. SListBaseCounted<FlowEdge *> *succList = head->GetSuccList();
  7019. Assert(succList->HasTwo());
  7020. // Between the two successors of head, one is tail and the other one is the outerBlock
  7021. SListBaseCounted<FlowEdge *>::Iterator iter(succList);
  7022. iter.Next();
  7023. if (iter.Data()->GetSucc() == tail)
  7024. {
  7025. iter.Next();
  7026. outerBlock = iter.Data()->GetSucc();
  7027. }
  7028. else
  7029. {
  7030. outerBlock = iter.Data()->GetSucc();
  7031. #ifdef DBG
  7032. iter.Next();
  7033. Assert(iter.Data()->GetSucc() == tail);
  7034. #endif
  7035. }
  7036. outerBlock->RemovePred(head, this->func->m_fg);
  7037. landingPad->RemoveSucc(head, this->func->m_fg);
  7038. this->func->m_fg->AddEdge(landingPad, outerBlock);
  7039. this->func->m_fg->RemoveBlock(head, nullptr);
  7040. if (head != tail)
  7041. {
  7042. this->func->m_fg->RemoveBlock(tail, nullptr);
  7043. }
  7044. }
  7045. #if DBG_DUMP
  7046. bool
  7047. BackwardPass::IsTraceEnabled() const
  7048. {
  7049. return
  7050. Js::Configuration::Global.flags.Trace.IsEnabled(tag, this->func->GetSourceContextId(), this->func->GetLocalFunctionId()) &&
  7051. (PHASE_TRACE(Js::SimpleJitPhase, func) || !func->IsSimpleJit());
  7052. }
  7053. #endif