BackwardPass.cpp 308 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890
  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. // Prefer to restore from type-specialized versions of the sym, as that will reduce the need for potentially
  1585. // expensive ToVars that can more easily be eliminated due to being dead stores
  1586. StackSym * int32StackSym = nullptr;
  1587. StackSym * float64StackSym = nullptr;
  1588. StackSym * simd128StackSym = nullptr;
  1589. // If the sym is type specialized, we need to check for upward exposed uses of the specialized sym and not the equivalent var sym. If there are no
  1590. // uses and we use the copy prop sym to restore, we'll need to find the type specialize sym for that sym as well.
  1591. StackSym * typeSpecSym = nullptr;
  1592. auto findTypeSpecSym = [&]()
  1593. {
  1594. if (bailOutInfo->liveLosslessInt32Syms->Test(symId))
  1595. {
  1596. // Var version of the sym is not live, use the int32 version
  1597. int32StackSym = stackSym->GetInt32EquivSym(nullptr);
  1598. typeSpecSym = int32StackSym;
  1599. Assert(int32StackSym);
  1600. }
  1601. else if(bailOutInfo->liveFloat64Syms->Test(symId))
  1602. {
  1603. // Var/int32 version of the sym is not live, use the float64 version
  1604. float64StackSym = stackSym->GetFloat64EquivSym(nullptr);
  1605. typeSpecSym = float64StackSym;
  1606. Assert(float64StackSym);
  1607. }
  1608. #ifdef ENABLE_SIMDJS
  1609. // SIMD_JS
  1610. else if (bailOutInfo->liveSimd128F4Syms->Test(symId))
  1611. {
  1612. simd128StackSym = stackSym->GetSimd128F4EquivSym(nullptr);
  1613. typeSpecSym = simd128StackSym;
  1614. }
  1615. else if (bailOutInfo->liveSimd128I4Syms->Test(symId))
  1616. {
  1617. simd128StackSym = stackSym->GetSimd128I4EquivSym(nullptr);
  1618. typeSpecSym = simd128StackSym;
  1619. }
  1620. #endif
  1621. else
  1622. {
  1623. Assert(bailOutInfo->liveVarSyms->Test(symId));
  1624. typeSpecSym = stackSym;
  1625. }
  1626. };
  1627. findTypeSpecSym();
  1628. Assert(typeSpecSym != nullptr);
  1629. IR::Instr *const instr = bailOutInfo->bailOutInstr;
  1630. StackSym *const dstSym = IR::RegOpnd::TryGetStackSym(instr->GetDst());
  1631. if(instr->GetBailOutKind() & IR::BailOutOnResultConditions &&
  1632. instr->GetByteCodeOffset() != Js::Constants::NoByteCodeOffset &&
  1633. bailOutInfo->bailOutOffset <= instr->GetByteCodeOffset() &&
  1634. dstSym &&
  1635. dstSym->IsInt32() &&
  1636. dstSym->IsTypeSpec() &&
  1637. dstSym->GetVarEquivSym(nullptr) == copyPropSyms.Value() &&
  1638. instr->GetSrc1() &&
  1639. !instr->GetDst()->IsEqual(instr->GetSrc1()) &&
  1640. !(instr->GetSrc2() && instr->GetDst()->IsEqual(instr->GetSrc2())))
  1641. {
  1642. Assert(bailOutInfo->bailOutOffset == instr->GetByteCodeOffset());
  1643. // Need to use the original sym to restore. The original sym is byte-code upwards-exposed, which is why it needs
  1644. // to be restored. Because the original sym needs to be restored and the copy-prop sym is changing here, the
  1645. // original sym must be live in some fashion at the point of this instruction, that will be verified below. The
  1646. // original sym will also be made upwards-exposed from here, so the aforementioned transferring store of the
  1647. // copy-prop sym to the original sym will not be a dead store.
  1648. }
  1649. else if (block->upwardExposedUses->Test(typeSpecSym->m_id) && !block->upwardExposedUses->Test(copyPropSyms.Value()->m_id))
  1650. {
  1651. // Don't use the copy prop sym if it is not used and the orig sym still has uses.
  1652. // No point in extending the lifetime of the copy prop sym unnecessarily.
  1653. }
  1654. else
  1655. {
  1656. // Need to use the copy-prop sym to restore
  1657. stackSym = copyPropSyms.Value();
  1658. symId = stackSym->m_id;
  1659. int32StackSym = nullptr;
  1660. float64StackSym = nullptr;
  1661. simd128StackSym = nullptr;
  1662. findTypeSpecSym();
  1663. }
  1664. // 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.
  1665. if (stackSym != copyPropSyms.Value() && stackSym->HasArgSlotNum())
  1666. {
  1667. bailoutReferencedArgSymsBv->Set(stackSym->m_id);
  1668. }
  1669. if (int32StackSym != nullptr)
  1670. {
  1671. Assert(float64StackSym == nullptr);
  1672. usedCopyPropSyms->PrependNode(allocator, copyPropSyms.Key(), int32StackSym);
  1673. iter.RemoveCurrent(allocator);
  1674. upwardExposedUses->Set(int32StackSym->m_id);
  1675. }
  1676. else if (float64StackSym != nullptr)
  1677. {
  1678. // This float-specialized sym is going to be used to restore the corresponding byte-code register. Need to
  1679. // ensure that the float value can be precisely coerced back to the original Var value by requiring that it is
  1680. // specialized using BailOutNumberOnly.
  1681. float64StackSym->m_requiresBailOnNotNumber = true;
  1682. usedCopyPropSyms->PrependNode(allocator, copyPropSyms.Key(), float64StackSym);
  1683. iter.RemoveCurrent(allocator);
  1684. upwardExposedUses->Set(float64StackSym->m_id);
  1685. }
  1686. // SIMD_JS
  1687. else if (simd128StackSym != nullptr)
  1688. {
  1689. usedCopyPropSyms->PrependNode(allocator, copyPropSyms.Key(), simd128StackSym);
  1690. iter.RemoveCurrent(allocator);
  1691. upwardExposedUses->Set(simd128StackSym->m_id);
  1692. }
  1693. else
  1694. {
  1695. usedCopyPropSyms->PrependNode(allocator, copyPropSyms.Key(), stackSym);
  1696. iter.RemoveCurrent(allocator);
  1697. upwardExposedUses->Set(symId);
  1698. }
  1699. }
  1700. else if (!this->IsPrePass())
  1701. {
  1702. // Copy prop sym doesn't need to be restored, delete.
  1703. iter.RemoveCurrent(allocator);
  1704. }
  1705. }
  1706. NEXT_SLISTBASE_ENTRY_EDITING;
  1707. }
  1708. bool
  1709. BackwardPass::ProcessBailOutInfo(IR::Instr * instr)
  1710. {
  1711. if (this->tag == Js::BackwardPhase)
  1712. {
  1713. // We don't need to fill in the bailout instruction in backward pass
  1714. Assert(this->func->hasBailout || !instr->HasBailOutInfo());
  1715. Assert(!instr->HasBailOutInfo() || instr->GetBailOutInfo()->byteCodeUpwardExposedUsed == nullptr || (this->func->HasTry() && this->func->DoOptimizeTry()));
  1716. if (instr->IsByteCodeUsesInstr())
  1717. {
  1718. // FGPeeps inserts bytecodeuses instrs with srcs. We need to look at them to set the proper
  1719. // UpwardExposedUsed info and keep the defs alive.
  1720. // The inliner inserts bytecodeuses instrs withs dsts, but we don't want to look at them for upwardExposedUsed
  1721. // as it would cause real defs to look dead. We use these for bytecodeUpwardExposedUsed info only, which is needed
  1722. // in the dead-store pass only.
  1723. //
  1724. // Handle the source side.
  1725. IR::ByteCodeUsesInstr *byteCodeUsesInstr = instr->AsByteCodeUsesInstr();
  1726. const BVSparse<JitArenaAllocator> * byteCodeUpwardExposedUsed = byteCodeUsesInstr->GetByteCodeUpwardExposedUsed();
  1727. if (byteCodeUpwardExposedUsed != nullptr)
  1728. {
  1729. this->currentBlock->upwardExposedUses->Or(byteCodeUpwardExposedUsed);
  1730. }
  1731. return true;
  1732. }
  1733. return false;
  1734. }
  1735. if (instr->IsByteCodeUsesInstr())
  1736. {
  1737. Assert(instr->m_opcode == Js::OpCode::ByteCodeUses);
  1738. #if DBG
  1739. if (this->DoMarkTempObjectVerify() && (this->currentBlock->isDead || !this->func->hasBailout))
  1740. {
  1741. if (IsCollectionPass())
  1742. {
  1743. if (!this->func->hasBailout)
  1744. {
  1745. // Prevent byte code uses from being remove on collection pass for mark temp object verify
  1746. // if we don't have any bailout
  1747. return true;
  1748. }
  1749. }
  1750. else
  1751. {
  1752. this->currentBlock->tempObjectVerifyTracker->NotifyDeadByteCodeUses(instr);
  1753. }
  1754. }
  1755. #endif
  1756. if (this->func->hasBailout)
  1757. {
  1758. Assert(this->DoByteCodeUpwardExposedUsed());
  1759. // Just collect the byte code uses, and remove the instruction
  1760. // We are going backward, process the dst first and then the src
  1761. IR::Opnd * dst = instr->GetDst();
  1762. if (dst)
  1763. {
  1764. IR::RegOpnd * dstRegOpnd = dst->AsRegOpnd();
  1765. StackSym * dstStackSym = dstRegOpnd->m_sym->AsStackSym();
  1766. Assert(!dstRegOpnd->GetIsJITOptimizedReg());
  1767. Assert(dstStackSym->GetByteCodeRegSlot() != Js::Constants::NoRegister);
  1768. if (dstStackSym->GetType() != TyVar)
  1769. {
  1770. dstStackSym = dstStackSym->GetVarEquivSym(nullptr);
  1771. }
  1772. // If the current region is a Try, symbols in its write-through set shouldn't be cleared.
  1773. // Otherwise, symbols in the write-through set of the first try ancestor shouldn't be cleared.
  1774. if (!this->currentRegion ||
  1775. !this->CheckWriteThroughSymInRegion(this->currentRegion, dstStackSym))
  1776. {
  1777. this->currentBlock->byteCodeUpwardExposedUsed->Clear(dstStackSym->m_id);
  1778. #if DBG
  1779. // We can only track first level function stack syms right now
  1780. if (dstStackSym->GetByteCodeFunc() == this->func)
  1781. {
  1782. this->currentBlock->byteCodeRestoreSyms[dstStackSym->GetByteCodeRegSlot()] = nullptr;
  1783. }
  1784. #endif
  1785. }
  1786. }
  1787. IR::ByteCodeUsesInstr *byteCodeUsesInstr = instr->AsByteCodeUsesInstr();
  1788. if (byteCodeUsesInstr->GetByteCodeUpwardExposedUsed() != nullptr)
  1789. {
  1790. this->currentBlock->byteCodeUpwardExposedUsed->Or(byteCodeUsesInstr->GetByteCodeUpwardExposedUsed());
  1791. #if DBG
  1792. FOREACH_BITSET_IN_SPARSEBV(symId, byteCodeUsesInstr->GetByteCodeUpwardExposedUsed())
  1793. {
  1794. StackSym * stackSym = this->func->m_symTable->FindStackSym(symId);
  1795. Assert(!stackSym->IsTypeSpec());
  1796. // We can only track first level function stack syms right now
  1797. if (stackSym->GetByteCodeFunc() == this->func)
  1798. {
  1799. Js::RegSlot byteCodeRegSlot = stackSym->GetByteCodeRegSlot();
  1800. Assert(byteCodeRegSlot != Js::Constants::NoRegister);
  1801. if (this->currentBlock->byteCodeRestoreSyms[byteCodeRegSlot] != stackSym)
  1802. {
  1803. AssertMsg(this->currentBlock->byteCodeRestoreSyms[byteCodeRegSlot] == nullptr,
  1804. "Can't have two active lifetime for the same byte code register");
  1805. this->currentBlock->byteCodeRestoreSyms[byteCodeRegSlot] = stackSym;
  1806. }
  1807. }
  1808. }
  1809. NEXT_BITSET_IN_SPARSEBV;
  1810. #endif
  1811. }
  1812. if(IsCollectionPass())
  1813. {
  1814. return true;
  1815. }
  1816. ProcessPendingPreOpBailOutInfo(instr);
  1817. PropertySym *propertySymUse = byteCodeUsesInstr->propertySymUse;
  1818. if (propertySymUse && !this->currentBlock->isDead)
  1819. {
  1820. this->currentBlock->upwardExposedFields->Set(propertySymUse->m_id);
  1821. }
  1822. if (this->IsPrePass())
  1823. {
  1824. // Don't remove the instruction yet if we are in the prepass
  1825. // But tell the caller we don't need to process the instruction any more
  1826. return true;
  1827. }
  1828. }
  1829. this->currentBlock->RemoveInstr(instr);
  1830. return true;
  1831. }
  1832. if(IsCollectionPass())
  1833. {
  1834. return false;
  1835. }
  1836. if (instr->HasBailOutInfo())
  1837. {
  1838. Assert(this->func->hasBailout);
  1839. Assert(this->DoByteCodeUpwardExposedUsed());
  1840. BailOutInfo * bailOutInfo = instr->GetBailOutInfo();
  1841. // Only process the bailout info if this is the main bailout point (instead of shared)
  1842. if (bailOutInfo->bailOutInstr == instr)
  1843. {
  1844. if(instr->GetByteCodeOffset() == Js::Constants::NoByteCodeOffset ||
  1845. bailOutInfo->bailOutOffset > instr->GetByteCodeOffset())
  1846. {
  1847. // Currently, we only have post-op bailout with BailOutOnImplicitCalls
  1848. // or JIT inserted operation (which no byte code offsets).
  1849. // If there are other bailouts that we want to bailout after the operation,
  1850. // we have to make sure that it still doesn't do the implicit call
  1851. // if it is done on the stack object.
  1852. // Otherwise, the stack object will be passed to the implicit call functions.
  1853. Assert(instr->GetByteCodeOffset() == Js::Constants::NoByteCodeOffset
  1854. || (instr->GetBailOutKind() & ~IR::BailOutKindBits) == IR::BailOutOnImplicitCalls
  1855. || (instr->GetBailOutKind() & ~IR::BailOutKindBits) == IR::BailOutInvalid);
  1856. // This instruction bails out to a later byte-code instruction, so process the bailout info now
  1857. ProcessBailOutInfo(instr, bailOutInfo);
  1858. }
  1859. else
  1860. {
  1861. // This instruction bails out to the equivalent byte code instruction. This instruction and ByteCodeUses
  1862. // instructions relevant to this instruction need to be processed before the bailout info for this instruction
  1863. // can be processed, so that it can be determined what byte code registers are used by the equivalent byte code
  1864. // instruction and need to be restored. Save the instruction for bailout info processing later.
  1865. Assert(bailOutInfo->bailOutOffset == instr->GetByteCodeOffset());
  1866. Assert(!preOpBailOutInstrToProcess);
  1867. preOpBailOutInstrToProcess = instr;
  1868. }
  1869. }
  1870. }
  1871. return false;
  1872. }
  1873. bool
  1874. BackwardPass::IsImplicitCallBailOutCurrentlyNeeded(IR::Instr * instr, bool mayNeedImplicitCallBailOut, bool hasLiveFields)
  1875. {
  1876. return this->globOpt->IsImplicitCallBailOutCurrentlyNeeded(instr, nullptr, nullptr, this->currentBlock, hasLiveFields, mayNeedImplicitCallBailOut, false) ||
  1877. this->NeedBailOutOnImplicitCallsForTypedArrayStore(instr);
  1878. }
  1879. void
  1880. BackwardPass::DeadStoreTypeCheckBailOut(IR::Instr * instr)
  1881. {
  1882. // Good news: There are cases where the forward pass installs BailOutFailedTypeCheck, but the dead store pass
  1883. // discovers that the checked type is dead.
  1884. // Bad news: We may still need implicit call bailout, and it's up to the dead store pass to figure this out.
  1885. // Worse news: BailOutFailedTypeCheck is pre-op, and BailOutOnImplicitCall is post-op. We'll use a special
  1886. // bailout kind to indicate implicit call bailout that targets its own instruction. The lowerer will emit
  1887. // code to disable/re-enable implicit calls around the operation.
  1888. Assert(this->tag == Js::DeadStorePhase);
  1889. if (this->IsPrePass() || !instr->HasBailOutInfo())
  1890. {
  1891. return;
  1892. }
  1893. IR::BailOutKind oldBailOutKind = instr->GetBailOutKind();
  1894. if (!IR::IsTypeCheckBailOutKind(oldBailOutKind))
  1895. {
  1896. return;
  1897. }
  1898. // Either src1 or dst must be a property sym operand
  1899. Assert((instr->GetSrc1() && instr->GetSrc1()->IsSymOpnd() && instr->GetSrc1()->AsSymOpnd()->IsPropertySymOpnd()) ||
  1900. (instr->GetDst() && instr->GetDst()->IsSymOpnd() && instr->GetDst()->AsSymOpnd()->IsPropertySymOpnd()));
  1901. IR::PropertySymOpnd *propertySymOpnd =
  1902. (instr->GetDst() && instr->GetDst()->IsSymOpnd()) ? instr->GetDst()->AsPropertySymOpnd() : instr->GetSrc1()->AsPropertySymOpnd();
  1903. bool isTypeCheckProtected = false;
  1904. IR::BailOutKind bailOutKind;
  1905. if (GlobOpt::NeedsTypeCheckBailOut(instr, propertySymOpnd, propertySymOpnd == instr->GetDst(), &isTypeCheckProtected, &bailOutKind))
  1906. {
  1907. // If we installed a failed type check bailout in the forward pass, but we are now discovering that the checked
  1908. // type is dead, we may still need a bailout on failed fixed field type check. These type checks are required
  1909. // regardless of whether the checked type is dead. Hence, the bailout kind may change here.
  1910. Assert((oldBailOutKind & ~IR::BailOutKindBits) == bailOutKind ||
  1911. bailOutKind == IR::BailOutFailedFixedFieldTypeCheck || bailOutKind == IR::BailOutFailedEquivalentFixedFieldTypeCheck);
  1912. instr->SetBailOutKind(bailOutKind);
  1913. return;
  1914. }
  1915. else if (isTypeCheckProtected)
  1916. {
  1917. instr->ClearBailOutInfo();
  1918. if (preOpBailOutInstrToProcess == instr)
  1919. {
  1920. preOpBailOutInstrToProcess = nullptr;
  1921. }
  1922. return;
  1923. }
  1924. Assert(!propertySymOpnd->IsTypeCheckProtected());
  1925. // 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
  1926. // 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
  1927. // a NOP and remove the bailout.
  1928. if (instr->m_opcode == Js::OpCode::CheckObjType)
  1929. {
  1930. Assert(instr->GetDst() == nullptr && instr->GetSrc1() != nullptr && instr->GetSrc2() == nullptr);
  1931. instr->m_opcode = Js::OpCode::Nop;
  1932. instr->FreeSrc1();
  1933. instr->ClearBailOutInfo();
  1934. if (this->preOpBailOutInstrToProcess == instr)
  1935. {
  1936. this->preOpBailOutInstrToProcess = nullptr;
  1937. }
  1938. return;
  1939. }
  1940. // We don't need BailOutFailedTypeCheck but may need BailOutOnImplicitCall.
  1941. // Consider: are we in the loop landing pad? If so, no bailout, since implicit calls will be checked at
  1942. // the end of the block.
  1943. if (this->currentBlock->IsLandingPad())
  1944. {
  1945. // We're in the landing pad.
  1946. if (preOpBailOutInstrToProcess == instr)
  1947. {
  1948. preOpBailOutInstrToProcess = nullptr;
  1949. }
  1950. instr->UnlinkBailOutInfo();
  1951. return;
  1952. }
  1953. // If bailOutKind is equivTypeCheck then leave alone the bailout
  1954. if (bailOutKind == IR::BailOutFailedEquivalentTypeCheck ||
  1955. bailOutKind == IR::BailOutFailedEquivalentFixedFieldTypeCheck)
  1956. {
  1957. return;
  1958. }
  1959. // We're not checking for polymorphism, so don't let the bailout indicate that we
  1960. // detected polymorphism.
  1961. instr->GetBailOutInfo()->polymorphicCacheIndex = (uint)-1;
  1962. // Keep the mark temp object bit if it is there so that we will not remove the implicit call check
  1963. instr->SetBailOutKind(IR::BailOutOnImplicitCallsPreOp | (oldBailOutKind & IR::BailOutMarkTempObject));
  1964. }
  1965. void
  1966. BackwardPass::DeadStoreImplicitCallBailOut(IR::Instr * instr, bool hasLiveFields)
  1967. {
  1968. Assert(this->tag == Js::DeadStorePhase);
  1969. if (this->IsPrePass() || !instr->HasBailOutInfo())
  1970. {
  1971. // Don't do this in the pre-pass, because, for instance, we don't have live-on-back-edge fields yet.
  1972. return;
  1973. }
  1974. if (OpCodeAttr::BailOutRec(instr->m_opcode))
  1975. {
  1976. // This is something like OpCode::BailOutOnNotEqual. Assume it needs what it's got.
  1977. return;
  1978. }
  1979. UpdateArrayBailOutKind(instr);
  1980. // Install the implicit call PreOp for mark temp object if we need one.
  1981. IR::BailOutKind kind = instr->GetBailOutKind();
  1982. IR::BailOutKind kindNoBits = kind & ~IR::BailOutKindBits;
  1983. if ((kind & IR::BailOutMarkTempObject) != 0 && kindNoBits != IR::BailOutOnImplicitCallsPreOp)
  1984. {
  1985. Assert(kindNoBits != IR::BailOutOnImplicitCalls);
  1986. if (kindNoBits == IR::BailOutInvalid)
  1987. {
  1988. // We should only have combined with array bits
  1989. Assert((kind & ~IR::BailOutForArrayBits) == IR::BailOutMarkTempObject);
  1990. // Don't need to install if we are not going to do helper calls,
  1991. // or we are in the landingPad since implicit calls are already turned off.
  1992. if ((kind & IR::BailOutOnArrayAccessHelperCall) == 0 && !this->currentBlock->IsLandingPad())
  1993. {
  1994. kind += IR::BailOutOnImplicitCallsPreOp;
  1995. instr->SetBailOutKind(kind);
  1996. }
  1997. }
  1998. }
  1999. // Currently only try to eliminate these bailout kinds. The others are required in cases
  2000. // where we don't necessarily have live/hoisted fields.
  2001. const bool mayNeedBailOnImplicitCall = BailOutInfo::IsBailOutOnImplicitCalls(kind);
  2002. if (!mayNeedBailOnImplicitCall)
  2003. {
  2004. if (kind & IR::BailOutMarkTempObject)
  2005. {
  2006. if (kind == IR::BailOutMarkTempObject)
  2007. {
  2008. // Landing pad does not need per-instr implicit call bailouts.
  2009. Assert(this->currentBlock->IsLandingPad());
  2010. instr->ClearBailOutInfo();
  2011. if (this->preOpBailOutInstrToProcess == instr)
  2012. {
  2013. this->preOpBailOutInstrToProcess = nullptr;
  2014. }
  2015. }
  2016. else
  2017. {
  2018. // Mark temp object bit is not needed after dead store pass
  2019. instr->SetBailOutKind(kind & ~IR::BailOutMarkTempObject);
  2020. }
  2021. }
  2022. return;
  2023. }
  2024. // We have an implicit call bailout in the code, and we want to make sure that it's required.
  2025. // Do this now, because only in the dead store pass do we have complete forward and backward liveness info.
  2026. bool needsBailOutOnImplicitCall = this->IsImplicitCallBailOutCurrentlyNeeded(instr, mayNeedBailOnImplicitCall, hasLiveFields);
  2027. if(!UpdateImplicitCallBailOutKind(instr, needsBailOutOnImplicitCall))
  2028. {
  2029. instr->ClearBailOutInfo();
  2030. if (preOpBailOutInstrToProcess == instr)
  2031. {
  2032. preOpBailOutInstrToProcess = nullptr;
  2033. }
  2034. #if DBG
  2035. if (this->DoMarkTempObjectVerify())
  2036. {
  2037. this->currentBlock->tempObjectVerifyTracker->NotifyBailOutRemoval(instr, this);
  2038. }
  2039. #endif
  2040. }
  2041. }
  2042. bool
  2043. BackwardPass::NeedBailOutOnImplicitCallsForTypedArrayStore(IR::Instr* instr)
  2044. {
  2045. if ((instr->m_opcode == Js::OpCode::StElemI_A || instr->m_opcode == Js::OpCode::StElemI_A_Strict) &&
  2046. instr->GetDst()->IsIndirOpnd() &&
  2047. instr->GetDst()->AsIndirOpnd()->GetBaseOpnd()->GetValueType().IsLikelyTypedArray())
  2048. {
  2049. IR::Opnd * opnd = instr->GetSrc1();
  2050. if (opnd->IsRegOpnd())
  2051. {
  2052. return !opnd->AsRegOpnd()->GetValueType().IsPrimitive() &&
  2053. !opnd->AsRegOpnd()->m_sym->IsInt32() &&
  2054. !opnd->AsRegOpnd()->m_sym->IsFloat64() &&
  2055. !opnd->AsRegOpnd()->m_sym->IsFloatConst() &&
  2056. !opnd->AsRegOpnd()->m_sym->IsIntConst();
  2057. }
  2058. else
  2059. {
  2060. Assert(opnd->IsIntConstOpnd() || opnd->IsInt64ConstOpnd() || opnd->IsFloat32ConstOpnd() || opnd->IsFloatConstOpnd() || opnd->IsAddrOpnd());
  2061. }
  2062. }
  2063. return false;
  2064. }
  2065. void
  2066. BackwardPass::ProcessPendingPreOpBailOutInfo(IR::Instr *const currentInstr)
  2067. {
  2068. Assert(!IsCollectionPass());
  2069. if(!preOpBailOutInstrToProcess)
  2070. {
  2071. return;
  2072. }
  2073. IR::Instr *const prevInstr = currentInstr->m_prev;
  2074. if(prevInstr &&
  2075. prevInstr->IsByteCodeUsesInstr() &&
  2076. prevInstr->AsByteCodeUsesInstr()->GetByteCodeOffset() == preOpBailOutInstrToProcess->GetByteCodeOffset())
  2077. {
  2078. return;
  2079. }
  2080. // A pre-op bailout instruction was saved for bailout info processing after the instruction and relevant ByteCodeUses
  2081. // instructions before it have been processed. We can process the bailout info for that instruction now.
  2082. BailOutInfo *const bailOutInfo = preOpBailOutInstrToProcess->GetBailOutInfo();
  2083. Assert(bailOutInfo->bailOutInstr == preOpBailOutInstrToProcess);
  2084. Assert(bailOutInfo->bailOutOffset == preOpBailOutInstrToProcess->GetByteCodeOffset());
  2085. ProcessBailOutInfo(preOpBailOutInstrToProcess, bailOutInfo);
  2086. preOpBailOutInstrToProcess = nullptr;
  2087. }
  2088. void
  2089. BackwardPass::ProcessBailOutInfo(IR::Instr * instr, BailOutInfo * bailOutInfo)
  2090. {
  2091. /*
  2092. When we optimize functions having try-catch, we install a bailout at the starting of the catch block, namely, BailOnException.
  2093. 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
  2094. not try to restore from the constant values or copy-prop syms or the type specialized syms, as these may not necessarily be/have
  2095. the right values. For example,
  2096. //constant values
  2097. c =
  2098. try
  2099. {
  2100. <exception>
  2101. c = k (constant)
  2102. }
  2103. catch
  2104. {
  2105. BailOnException
  2106. = c <-- We need to restore c from the value outside the try.
  2107. }
  2108. //copy-prop syms
  2109. c =
  2110. try
  2111. {
  2112. b = a
  2113. <exception>
  2114. c = b
  2115. }
  2116. catch
  2117. {
  2118. BailOnException
  2119. = c <-- We really want to restore c from its original sym, and not from its copy-prop sym, a
  2120. }
  2121. //type specialized syms
  2122. a =
  2123. try
  2124. {
  2125. <exception>
  2126. a++ <-- type specializes a
  2127. }
  2128. catch
  2129. {
  2130. BailOnException
  2131. = a <-- We need to restore a from its var version.
  2132. }
  2133. */
  2134. BasicBlock * block = this->currentBlock;
  2135. BVSparse<JitArenaAllocator> * byteCodeUpwardExposedUsed = block->byteCodeUpwardExposedUsed;
  2136. Assert(bailOutInfo->bailOutInstr == instr);
  2137. // The byteCodeUpwardExposedUsed should only be assigned once. The only case which would break this
  2138. // assumption is when we are optimizing a function having try-catch. In that case, we need the
  2139. // byteCodeUpwardExposedUsed analysis in the initial backward pass too.
  2140. Assert(bailOutInfo->byteCodeUpwardExposedUsed == nullptr || (this->func->HasTry() && this->func->DoOptimizeTry()));
  2141. // Make a copy of the byteCodeUpwardExposedUsed so we can remove the constants
  2142. if (!this->IsPrePass())
  2143. {
  2144. // Create the BV of symbols that need to be restored in the BailOutRecord
  2145. byteCodeUpwardExposedUsed = byteCodeUpwardExposedUsed->CopyNew(this->func->m_alloc);
  2146. bailOutInfo->byteCodeUpwardExposedUsed = byteCodeUpwardExposedUsed;
  2147. }
  2148. else
  2149. {
  2150. // Create a temporary byteCodeUpwardExposedUsed
  2151. byteCodeUpwardExposedUsed = byteCodeUpwardExposedUsed->CopyNew(this->tempAlloc);
  2152. }
  2153. // All the register-based argument syms need to be tracked. They are either:
  2154. // 1. Referenced as constants in bailOutInfo->usedcapturedValues.constantValues
  2155. // 2. Referenced using copy prop syms in bailOutInfo->usedcapturedValues.copyPropSyms
  2156. // 3. Marked as m_isBailOutReferenced = true & added to upwardExposedUsed bit vector to ensure we do not dead store their defs.
  2157. // The third set of syms is represented by the bailoutReferencedArgSymsBv.
  2158. BVSparse<JitArenaAllocator>* bailoutReferencedArgSymsBv = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  2159. if (!this->IsPrePass())
  2160. {
  2161. bailOutInfo->IterateArgOutSyms([=](uint, uint, StackSym* sym) {
  2162. if (!sym->IsArgSlotSym())
  2163. {
  2164. bailoutReferencedArgSymsBv->Set(sym->m_id);
  2165. }
  2166. });
  2167. }
  2168. // Process Argument object first, as they can be found on the stack and don't need to rely on copy prop
  2169. this->ProcessBailOutArgObj(bailOutInfo, byteCodeUpwardExposedUsed);
  2170. if (instr->m_opcode != Js::OpCode::BailOnException) // see comment at the beginning of this function
  2171. {
  2172. this->ProcessBailOutConstants(bailOutInfo, byteCodeUpwardExposedUsed, bailoutReferencedArgSymsBv);
  2173. this->ProcessBailOutCopyProps(bailOutInfo, byteCodeUpwardExposedUsed, bailoutReferencedArgSymsBv);
  2174. }
  2175. BVSparse<JitArenaAllocator> * tempBv = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  2176. if (bailOutInfo->liveVarSyms)
  2177. {
  2178. // Prefer to restore from type-specialized versions of the sym, as that will reduce the need for potentially expensive
  2179. // ToVars that can more easily be eliminated due to being dead stores.
  2180. #if DBG
  2181. #ifdef ENABLE_SIMDJS
  2182. // SIMD_JS
  2183. // Simd128 syms should be live in at most one form
  2184. tempBv->And(bailOutInfo->liveSimd128F4Syms, bailOutInfo->liveSimd128I4Syms);
  2185. #endif
  2186. Assert(tempBv->IsEmpty());
  2187. // Verify that all syms to restore are live in some fashion
  2188. tempBv->Minus(byteCodeUpwardExposedUsed, bailOutInfo->liveVarSyms);
  2189. tempBv->Minus(bailOutInfo->liveLosslessInt32Syms);
  2190. tempBv->Minus(bailOutInfo->liveFloat64Syms);
  2191. #ifdef ENABLE_SIMDJS
  2192. tempBv->Minus(bailOutInfo->liveSimd128F4Syms);
  2193. tempBv->Minus(bailOutInfo->liveSimd128I4Syms);
  2194. #endif
  2195. Assert(tempBv->IsEmpty());
  2196. #endif
  2197. if (this->func->IsJitInDebugMode())
  2198. {
  2199. // Add to byteCodeUpwardExposedUsed the non-temp local vars used so far to restore during bail out.
  2200. // The ones that are not used so far will get their values from bytecode when we continue after bail out in interpreter.
  2201. Assert(this->func->m_nonTempLocalVars);
  2202. tempBv->And(this->func->m_nonTempLocalVars, bailOutInfo->liveVarSyms);
  2203. // Remove syms that are restored in other ways than byteCodeUpwardExposedUsed.
  2204. FOREACH_SLIST_ENTRY(ConstantStackSymValue, value, &bailOutInfo->usedCapturedValues.constantValues)
  2205. {
  2206. Assert(value.Key()->HasByteCodeRegSlot() || value.Key()->GetInstrDef()->m_opcode == Js::OpCode::BytecodeArgOutCapture);
  2207. if (value.Key()->HasByteCodeRegSlot())
  2208. {
  2209. tempBv->Clear(value.Key()->GetByteCodeRegSlot());
  2210. }
  2211. }
  2212. NEXT_SLIST_ENTRY;
  2213. FOREACH_SLIST_ENTRY(CopyPropSyms, value, &bailOutInfo->usedCapturedValues.copyPropSyms)
  2214. {
  2215. Assert(value.Key()->HasByteCodeRegSlot() || value.Key()->GetInstrDef()->m_opcode == Js::OpCode::BytecodeArgOutCapture);
  2216. if (value.Key()->HasByteCodeRegSlot())
  2217. {
  2218. tempBv->Clear(value.Key()->GetByteCodeRegSlot());
  2219. }
  2220. }
  2221. NEXT_SLIST_ENTRY;
  2222. if (bailOutInfo->usedCapturedValues.argObjSyms)
  2223. {
  2224. tempBv->Minus(bailOutInfo->usedCapturedValues.argObjSyms);
  2225. }
  2226. byteCodeUpwardExposedUsed->Or(tempBv);
  2227. }
  2228. if (instr->m_opcode != Js::OpCode::BailOnException) // see comment at the beginning of this function
  2229. {
  2230. // Int32
  2231. tempBv->And(byteCodeUpwardExposedUsed, bailOutInfo->liveLosslessInt32Syms);
  2232. byteCodeUpwardExposedUsed->Minus(tempBv);
  2233. FOREACH_BITSET_IN_SPARSEBV(symId, tempBv)
  2234. {
  2235. StackSym * stackSym = this->func->m_symTable->FindStackSym(symId);
  2236. Assert(stackSym->GetType() == TyVar);
  2237. StackSym * int32StackSym = stackSym->GetInt32EquivSym(nullptr);
  2238. Assert(int32StackSym);
  2239. byteCodeUpwardExposedUsed->Set(int32StackSym->m_id);
  2240. }
  2241. NEXT_BITSET_IN_SPARSEBV;
  2242. // Float64
  2243. tempBv->And(byteCodeUpwardExposedUsed, bailOutInfo->liveFloat64Syms);
  2244. byteCodeUpwardExposedUsed->Minus(tempBv);
  2245. FOREACH_BITSET_IN_SPARSEBV(symId, tempBv)
  2246. {
  2247. StackSym * stackSym = this->func->m_symTable->FindStackSym(symId);
  2248. Assert(stackSym->GetType() == TyVar);
  2249. StackSym * float64StackSym = stackSym->GetFloat64EquivSym(nullptr);
  2250. Assert(float64StackSym);
  2251. byteCodeUpwardExposedUsed->Set(float64StackSym->m_id);
  2252. // This float-specialized sym is going to be used to restore the corresponding byte-code register. Need to
  2253. // ensure that the float value can be precisely coerced back to the original Var value by requiring that it is
  2254. // specialized using BailOutNumberOnly.
  2255. float64StackSym->m_requiresBailOnNotNumber = true;
  2256. }
  2257. NEXT_BITSET_IN_SPARSEBV;
  2258. #ifdef ENABLE_SIMDJS
  2259. // SIMD_JS
  2260. tempBv->Or(bailOutInfo->liveSimd128F4Syms, bailOutInfo->liveSimd128I4Syms);
  2261. tempBv->And(byteCodeUpwardExposedUsed);
  2262. byteCodeUpwardExposedUsed->Minus(tempBv);
  2263. FOREACH_BITSET_IN_SPARSEBV(symId, tempBv)
  2264. {
  2265. StackSym * stackSym = this->func->m_symTable->FindStackSym(symId);
  2266. Assert(stackSym->GetType() == TyVar);
  2267. StackSym * simd128Sym = nullptr;
  2268. if (bailOutInfo->liveSimd128F4Syms->Test(symId))
  2269. {
  2270. simd128Sym = stackSym->GetSimd128F4EquivSym(nullptr);
  2271. }
  2272. else
  2273. {
  2274. Assert(bailOutInfo->liveSimd128I4Syms->Test(symId));
  2275. simd128Sym = stackSym->GetSimd128I4EquivSym(nullptr);
  2276. }
  2277. byteCodeUpwardExposedUsed->Set(simd128Sym->m_id);
  2278. }
  2279. NEXT_BITSET_IN_SPARSEBV;
  2280. #endif
  2281. }
  2282. // Var
  2283. // Any remaining syms to restore will be restored from their var versions
  2284. }
  2285. else
  2286. {
  2287. Assert(!this->func->DoGlobOpt());
  2288. }
  2289. JitAdelete(this->tempAlloc, tempBv);
  2290. // BailOnNoProfile makes some edges dead. Upward exposed symbols info set after the BailOnProfile won't
  2291. // flow through these edges, and, in turn, not through predecessor edges of the block containing the
  2292. // BailOnNoProfile. This is specifically bad for an inlinee's argout syms as they are set as upward exposed
  2293. // when we see the InlineeEnd, but may not look so to some blocks and may get overwritten.
  2294. // Set the argout syms as upward exposed here.
  2295. if (instr->m_opcode == Js::OpCode::BailOnNoProfile && instr->m_func->IsInlinee() &&
  2296. instr->m_func->m_hasInlineArgsOpt && instr->m_func->frameInfo->isRecorded)
  2297. {
  2298. instr->m_func->frameInfo->IterateSyms([=](StackSym* argSym)
  2299. {
  2300. this->currentBlock->upwardExposedUses->Set(argSym->m_id);
  2301. });
  2302. }
  2303. // Mark all the register that we need to restore as used (excluding constants)
  2304. block->upwardExposedUses->Or(byteCodeUpwardExposedUsed);
  2305. block->upwardExposedUses->Or(bailoutReferencedArgSymsBv);
  2306. if (!this->IsPrePass())
  2307. {
  2308. bailOutInfo->IterateArgOutSyms([=](uint index, uint, StackSym* sym) {
  2309. if (sym->IsArgSlotSym() || bailoutReferencedArgSymsBv->Test(sym->m_id))
  2310. {
  2311. bailOutInfo->argOutSyms[index]->m_isBailOutReferenced = true;
  2312. }
  2313. });
  2314. }
  2315. JitAdelete(this->tempAlloc, bailoutReferencedArgSymsBv);
  2316. if (this->IsPrePass())
  2317. {
  2318. JitAdelete(this->tempAlloc, byteCodeUpwardExposedUsed);
  2319. }
  2320. }
  2321. void
  2322. BackwardPass::ProcessBlock(BasicBlock * block)
  2323. {
  2324. this->currentBlock = block;
  2325. this->MergeSuccBlocksInfo(block);
  2326. #if DBG_DUMP
  2327. if (this->IsTraceEnabled())
  2328. {
  2329. Output::Print(_u("******************************* Before Process Block *******************************n"));
  2330. DumpBlockData(block);
  2331. }
  2332. #endif
  2333. FOREACH_INSTR_BACKWARD_IN_BLOCK_EDITING(instr, instrPrev, block)
  2334. {
  2335. #if DBG_DUMP
  2336. if (!IsCollectionPass() && IsTraceEnabled() && Js::Configuration::Global.flags.Verbose)
  2337. {
  2338. Output::Print(_u(">>>>>>>>>>>>>>>>>>>>>> %s: Instr Start\n"), tag == Js::BackwardPhase? _u("BACKWARD") : _u("DEADSTORE"));
  2339. instr->Dump();
  2340. if (block->upwardExposedUses)
  2341. {
  2342. Output::SkipToColumn(10);
  2343. Output::Print(_u(" Exposed Use: "));
  2344. block->upwardExposedUses->Dump();
  2345. }
  2346. if (block->upwardExposedFields)
  2347. {
  2348. Output::SkipToColumn(10);
  2349. Output::Print(_u("Exposed Fields: "));
  2350. block->upwardExposedFields->Dump();
  2351. }
  2352. if (block->byteCodeUpwardExposedUsed)
  2353. {
  2354. Output::SkipToColumn(10);
  2355. Output::Print(_u(" Byte Code Use: "));
  2356. block->byteCodeUpwardExposedUsed->Dump();
  2357. }
  2358. Output::Print(_u("--------------------\n"));
  2359. }
  2360. #endif
  2361. AssertOrFailFastMsg(!instr->IsLowered(), "Lowered instruction detected in pre-lower context!");
  2362. this->currentInstr = instr;
  2363. this->currentRegion = this->currentBlock->GetFirstInstr()->AsLabelInstr()->GetRegion();
  2364. IR::Instr * insertedInstr = TryChangeInstrForStackArgOpt();
  2365. if (insertedInstr != nullptr)
  2366. {
  2367. instrPrev = insertedInstr;
  2368. continue;
  2369. }
  2370. MarkScopeObjSymUseForStackArgOpt();
  2371. ProcessBailOnStackArgsOutOfActualsRange();
  2372. if (ProcessNoImplicitCallUses(instr) || this->ProcessBailOutInfo(instr))
  2373. {
  2374. continue;
  2375. }
  2376. IR::Instr *instrNext = instr->m_next;
  2377. if (this->TrackNoImplicitCallInlinees(instr))
  2378. {
  2379. instrPrev = instrNext->m_prev;
  2380. continue;
  2381. }
  2382. if (CanDeadStoreInstrForScopeObjRemoval() && DeadStoreOrChangeInstrForScopeObjRemoval(&instrPrev))
  2383. {
  2384. continue;
  2385. }
  2386. bool hasLiveFields = (block->upwardExposedFields && !block->upwardExposedFields->IsEmpty());
  2387. IR::Opnd * opnd = instr->GetDst();
  2388. if (opnd != nullptr)
  2389. {
  2390. bool isRemoved = ReverseCopyProp(instr);
  2391. if (isRemoved)
  2392. {
  2393. instrPrev = instrNext->m_prev;
  2394. continue;
  2395. }
  2396. if (instr->m_opcode == Js::OpCode::Conv_Bool)
  2397. {
  2398. isRemoved = this->FoldCmBool(instr);
  2399. if (isRemoved)
  2400. {
  2401. continue;
  2402. }
  2403. }
  2404. ProcessNewScObject(instr);
  2405. this->ProcessTransfers(instr);
  2406. isRemoved = this->ProcessDef(opnd);
  2407. if (isRemoved)
  2408. {
  2409. continue;
  2410. }
  2411. }
  2412. if(!IsCollectionPass())
  2413. {
  2414. this->MarkTempProcessInstr(instr);
  2415. this->ProcessFieldKills(instr);
  2416. if (this->DoDeadStoreSlots()
  2417. && (instr->HasAnyImplicitCalls() || instr->HasBailOutInfo() || instr->UsesAllFields()))
  2418. {
  2419. // Can't dead-store slots if there can be an implicit-call, an exception, or a bailout
  2420. block->slotDeadStoreCandidates->ClearAll();
  2421. }
  2422. if (this->DoFieldHoistCandidates())
  2423. {
  2424. this->ProcessFieldHoistKills(instr);
  2425. }
  2426. TrackIntUsage(instr);
  2427. TrackBitWiseOrNumberOp(instr);
  2428. TrackFloatSymEquivalence(instr);
  2429. }
  2430. opnd = instr->GetSrc1();
  2431. if (opnd != nullptr)
  2432. {
  2433. this->ProcessUse(opnd);
  2434. opnd = instr->GetSrc2();
  2435. if (opnd != nullptr)
  2436. {
  2437. this->ProcessUse(opnd);
  2438. }
  2439. }
  2440. if(IsCollectionPass())
  2441. {
  2442. continue;
  2443. }
  2444. if (this->tag == Js::DeadStorePhase)
  2445. {
  2446. switch(instr->m_opcode)
  2447. {
  2448. case Js::OpCode::LdSlot:
  2449. {
  2450. DeadStoreOrChangeInstrForScopeObjRemoval(&instrPrev);
  2451. break;
  2452. }
  2453. case Js::OpCode::InlineArrayPush:
  2454. case Js::OpCode::InlineArrayPop:
  2455. {
  2456. IR::Opnd *const thisOpnd = instr->GetSrc1();
  2457. if(thisOpnd && thisOpnd->IsRegOpnd())
  2458. {
  2459. IR::RegOpnd *const thisRegOpnd = thisOpnd->AsRegOpnd();
  2460. if(thisRegOpnd->IsArrayRegOpnd())
  2461. {
  2462. // Process the array use at the point of the array built-in call, since the array will actually
  2463. // be used at the call, not at the ArgOut_A_InlineBuiltIn
  2464. ProcessArrayRegOpndUse(instr, thisRegOpnd->AsArrayRegOpnd());
  2465. }
  2466. }
  2467. }
  2468. #if !INT32VAR // the following is not valid on 64-bit platforms
  2469. case Js::OpCode::BoundCheck:
  2470. {
  2471. if(IsPrePass())
  2472. {
  2473. break;
  2474. }
  2475. // Look for:
  2476. // BoundCheck 0 <= s1
  2477. // BoundCheck s1 <= s2 + c, where c == 0 || c == -1
  2478. //
  2479. // And change it to:
  2480. // UnsignedBoundCheck s1 <= s2 + c
  2481. //
  2482. // The BoundCheck instruction is a signed operation, so any unsigned operand used in the instruction must be
  2483. // guaranteed to be >= 0 and <= int32 max when its value is interpreted as signed. Due to the restricted
  2484. // range of s2 above, by using an unsigned comparison instead, the negative check on s1 will also be
  2485. // covered.
  2486. //
  2487. // A BoundCheck instruction takes the form (src1 <= src2 + dst).
  2488. // Check the current instruction's pattern for:
  2489. // BoundCheck s1 <= s2 + c, where c <= 0
  2490. if(!instr->GetSrc1()->IsRegOpnd() ||
  2491. !instr->GetSrc1()->IsInt32() ||
  2492. !instr->GetSrc2() ||
  2493. instr->GetSrc2()->IsIntConstOpnd())
  2494. {
  2495. break;
  2496. }
  2497. if(instr->GetDst())
  2498. {
  2499. const int c = instr->GetDst()->AsIntConstOpnd()->GetValue();
  2500. if(c != 0 && c != -1)
  2501. {
  2502. break;
  2503. }
  2504. }
  2505. // Check the previous instruction's pattern for:
  2506. // BoundCheck 0 <= s1
  2507. IR::Instr *const lowerBoundCheck = instr->m_prev;
  2508. if(lowerBoundCheck->m_opcode != Js::OpCode::BoundCheck ||
  2509. !lowerBoundCheck->GetSrc1()->IsIntConstOpnd() ||
  2510. lowerBoundCheck->GetSrc1()->AsIntConstOpnd()->GetValue() != 0 ||
  2511. !lowerBoundCheck->GetSrc2() ||
  2512. !instr->GetSrc1()->AsRegOpnd()->IsEqual(lowerBoundCheck->GetSrc2()) ||
  2513. lowerBoundCheck->GetDst() && lowerBoundCheck->GetDst()->AsIntConstOpnd()->GetValue() != 0)
  2514. {
  2515. break;
  2516. }
  2517. // Remove the previous lower bound check, and change the current upper bound check to:
  2518. // UnsignedBoundCheck s1 <= s2 + c
  2519. instr->m_opcode = Js::OpCode::UnsignedBoundCheck;
  2520. currentBlock->RemoveInstr(lowerBoundCheck);
  2521. instrPrev = instr->m_prev;
  2522. break;
  2523. }
  2524. #endif
  2525. }
  2526. DeadStoreTypeCheckBailOut(instr);
  2527. DeadStoreImplicitCallBailOut(instr, hasLiveFields);
  2528. if (block->stackSymToFinalType != nullptr)
  2529. {
  2530. this->InsertTypeTransitionsAtPotentialKills();
  2531. }
  2532. // NoImplicitCallUses transfers need to be processed after determining whether implicit calls need to be disabled
  2533. // for the current instruction, because the instruction where the def occurs also needs implicit calls disabled.
  2534. // Array value type for the destination needs to be updated before transfers have been processed by
  2535. // ProcessNoImplicitCallDef, and array value types for sources need to be updated after transfers have been
  2536. // processed by ProcessNoImplicitCallDef, as it requires the no-implicit-call tracking bit-vectors to be precise at
  2537. // the point of the update.
  2538. if(!IsPrePass())
  2539. {
  2540. UpdateArrayValueTypes(instr, instr->GetDst());
  2541. }
  2542. ProcessNoImplicitCallDef(instr);
  2543. if(!IsPrePass())
  2544. {
  2545. UpdateArrayValueTypes(instr, instr->GetSrc1());
  2546. UpdateArrayValueTypes(instr, instr->GetSrc2());
  2547. }
  2548. }
  2549. else
  2550. {
  2551. switch (instr->m_opcode)
  2552. {
  2553. case Js::OpCode::BailOnNoProfile:
  2554. {
  2555. this->ProcessBailOnNoProfile(instr, block);
  2556. // this call could change the last instr of the previous block... Adjust instrStop.
  2557. instrStop = block->GetFirstInstr()->m_prev;
  2558. Assert(this->tag != Js::DeadStorePhase);
  2559. continue;
  2560. }
  2561. case Js::OpCode::Catch:
  2562. {
  2563. if (this->func->DoOptimizeTry() && !this->IsPrePass())
  2564. {
  2565. // Execute the "Catch" in the JIT'ed code, and bailout to the next instruction. This way, the bailout will restore the exception object automatically.
  2566. IR::BailOutInstr* bailOnException = IR::BailOutInstr::New(Js::OpCode::BailOnException, IR::BailOutOnException, instr->m_next, instr->m_func);
  2567. instr->InsertAfter(bailOnException);
  2568. Assert(instr->GetDst()->IsRegOpnd() && instr->GetDst()->GetStackSym()->HasByteCodeRegSlot());
  2569. StackSym * exceptionObjSym = instr->GetDst()->GetStackSym();
  2570. Assert(instr->m_prev->IsLabelInstr() && (instr->m_prev->AsLabelInstr()->GetRegion()->GetType() == RegionTypeCatch));
  2571. instr->m_prev->AsLabelInstr()->GetRegion()->SetExceptionObjectSym(exceptionObjSym);
  2572. }
  2573. break;
  2574. }
  2575. case Js::OpCode::Throw:
  2576. case Js::OpCode::EHThrow:
  2577. case Js::OpCode::InlineThrow:
  2578. this->func->SetHasThrow();
  2579. break;
  2580. }
  2581. }
  2582. if (instr->m_opcode == Js::OpCode::InlineeEnd)
  2583. {
  2584. this->ProcessInlineeEnd(instr);
  2585. }
  2586. if ((instr->IsLabelInstr() && instr->m_next->m_opcode == Js::OpCode::Catch) || (instr->IsLabelInstr() && instr->m_next->m_opcode == Js::OpCode::Finally))
  2587. {
  2588. if (!this->currentRegion)
  2589. {
  2590. Assert(!this->func->DoOptimizeTry() && !(this->func->IsSimpleJit() && this->func->hasBailout));
  2591. }
  2592. else
  2593. {
  2594. Assert(this->currentRegion->GetType() == RegionTypeCatch || this->currentRegion->GetType() == RegionTypeFinally);
  2595. Region * matchingTryRegion = this->currentRegion->GetMatchingTryRegion();
  2596. Assert(matchingTryRegion);
  2597. // We need live-on-back-edge info to accurately set write-through symbols for try-catches in a loop.
  2598. // Don't set write-through symbols in pre-pass
  2599. if (!this->IsPrePass() && !matchingTryRegion->writeThroughSymbolsSet)
  2600. {
  2601. if (this->tag == Js::DeadStorePhase)
  2602. {
  2603. Assert(!this->func->DoGlobOpt());
  2604. }
  2605. // FullJit: Write-through symbols info must be populated in the backward pass as
  2606. // 1. the forward pass needs it to insert ToVars.
  2607. // 2. the deadstore pass needs it to not clear such symbols from the
  2608. // byteCodeUpwardExposedUsed BV upon a def in the try region. This is required
  2609. // because any bailout in the try region needs to restore all write-through
  2610. // symbols.
  2611. // SimpleJit: Won't run the initial backward pass, but write-through symbols info is still
  2612. // needed in the deadstore pass for <2> above.
  2613. this->SetWriteThroughSymbolsSetForRegion(this->currentBlock, matchingTryRegion);
  2614. }
  2615. }
  2616. }
  2617. #if DBG
  2618. if (instr->m_opcode == Js::OpCode::TryCatch)
  2619. {
  2620. if (!this->IsPrePass() && (this->func->DoOptimizeTry() || (this->func->IsSimpleJit() && this->func->hasBailout)))
  2621. {
  2622. Assert(instr->m_next->IsLabelInstr() && (instr->m_next->AsLabelInstr()->GetRegion() != nullptr));
  2623. Region * tryRegion = instr->m_next->AsLabelInstr()->GetRegion();
  2624. Assert(tryRegion && tryRegion->GetType() == RegionType::RegionTypeTry && tryRegion->GetMatchingCatchRegion() != nullptr);
  2625. Assert(tryRegion->writeThroughSymbolsSet);
  2626. }
  2627. }
  2628. #endif
  2629. ProcessPendingPreOpBailOutInfo(instr);
  2630. #if DBG_DUMP
  2631. if (!IsCollectionPass() && IsTraceEnabled() && Js::Configuration::Global.flags.Verbose)
  2632. {
  2633. Output::Print(_u("-------------------\n"));
  2634. instr->Dump();
  2635. if (block->upwardExposedUses)
  2636. {
  2637. Output::SkipToColumn(10);
  2638. Output::Print(_u(" Exposed Use: "));
  2639. block->upwardExposedUses->Dump();
  2640. }
  2641. if (block->upwardExposedFields)
  2642. {
  2643. Output::SkipToColumn(10);
  2644. Output::Print(_u("Exposed Fields: "));
  2645. block->upwardExposedFields->Dump();
  2646. }
  2647. if (block->byteCodeUpwardExposedUsed)
  2648. {
  2649. Output::SkipToColumn(10);
  2650. Output::Print(_u(" Byte Code Use: "));
  2651. block->byteCodeUpwardExposedUsed->Dump();
  2652. }
  2653. Output::Print(_u("<<<<<<<<<<<<<<<<<<<<<< %s: Instr End\n"), tag == Js::BackwardPhase? _u("BACKWARD") : _u("DEADSTORE"));
  2654. }
  2655. #endif
  2656. }
  2657. NEXT_INSTR_BACKWARD_IN_BLOCK_EDITING;
  2658. EndIntOverflowDoesNotMatterRange();
  2659. if (this->DoFieldHoistCandidates() && !block->isDead && block->isLoopHeader)
  2660. {
  2661. Assert(block->loop->fieldHoistCandidates == nullptr);
  2662. block->loop->fieldHoistCandidates = block->fieldHoistCandidates->CopyNew(this->func->m_alloc);
  2663. }
  2664. if (!this->IsPrePass() && !block->isDead && block->isLoopHeader)
  2665. {
  2666. // Copy the upward exposed use as the live on back edge regs
  2667. block->loop->regAlloc.liveOnBackEdgeSyms = block->upwardExposedUses->CopyNew(this->func->m_alloc);
  2668. }
  2669. Assert(!considerSymAsRealUseInNoImplicitCallUses);
  2670. #if DBG_DUMP
  2671. if (this->IsTraceEnabled())
  2672. {
  2673. Output::Print(_u("******************************* After Process Block *******************************n"));
  2674. DumpBlockData(block);
  2675. }
  2676. #endif
  2677. }
  2678. bool
  2679. BackwardPass::CanDeadStoreInstrForScopeObjRemoval(Sym *sym) const
  2680. {
  2681. if (tag == Js::DeadStorePhase && this->currentInstr->m_func->IsStackArgsEnabled())
  2682. {
  2683. Func * currFunc = this->currentInstr->m_func;
  2684. bool doScopeObjCreation = currFunc->GetJITFunctionBody()->GetDoScopeObjectCreation();
  2685. switch (this->currentInstr->m_opcode)
  2686. {
  2687. case Js::OpCode::InitCachedScope:
  2688. {
  2689. if(!doScopeObjCreation && this->currentInstr->GetDst()->IsScopeObjOpnd(currFunc))
  2690. {
  2691. /*
  2692. * We don't really dead store this instruction. We just want the source sym of this instruction
  2693. * to NOT be tracked as USED by this instruction.
  2694. * This instr will effectively be lowered to dest = MOV NULLObject, in the lowerer phase.
  2695. */
  2696. return true;
  2697. }
  2698. break;
  2699. }
  2700. case Js::OpCode::LdSlot:
  2701. {
  2702. if (sym && IsFormalParamSym(currFunc, sym))
  2703. {
  2704. return true;
  2705. }
  2706. break;
  2707. }
  2708. case Js::OpCode::CommitScope:
  2709. case Js::OpCode::GetCachedFunc:
  2710. {
  2711. return !doScopeObjCreation && this->currentInstr->GetSrc1()->IsScopeObjOpnd(currFunc);
  2712. }
  2713. case Js::OpCode::BrFncCachedScopeEq:
  2714. case Js::OpCode::BrFncCachedScopeNeq:
  2715. {
  2716. return !doScopeObjCreation && this->currentInstr->GetSrc2()->IsScopeObjOpnd(currFunc);
  2717. }
  2718. case Js::OpCode::CallHelper:
  2719. {
  2720. if (!doScopeObjCreation && this->currentInstr->GetSrc1()->AsHelperCallOpnd()->m_fnHelper == IR::JnHelperMethod::HelperOP_InitCachedFuncs)
  2721. {
  2722. IR::RegOpnd * scopeObjOpnd = this->currentInstr->GetSrc2()->GetStackSym()->GetInstrDef()->GetSrc1()->AsRegOpnd();
  2723. return scopeObjOpnd->IsScopeObjOpnd(currFunc);
  2724. }
  2725. break;
  2726. }
  2727. }
  2728. }
  2729. return false;
  2730. }
  2731. /*
  2732. * This is for Eliminating Scope Object Creation during Heap arguments optimization.
  2733. */
  2734. bool
  2735. BackwardPass::DeadStoreOrChangeInstrForScopeObjRemoval(IR::Instr ** pInstrPrev)
  2736. {
  2737. IR::Instr * instr = this->currentInstr;
  2738. Func * currFunc = instr->m_func;
  2739. if (this->tag == Js::DeadStorePhase && instr->m_func->IsStackArgsEnabled() && !IsPrePass())
  2740. {
  2741. switch (instr->m_opcode)
  2742. {
  2743. /*
  2744. * This LdSlot loads the formal from the formals array. We replace this a Ld_A <ArgInSym>.
  2745. * ArgInSym is inserted at the beginning of the function during the start of the deadstore pass- for the top func.
  2746. * In case of inlinee, it will be from the source sym of the ArgOut Instruction to the inlinee.
  2747. */
  2748. case Js::OpCode::LdSlot:
  2749. {
  2750. IR::Opnd * src1 = instr->GetSrc1();
  2751. if (src1 && src1->IsSymOpnd())
  2752. {
  2753. Sym * sym = src1->AsSymOpnd()->m_sym;
  2754. Assert(sym);
  2755. if (IsFormalParamSym(currFunc, sym))
  2756. {
  2757. AssertMsg(!currFunc->GetJITFunctionBody()->HasImplicitArgIns(), "We don't have mappings between named formals and arguments object here");
  2758. instr->m_opcode = Js::OpCode::Ld_A;
  2759. PropertySym * propSym = sym->AsPropertySym();
  2760. Js::ArgSlot value = (Js::ArgSlot)propSym->m_propertyId;
  2761. Assert(currFunc->HasStackSymForFormal(value));
  2762. StackSym * paramStackSym = currFunc->GetStackSymForFormal(value);
  2763. IR::RegOpnd * srcOpnd = IR::RegOpnd::New(paramStackSym, TyVar, currFunc);
  2764. instr->ReplaceSrc1(srcOpnd);
  2765. this->ProcessSymUse(paramStackSym, true, true);
  2766. if (PHASE_VERBOSE_TRACE1(Js::StackArgFormalsOptPhase))
  2767. {
  2768. Output::Print(_u("StackArgFormals : %s (%d) :Replacing LdSlot with Ld_A in Deadstore pass. \n"), instr->m_func->GetJITFunctionBody()->GetDisplayName(), instr->m_func->GetFunctionNumber());
  2769. Output::Flush();
  2770. }
  2771. }
  2772. }
  2773. break;
  2774. }
  2775. case Js::OpCode::CommitScope:
  2776. {
  2777. if (instr->GetSrc1()->IsScopeObjOpnd(currFunc))
  2778. {
  2779. instr->Remove();
  2780. return true;
  2781. }
  2782. break;
  2783. }
  2784. case Js::OpCode::BrFncCachedScopeEq:
  2785. case Js::OpCode::BrFncCachedScopeNeq:
  2786. {
  2787. if (instr->GetSrc2()->IsScopeObjOpnd(currFunc))
  2788. {
  2789. instr->Remove();
  2790. return true;
  2791. }
  2792. break;
  2793. }
  2794. case Js::OpCode::CallHelper:
  2795. {
  2796. //Remove the CALL and all its Argout instrs.
  2797. if (instr->GetSrc1()->AsHelperCallOpnd()->m_fnHelper == IR::JnHelperMethod::HelperOP_InitCachedFuncs)
  2798. {
  2799. IR::RegOpnd * scopeObjOpnd = instr->GetSrc2()->GetStackSym()->GetInstrDef()->GetSrc1()->AsRegOpnd();
  2800. if (scopeObjOpnd->IsScopeObjOpnd(currFunc))
  2801. {
  2802. IR::Instr * instrDef = instr;
  2803. IR::Instr * nextInstr = instr->m_next;
  2804. while (instrDef != nullptr)
  2805. {
  2806. IR::Instr * instrToDelete = instrDef;
  2807. if (instrDef->GetSrc2() != nullptr)
  2808. {
  2809. instrDef = instrDef->GetSrc2()->GetStackSym()->GetInstrDef();
  2810. Assert(instrDef->m_opcode == Js::OpCode::ArgOut_A);
  2811. }
  2812. else
  2813. {
  2814. instrDef = nullptr;
  2815. }
  2816. instrToDelete->Remove();
  2817. }
  2818. Assert(nextInstr != nullptr);
  2819. *pInstrPrev = nextInstr->m_prev;
  2820. return true;
  2821. }
  2822. }
  2823. break;
  2824. }
  2825. case Js::OpCode::GetCachedFunc:
  2826. {
  2827. // <dst> = GetCachedFunc <scopeObject>, <functionNum>
  2828. // is converted to
  2829. // <dst> = NewScFunc <functionNum>, <env: FrameDisplay>
  2830. if (instr->GetSrc1()->IsScopeObjOpnd(currFunc))
  2831. {
  2832. instr->m_opcode = Js::OpCode::NewScFunc;
  2833. IR::Opnd * intConstOpnd = instr->UnlinkSrc2();
  2834. Assert(intConstOpnd->IsIntConstOpnd());
  2835. uint nestedFuncIndex = instr->m_func->GetJITFunctionBody()->GetNestedFuncIndexForSlotIdInCachedScope(intConstOpnd->AsIntConstOpnd()->AsUint32());
  2836. intConstOpnd->Free(instr->m_func);
  2837. instr->ReplaceSrc1(IR::IntConstOpnd::New(nestedFuncIndex, TyUint32, instr->m_func));
  2838. instr->SetSrc2(IR::RegOpnd::New(currFunc->GetLocalFrameDisplaySym(), IRType::TyVar, currFunc));
  2839. }
  2840. break;
  2841. }
  2842. }
  2843. }
  2844. return false;
  2845. }
  2846. IR::Instr *
  2847. BackwardPass::TryChangeInstrForStackArgOpt()
  2848. {
  2849. IR::Instr * instr = this->currentInstr;
  2850. if (tag == Js::DeadStorePhase && instr->DoStackArgsOpt(this->func))
  2851. {
  2852. switch (instr->m_opcode)
  2853. {
  2854. case Js::OpCode::TypeofElem:
  2855. {
  2856. /*
  2857. Before:
  2858. dst = TypeOfElem arguments[i] <(BailOnStackArgsOutOfActualsRange)>
  2859. After:
  2860. tmpdst = LdElemI_A arguments[i] <(BailOnStackArgsOutOfActualsRange)>
  2861. dst = TypeOf tmpdst
  2862. */
  2863. AssertMsg(instr->HasBailOutInfo() && (instr->GetBailOutKind() & IR::BailOutKind::BailOnStackArgsOutOfActualsRange), "Why is the bailout kind not set, when it is StackArgOptimized?");
  2864. instr->m_opcode = Js::OpCode::LdElemI_A;
  2865. IR::Opnd * dstOpnd = instr->UnlinkDst();
  2866. IR::RegOpnd * elementOpnd = IR::RegOpnd::New(StackSym::New(instr->m_func), IRType::TyVar, instr->m_func);
  2867. instr->SetDst(elementOpnd);
  2868. IR::Instr * typeOfInstr = IR::Instr::New(Js::OpCode::Typeof, dstOpnd, elementOpnd, instr->m_func);
  2869. instr->InsertAfter(typeOfInstr);
  2870. return typeOfInstr;
  2871. }
  2872. }
  2873. }
  2874. /*
  2875. * Scope Object Sym is kept alive in all code paths.
  2876. * -This is to facilitate Bailout to record the live Scope object Sym, whenever required.
  2877. * -Reason for doing is this because - Scope object has to be implicitly live whenever Heap Arguments object is live.
  2878. * -When we restore HeapArguments object in the bail out path, it expects the scope object also to be restored - if one was created.
  2879. * -We do not know detailed information about Heap arguments obj syms(aliasing etc.) until we complete Forward Pass.
  2880. * -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.
  2881. * -Hence this is the optimal spot to do this.
  2882. */
  2883. if (tag == Js::BackwardPhase && instr->m_func->GetScopeObjSym() != nullptr)
  2884. {
  2885. this->currentBlock->upwardExposedUses->Set(instr->m_func->GetScopeObjSym()->m_id);
  2886. }
  2887. return nullptr;
  2888. }
  2889. void
  2890. BackwardPass::TraceDeadStoreOfInstrsForScopeObjectRemoval()
  2891. {
  2892. IR::Instr * instr = this->currentInstr;
  2893. if (instr->m_func->IsStackArgsEnabled())
  2894. {
  2895. if ((instr->m_opcode == Js::OpCode::InitCachedScope || instr->m_opcode == Js::OpCode::NewScopeObject) && !IsPrePass())
  2896. {
  2897. if (PHASE_TRACE1(Js::StackArgFormalsOptPhase))
  2898. {
  2899. Output::Print(_u("StackArgFormals : %s (%d) :Removing Scope object creation in Deadstore pass. \n"), instr->m_func->GetJITFunctionBody()->GetDisplayName(), instr->m_func->GetFunctionNumber());
  2900. Output::Flush();
  2901. }
  2902. }
  2903. }
  2904. }
  2905. bool
  2906. BackwardPass::IsFormalParamSym(Func * func, Sym * sym) const
  2907. {
  2908. Assert(sym);
  2909. if (sym->IsPropertySym())
  2910. {
  2911. //If the sym is a propertySym, then see if the propertyId is within the range of the formals
  2912. //We can have other properties stored in the scope object other than the formals (following the formals).
  2913. PropertySym * propSym = sym->AsPropertySym();
  2914. IntConstType value = propSym->m_propertyId;
  2915. return func->IsFormalsArraySym(propSym->m_stackSym->m_id) &&
  2916. (value >= 0 && value < func->GetJITFunctionBody()->GetInParamsCount() - 1);
  2917. }
  2918. else
  2919. {
  2920. Assert(sym->IsStackSym());
  2921. return !!func->IsFormalsArraySym(sym->AsStackSym()->m_id);
  2922. }
  2923. }
  2924. #if DBG_DUMP
  2925. void
  2926. BackwardPass::DumpBlockData(BasicBlock * block)
  2927. {
  2928. block->DumpHeader();
  2929. if (block->upwardExposedUses) // may be null for dead blocks
  2930. {
  2931. Output::Print(_u(" Exposed Uses: "));
  2932. block->upwardExposedUses->Dump();
  2933. }
  2934. if (block->typesNeedingKnownObjectLayout)
  2935. {
  2936. Output::Print(_u(" Needs Known Object Layout: "));
  2937. block->typesNeedingKnownObjectLayout->Dump();
  2938. }
  2939. if (this->DoFieldHoistCandidates() && !block->isDead)
  2940. {
  2941. Output::Print(_u(" Exposed Field: "));
  2942. block->fieldHoistCandidates->Dump();
  2943. }
  2944. if (block->byteCodeUpwardExposedUsed)
  2945. {
  2946. Output::Print(_u(" Byte Code Exposed Uses: "));
  2947. block->byteCodeUpwardExposedUsed->Dump();
  2948. }
  2949. if (!this->IsCollectionPass())
  2950. {
  2951. if (!block->isDead)
  2952. {
  2953. if (this->DoDeadStoreSlots())
  2954. {
  2955. Output::Print(_u("Slot deadStore candidates: "));
  2956. block->slotDeadStoreCandidates->Dump();
  2957. }
  2958. DumpMarkTemp();
  2959. }
  2960. }
  2961. Output::Flush();
  2962. }
  2963. #endif
  2964. bool
  2965. BackwardPass::UpdateImplicitCallBailOutKind(IR::Instr *const instr, bool needsBailOutOnImplicitCall)
  2966. {
  2967. Assert(instr);
  2968. Assert(instr->HasBailOutInfo());
  2969. IR::BailOutKind implicitCallBailOutKind = needsBailOutOnImplicitCall ? IR::BailOutOnImplicitCalls : IR::BailOutInvalid;
  2970. const IR::BailOutKind instrBailOutKind = instr->GetBailOutKind();
  2971. if (instrBailOutKind & IR::BailOutMarkTempObject)
  2972. {
  2973. // Don't remove the implicit call pre op bailout for mark temp object
  2974. // Remove the mark temp object bit, as we don't need it after the dead store pass
  2975. instr->SetBailOutKind(instrBailOutKind & ~IR::BailOutMarkTempObject);
  2976. return true;
  2977. }
  2978. const IR::BailOutKind instrImplicitCallBailOutKind = instrBailOutKind & ~IR::BailOutKindBits;
  2979. if(instrImplicitCallBailOutKind == IR::BailOutOnImplicitCallsPreOp)
  2980. {
  2981. if(needsBailOutOnImplicitCall)
  2982. {
  2983. implicitCallBailOutKind = IR::BailOutOnImplicitCallsPreOp;
  2984. }
  2985. }
  2986. else if(instrImplicitCallBailOutKind != IR::BailOutOnImplicitCalls && instrImplicitCallBailOutKind != IR::BailOutInvalid)
  2987. {
  2988. // This bailout kind (the value of 'instrImplicitCallBailOutKind') must guarantee that implicit calls will not happen.
  2989. // If it doesn't make such a guarantee, it must be possible to merge this bailout kind with an implicit call bailout
  2990. // kind, and therefore should be part of BailOutKindBits.
  2991. Assert(!needsBailOutOnImplicitCall);
  2992. return true;
  2993. }
  2994. if(instrImplicitCallBailOutKind == implicitCallBailOutKind)
  2995. {
  2996. return true;
  2997. }
  2998. const IR::BailOutKind newBailOutKind = instrBailOutKind - instrImplicitCallBailOutKind + implicitCallBailOutKind;
  2999. if(newBailOutKind == IR::BailOutInvalid)
  3000. {
  3001. return false;
  3002. }
  3003. instr->SetBailOutKind(newBailOutKind);
  3004. return true;
  3005. }
  3006. bool
  3007. BackwardPass::ProcessNoImplicitCallUses(IR::Instr *const instr)
  3008. {
  3009. Assert(instr);
  3010. if(instr->m_opcode != Js::OpCode::NoImplicitCallUses)
  3011. {
  3012. return false;
  3013. }
  3014. Assert(tag == Js::DeadStorePhase);
  3015. Assert(!instr->GetDst());
  3016. Assert(instr->GetSrc1());
  3017. Assert(instr->GetSrc1()->IsRegOpnd() || instr->GetSrc1()->IsSymOpnd());
  3018. Assert(!instr->GetSrc2() || instr->GetSrc2()->IsRegOpnd() || instr->GetSrc2()->IsSymOpnd());
  3019. if(IsCollectionPass())
  3020. {
  3021. return true;
  3022. }
  3023. IR::Opnd *const srcs[] = { instr->GetSrc1(), instr->GetSrc2() };
  3024. for(int i = 0; i < sizeof(srcs) / sizeof(srcs[0]) && srcs[i]; ++i)
  3025. {
  3026. IR::Opnd *const src = srcs[i];
  3027. IR::ArrayRegOpnd *arraySrc = nullptr;
  3028. Sym *sym = nullptr;
  3029. switch(src->GetKind())
  3030. {
  3031. case IR::OpndKindReg:
  3032. {
  3033. IR::RegOpnd *const regSrc = src->AsRegOpnd();
  3034. sym = regSrc->m_sym;
  3035. if(considerSymAsRealUseInNoImplicitCallUses && considerSymAsRealUseInNoImplicitCallUses == sym)
  3036. {
  3037. considerSymAsRealUseInNoImplicitCallUses = nullptr;
  3038. ProcessStackSymUse(sym->AsStackSym(), true);
  3039. }
  3040. if(regSrc->IsArrayRegOpnd())
  3041. {
  3042. arraySrc = regSrc->AsArrayRegOpnd();
  3043. }
  3044. break;
  3045. }
  3046. case IR::OpndKindSym:
  3047. sym = src->AsSymOpnd()->m_sym;
  3048. Assert(sym->IsPropertySym());
  3049. break;
  3050. default:
  3051. Assert(false);
  3052. __assume(false);
  3053. }
  3054. currentBlock->noImplicitCallUses->Set(sym->m_id);
  3055. const ValueType valueType(src->GetValueType());
  3056. if(valueType.IsArrayOrObjectWithArray())
  3057. {
  3058. if(valueType.HasNoMissingValues())
  3059. {
  3060. currentBlock->noImplicitCallNoMissingValuesUses->Set(sym->m_id);
  3061. }
  3062. if(!valueType.HasVarElements())
  3063. {
  3064. currentBlock->noImplicitCallNativeArrayUses->Set(sym->m_id);
  3065. }
  3066. if(arraySrc)
  3067. {
  3068. ProcessArrayRegOpndUse(instr, arraySrc);
  3069. }
  3070. }
  3071. }
  3072. if(!IsPrePass())
  3073. {
  3074. currentBlock->RemoveInstr(instr);
  3075. }
  3076. return true;
  3077. }
  3078. void
  3079. BackwardPass::ProcessNoImplicitCallDef(IR::Instr *const instr)
  3080. {
  3081. Assert(tag == Js::DeadStorePhase);
  3082. Assert(instr);
  3083. IR::Opnd *const dst = instr->GetDst();
  3084. if(!dst)
  3085. {
  3086. return;
  3087. }
  3088. Sym *dstSym;
  3089. switch(dst->GetKind())
  3090. {
  3091. case IR::OpndKindReg:
  3092. dstSym = dst->AsRegOpnd()->m_sym;
  3093. break;
  3094. case IR::OpndKindSym:
  3095. dstSym = dst->AsSymOpnd()->m_sym;
  3096. if(!dstSym->IsPropertySym())
  3097. {
  3098. return;
  3099. }
  3100. break;
  3101. default:
  3102. return;
  3103. }
  3104. if(!currentBlock->noImplicitCallUses->TestAndClear(dstSym->m_id))
  3105. {
  3106. Assert(!currentBlock->noImplicitCallNoMissingValuesUses->Test(dstSym->m_id));
  3107. Assert(!currentBlock->noImplicitCallNativeArrayUses->Test(dstSym->m_id));
  3108. Assert(!currentBlock->noImplicitCallJsArrayHeadSegmentSymUses->Test(dstSym->m_id));
  3109. Assert(!currentBlock->noImplicitCallArrayLengthSymUses->Test(dstSym->m_id));
  3110. return;
  3111. }
  3112. const bool transferNoMissingValuesUse = !!currentBlock->noImplicitCallNoMissingValuesUses->TestAndClear(dstSym->m_id);
  3113. const bool transferNativeArrayUse = !!currentBlock->noImplicitCallNativeArrayUses->TestAndClear(dstSym->m_id);
  3114. const bool transferJsArrayHeadSegmentSymUse =
  3115. !!currentBlock->noImplicitCallJsArrayHeadSegmentSymUses->TestAndClear(dstSym->m_id);
  3116. const bool transferArrayLengthSymUse = !!currentBlock->noImplicitCallArrayLengthSymUses->TestAndClear(dstSym->m_id);
  3117. IR::Opnd *const src = instr->GetSrc1();
  3118. if(!src || instr->GetSrc2())
  3119. {
  3120. return;
  3121. }
  3122. if(dst->IsRegOpnd() && src->IsRegOpnd())
  3123. {
  3124. if(!OpCodeAttr::NonIntTransfer(instr->m_opcode))
  3125. {
  3126. return;
  3127. }
  3128. }
  3129. else if(
  3130. !(
  3131. // LdFld or similar
  3132. (dst->IsRegOpnd() && src->IsSymOpnd() && src->AsSymOpnd()->m_sym->IsPropertySym()) ||
  3133. // StFld or similar. Don't transfer a field opnd from StFld into the reg opnd src unless the field's value type is
  3134. // definitely array or object with array, because only those value types require implicit calls to be disabled as
  3135. // long as they are live. Other definite value types only require implicit calls to be disabled as long as a live
  3136. // field holds the value, which is up to the StFld when going backwards.
  3137. (src->IsRegOpnd() && dst->GetValueType().IsArrayOrObjectWithArray())
  3138. ) ||
  3139. !instr->TransfersSrcValue())
  3140. {
  3141. return;
  3142. }
  3143. Sym *srcSym = nullptr;
  3144. switch(src->GetKind())
  3145. {
  3146. case IR::OpndKindReg:
  3147. srcSym = src->AsRegOpnd()->m_sym;
  3148. break;
  3149. case IR::OpndKindSym:
  3150. srcSym = src->AsSymOpnd()->m_sym;
  3151. Assert(srcSym->IsPropertySym());
  3152. break;
  3153. default:
  3154. Assert(false);
  3155. __assume(false);
  3156. }
  3157. currentBlock->noImplicitCallUses->Set(srcSym->m_id);
  3158. if(transferNoMissingValuesUse)
  3159. {
  3160. currentBlock->noImplicitCallNoMissingValuesUses->Set(srcSym->m_id);
  3161. }
  3162. if(transferNativeArrayUse)
  3163. {
  3164. currentBlock->noImplicitCallNativeArrayUses->Set(srcSym->m_id);
  3165. }
  3166. if(transferJsArrayHeadSegmentSymUse)
  3167. {
  3168. currentBlock->noImplicitCallJsArrayHeadSegmentSymUses->Set(srcSym->m_id);
  3169. }
  3170. if(transferArrayLengthSymUse)
  3171. {
  3172. currentBlock->noImplicitCallArrayLengthSymUses->Set(srcSym->m_id);
  3173. }
  3174. }
  3175. template<class F>
  3176. IR::Opnd *
  3177. BackwardPass::FindNoImplicitCallUse(
  3178. IR::Instr *const instr,
  3179. StackSym *const sym,
  3180. const F IsCheckedUse,
  3181. IR::Instr * *const noImplicitCallUsesInstrRef)
  3182. {
  3183. IR::RegOpnd *const opnd = IR::RegOpnd::New(sym, sym->GetType(), instr->m_func);
  3184. IR::Opnd *const use = FindNoImplicitCallUse(instr, opnd, IsCheckedUse, noImplicitCallUsesInstrRef);
  3185. opnd->FreeInternal(instr->m_func);
  3186. return use;
  3187. }
  3188. template<class F>
  3189. IR::Opnd *
  3190. BackwardPass::FindNoImplicitCallUse(
  3191. IR::Instr *const instr,
  3192. IR::Opnd *const opnd,
  3193. const F IsCheckedUse,
  3194. IR::Instr * *const noImplicitCallUsesInstrRef)
  3195. {
  3196. Assert(instr);
  3197. Assert(instr->m_opcode != Js::OpCode::NoImplicitCallUses);
  3198. // Skip byte-code uses
  3199. IR::Instr *prevInstr = instr->m_prev;
  3200. while(
  3201. prevInstr &&
  3202. !prevInstr->IsLabelInstr() &&
  3203. (!prevInstr->IsRealInstr() || prevInstr->IsByteCodeUsesInstr()) &&
  3204. prevInstr->m_opcode != Js::OpCode::NoImplicitCallUses)
  3205. {
  3206. prevInstr = prevInstr->m_prev;
  3207. }
  3208. // Find the corresponding use in a NoImplicitCallUses instruction
  3209. for(; prevInstr && prevInstr->m_opcode == Js::OpCode::NoImplicitCallUses; prevInstr = prevInstr->m_prev)
  3210. {
  3211. IR::Opnd *const checkedSrcs[] = { prevInstr->GetSrc1(), prevInstr->GetSrc2() };
  3212. for(int i = 0; i < sizeof(checkedSrcs) / sizeof(checkedSrcs[0]) && checkedSrcs[i]; ++i)
  3213. {
  3214. IR::Opnd *const checkedSrc = checkedSrcs[i];
  3215. if(checkedSrc->IsEqual(opnd) && IsCheckedUse(checkedSrc))
  3216. {
  3217. if(noImplicitCallUsesInstrRef)
  3218. {
  3219. *noImplicitCallUsesInstrRef = prevInstr;
  3220. }
  3221. return checkedSrc;
  3222. }
  3223. }
  3224. }
  3225. if(noImplicitCallUsesInstrRef)
  3226. {
  3227. *noImplicitCallUsesInstrRef = nullptr;
  3228. }
  3229. return nullptr;
  3230. }
  3231. void
  3232. BackwardPass::ProcessArrayRegOpndUse(IR::Instr *const instr, IR::ArrayRegOpnd *const arrayRegOpnd)
  3233. {
  3234. Assert(tag == Js::DeadStorePhase);
  3235. Assert(!IsCollectionPass());
  3236. Assert(instr);
  3237. Assert(arrayRegOpnd);
  3238. if(!(arrayRegOpnd->HeadSegmentSym() || arrayRegOpnd->HeadSegmentLengthSym() || arrayRegOpnd->LengthSym()))
  3239. {
  3240. return;
  3241. }
  3242. const ValueType arrayValueType(arrayRegOpnd->GetValueType());
  3243. const bool isJsArray = !arrayValueType.IsLikelyTypedArray();
  3244. Assert(isJsArray == arrayValueType.IsArrayOrObjectWithArray());
  3245. Assert(!isJsArray == arrayValueType.IsOptimizedTypedArray());
  3246. BasicBlock *const block = currentBlock;
  3247. if(!IsPrePass() &&
  3248. (arrayRegOpnd->HeadSegmentSym() || arrayRegOpnd->HeadSegmentLengthSym()) &&
  3249. (!isJsArray || instr->m_opcode != Js::OpCode::NoImplicitCallUses))
  3250. {
  3251. bool headSegmentIsLoadedButUnused =
  3252. instr->loadedArrayHeadSegment &&
  3253. arrayRegOpnd->HeadSegmentSym() &&
  3254. !block->upwardExposedUses->Test(arrayRegOpnd->HeadSegmentSym()->m_id);
  3255. const bool headSegmentLengthIsLoadedButUnused =
  3256. instr->loadedArrayHeadSegmentLength &&
  3257. arrayRegOpnd->HeadSegmentLengthSym() &&
  3258. !block->upwardExposedUses->Test(arrayRegOpnd->HeadSegmentLengthSym()->m_id);
  3259. if(headSegmentLengthIsLoadedButUnused && instr->extractedUpperBoundCheckWithoutHoisting)
  3260. {
  3261. // Find the upper bound check (index[src1] <= headSegmentLength[src2] + offset[dst])
  3262. IR::Instr *upperBoundCheck = this->globOpt->FindUpperBoundsCheckInstr(instr);
  3263. Assert(upperBoundCheck && upperBoundCheck != instr);
  3264. Assert(upperBoundCheck->GetSrc2()->AsRegOpnd()->m_sym == arrayRegOpnd->HeadSegmentLengthSym());
  3265. // Find the head segment length load
  3266. IR::Instr *headSegmentLengthLoad = this->globOpt->FindArraySegmentLoadInstr(upperBoundCheck);
  3267. Assert(headSegmentLengthLoad->GetDst()->AsRegOpnd()->m_sym == arrayRegOpnd->HeadSegmentLengthSym());
  3268. Assert(
  3269. headSegmentLengthLoad->GetSrc1()->AsIndirOpnd()->GetBaseOpnd()->m_sym ==
  3270. (isJsArray ? arrayRegOpnd->HeadSegmentSym() : arrayRegOpnd->m_sym));
  3271. // Fold the head segment length load into the upper bound check. Keep the load instruction there with a Nop so that
  3272. // the head segment length sym can be marked as unused before the Nop. The lowerer will remove it.
  3273. upperBoundCheck->ReplaceSrc2(headSegmentLengthLoad->UnlinkSrc1());
  3274. headSegmentLengthLoad->m_opcode = Js::OpCode::Nop;
  3275. if(isJsArray)
  3276. {
  3277. // The head segment length is on the head segment, so the bound check now uses the head segment sym
  3278. headSegmentIsLoadedButUnused = false;
  3279. }
  3280. }
  3281. if(headSegmentIsLoadedButUnused || headSegmentLengthIsLoadedButUnused)
  3282. {
  3283. // Check if the head segment / head segment length are being loaded here. If so, remove them and let the fast
  3284. // path load them since it does a better job.
  3285. IR::ArrayRegOpnd *noImplicitCallArrayUse = nullptr;
  3286. if(isJsArray)
  3287. {
  3288. IR::Opnd *const use =
  3289. FindNoImplicitCallUse(
  3290. instr,
  3291. arrayRegOpnd,
  3292. [&](IR::Opnd *const checkedSrc) -> bool
  3293. {
  3294. const ValueType checkedSrcValueType(checkedSrc->GetValueType());
  3295. if(!checkedSrcValueType.IsLikelyObject() ||
  3296. checkedSrcValueType.GetObjectType() != arrayValueType.GetObjectType())
  3297. {
  3298. return false;
  3299. }
  3300. IR::RegOpnd *const checkedRegSrc = checkedSrc->AsRegOpnd();
  3301. if(!checkedRegSrc->IsArrayRegOpnd())
  3302. {
  3303. return false;
  3304. }
  3305. IR::ArrayRegOpnd *const checkedArraySrc = checkedRegSrc->AsArrayRegOpnd();
  3306. if(headSegmentIsLoadedButUnused &&
  3307. checkedArraySrc->HeadSegmentSym() != arrayRegOpnd->HeadSegmentSym())
  3308. {
  3309. return false;
  3310. }
  3311. if(headSegmentLengthIsLoadedButUnused &&
  3312. checkedArraySrc->HeadSegmentLengthSym() != arrayRegOpnd->HeadSegmentLengthSym())
  3313. {
  3314. return false;
  3315. }
  3316. return true;
  3317. });
  3318. if(use)
  3319. {
  3320. noImplicitCallArrayUse = use->AsRegOpnd()->AsArrayRegOpnd();
  3321. }
  3322. }
  3323. else if(headSegmentLengthIsLoadedButUnused)
  3324. {
  3325. // A typed array's head segment length may be zeroed when the typed array's buffer is transferred to a web
  3326. // worker, so the head segment length sym use is included in a NoImplicitCallUses instruction. Since there
  3327. // are no forward uses of the head segment length sym, to allow removing the extracted head segment length
  3328. // load, the corresponding head segment length sym use in the NoImplicitCallUses instruction must also be
  3329. // removed.
  3330. IR::Instr *noImplicitCallUsesInstr;
  3331. IR::Opnd *const use =
  3332. FindNoImplicitCallUse(
  3333. instr,
  3334. arrayRegOpnd->HeadSegmentLengthSym(),
  3335. [&](IR::Opnd *const checkedSrc) -> bool
  3336. {
  3337. return checkedSrc->AsRegOpnd()->m_sym == arrayRegOpnd->HeadSegmentLengthSym();
  3338. },
  3339. &noImplicitCallUsesInstr);
  3340. if(use)
  3341. {
  3342. Assert(noImplicitCallUsesInstr);
  3343. Assert(!noImplicitCallUsesInstr->GetDst());
  3344. Assert(noImplicitCallUsesInstr->GetSrc1());
  3345. if(use == noImplicitCallUsesInstr->GetSrc1())
  3346. {
  3347. if(noImplicitCallUsesInstr->GetSrc2())
  3348. {
  3349. noImplicitCallUsesInstr->ReplaceSrc1(noImplicitCallUsesInstr->UnlinkSrc2());
  3350. }
  3351. else
  3352. {
  3353. noImplicitCallUsesInstr->FreeSrc1();
  3354. noImplicitCallUsesInstr->m_opcode = Js::OpCode::Nop;
  3355. }
  3356. }
  3357. else
  3358. {
  3359. Assert(use == noImplicitCallUsesInstr->GetSrc2());
  3360. noImplicitCallUsesInstr->FreeSrc2();
  3361. }
  3362. }
  3363. }
  3364. if(headSegmentIsLoadedButUnused &&
  3365. (!isJsArray || !arrayRegOpnd->HeadSegmentLengthSym() || headSegmentLengthIsLoadedButUnused))
  3366. {
  3367. // For JS arrays, the head segment length load is dependent on the head segment. So, only remove the head
  3368. // segment load if the head segment length load can also be removed.
  3369. arrayRegOpnd->RemoveHeadSegmentSym();
  3370. instr->loadedArrayHeadSegment = false;
  3371. if(noImplicitCallArrayUse)
  3372. {
  3373. noImplicitCallArrayUse->RemoveHeadSegmentSym();
  3374. }
  3375. }
  3376. if(headSegmentLengthIsLoadedButUnused)
  3377. {
  3378. arrayRegOpnd->RemoveHeadSegmentLengthSym();
  3379. instr->loadedArrayHeadSegmentLength = false;
  3380. if(noImplicitCallArrayUse)
  3381. {
  3382. noImplicitCallArrayUse->RemoveHeadSegmentLengthSym();
  3383. }
  3384. }
  3385. }
  3386. }
  3387. if(isJsArray && instr->m_opcode != Js::OpCode::NoImplicitCallUses)
  3388. {
  3389. // Only uses in NoImplicitCallUses instructions are counted toward liveness
  3390. return;
  3391. }
  3392. // Treat dependent syms as uses. For JS arrays, only uses in NoImplicitCallUses count because only then the assumptions made
  3393. // on the dependent syms are guaranteed to be valid. Similarly for typed arrays, a head segment length sym use counts toward
  3394. // liveness only in a NoImplicitCallUses instruction.
  3395. if(arrayRegOpnd->HeadSegmentSym())
  3396. {
  3397. ProcessStackSymUse(arrayRegOpnd->HeadSegmentSym(), true);
  3398. if(isJsArray)
  3399. {
  3400. block->noImplicitCallUses->Set(arrayRegOpnd->HeadSegmentSym()->m_id);
  3401. block->noImplicitCallJsArrayHeadSegmentSymUses->Set(arrayRegOpnd->HeadSegmentSym()->m_id);
  3402. }
  3403. }
  3404. if(arrayRegOpnd->HeadSegmentLengthSym())
  3405. {
  3406. if(isJsArray)
  3407. {
  3408. ProcessStackSymUse(arrayRegOpnd->HeadSegmentLengthSym(), true);
  3409. block->noImplicitCallUses->Set(arrayRegOpnd->HeadSegmentLengthSym()->m_id);
  3410. block->noImplicitCallJsArrayHeadSegmentSymUses->Set(arrayRegOpnd->HeadSegmentLengthSym()->m_id);
  3411. }
  3412. else
  3413. {
  3414. // ProcessNoImplicitCallUses automatically marks JS array reg opnds and their corresponding syms as live. A typed
  3415. // array's head segment length sym also needs to be marked as live at its use in the NoImplicitCallUses instruction,
  3416. // but it is just in a reg opnd. Flag the opnd to have the sym be marked as live when that instruction is processed.
  3417. Assert(!considerSymAsRealUseInNoImplicitCallUses);
  3418. IR::Opnd *const use =
  3419. FindNoImplicitCallUse(
  3420. instr,
  3421. arrayRegOpnd->HeadSegmentLengthSym(),
  3422. [&](IR::Opnd *const checkedSrc) -> bool
  3423. {
  3424. return checkedSrc->AsRegOpnd()->m_sym == arrayRegOpnd->HeadSegmentLengthSym();
  3425. });
  3426. if(use)
  3427. {
  3428. considerSymAsRealUseInNoImplicitCallUses = arrayRegOpnd->HeadSegmentLengthSym();
  3429. }
  3430. }
  3431. }
  3432. StackSym *const lengthSym = arrayRegOpnd->LengthSym();
  3433. if(lengthSym && lengthSym != arrayRegOpnd->HeadSegmentLengthSym())
  3434. {
  3435. ProcessStackSymUse(lengthSym, true);
  3436. Assert(arrayValueType.IsArray());
  3437. block->noImplicitCallUses->Set(lengthSym->m_id);
  3438. block->noImplicitCallArrayLengthSymUses->Set(lengthSym->m_id);
  3439. }
  3440. }
  3441. void
  3442. BackwardPass::ProcessNewScObject(IR::Instr* instr)
  3443. {
  3444. if (this->tag != Js::DeadStorePhase || IsCollectionPass())
  3445. {
  3446. return;
  3447. }
  3448. if (!instr->IsNewScObjectInstr())
  3449. {
  3450. return;
  3451. }
  3452. if (instr->HasBailOutInfo())
  3453. {
  3454. Assert(instr->IsProfiledInstr());
  3455. Assert(instr->GetBailOutKind() == IR::BailOutFailedCtorGuardCheck);
  3456. Assert(instr->GetDst()->IsRegOpnd());
  3457. BasicBlock * block = this->currentBlock;
  3458. StackSym* objSym = instr->GetDst()->AsRegOpnd()->GetStackSym();
  3459. if (block->upwardExposedUses->Test(objSym->m_id))
  3460. {
  3461. // If the object created here is used downstream, let's capture any property operations we must protect.
  3462. Assert(instr->GetDst()->AsRegOpnd()->GetStackSym()->HasObjectTypeSym());
  3463. JITTimeConstructorCache* ctorCache = instr->m_func->GetConstructorCache(static_cast<Js::ProfileId>(instr->AsProfiledInstr()->u.profileId));
  3464. if (block->stackSymToFinalType != nullptr)
  3465. {
  3466. // NewScObject is the origin of the object pointer. If we have a final type in hand, do the
  3467. // transition here.
  3468. AddPropertyCacheBucket *pBucket = block->stackSymToFinalType->Get(objSym->m_id);
  3469. if (pBucket &&
  3470. pBucket->GetInitialType() != nullptr &&
  3471. pBucket->GetFinalType() != pBucket->GetInitialType())
  3472. {
  3473. Assert(pBucket->GetInitialType() == ctorCache->GetType());
  3474. if (!this->IsPrePass())
  3475. {
  3476. this->InsertTypeTransition(instr->m_next, objSym, pBucket);
  3477. }
  3478. #if DBG
  3479. pBucket->deadStoreUnavailableInitialType = pBucket->GetInitialType();
  3480. if (pBucket->deadStoreUnavailableFinalType == nullptr)
  3481. {
  3482. pBucket->deadStoreUnavailableFinalType = pBucket->GetFinalType();
  3483. }
  3484. pBucket->SetInitialType(nullptr);
  3485. pBucket->SetFinalType(nullptr);
  3486. #else
  3487. block->stackSymToFinalType->Clear(objSym->m_id);
  3488. #endif
  3489. }
  3490. }
  3491. if (block->stackSymToGuardedProperties != nullptr)
  3492. {
  3493. ObjTypeGuardBucket* bucket = block->stackSymToGuardedProperties->Get(objSym->m_id);
  3494. if (bucket != nullptr)
  3495. {
  3496. BVSparse<JitArenaAllocator>* guardedPropertyOps = bucket->GetGuardedPropertyOps();
  3497. if (guardedPropertyOps != nullptr)
  3498. {
  3499. ctorCache->EnsureGuardedPropOps(this->func->m_alloc);
  3500. ctorCache->AddGuardedPropOps(guardedPropertyOps);
  3501. bucket->SetGuardedPropertyOps(nullptr);
  3502. JitAdelete(this->tempAlloc, guardedPropertyOps);
  3503. block->stackSymToGuardedProperties->Clear(objSym->m_id);
  3504. }
  3505. }
  3506. }
  3507. }
  3508. else
  3509. {
  3510. // If the object is not used downstream, let's remove the bailout and let the lowerer emit a fast path along with
  3511. // the fallback on helper, if the ctor cache ever became invalid.
  3512. instr->ClearBailOutInfo();
  3513. if (preOpBailOutInstrToProcess == instr)
  3514. {
  3515. preOpBailOutInstrToProcess = nullptr;
  3516. }
  3517. #if DBG
  3518. // We're creating a brand new object here, so no type check upstream could protect any properties of this
  3519. // object. Let's make sure we don't have any left to protect.
  3520. ObjTypeGuardBucket* bucket = block->stackSymToGuardedProperties != nullptr ?
  3521. block->stackSymToGuardedProperties->Get(objSym->m_id) : nullptr;
  3522. Assert(bucket == nullptr || bucket->GetGuardedPropertyOps()->IsEmpty());
  3523. #endif
  3524. }
  3525. }
  3526. }
  3527. void
  3528. BackwardPass::UpdateArrayValueTypes(IR::Instr *const instr, IR::Opnd *origOpnd)
  3529. {
  3530. Assert(tag == Js::DeadStorePhase);
  3531. Assert(!IsPrePass());
  3532. Assert(instr);
  3533. if(!origOpnd)
  3534. {
  3535. return;
  3536. }
  3537. IR::Instr *opndOwnerInstr = instr;
  3538. switch(instr->m_opcode)
  3539. {
  3540. case Js::OpCode::StElemC:
  3541. case Js::OpCode::StArrSegElemC:
  3542. // These may not be fixed if we are unsure about the type of the array they're storing to
  3543. // (because it relies on profile data) and we weren't able to hoist the array check.
  3544. return;
  3545. }
  3546. Sym *sym;
  3547. IR::Opnd* opnd = origOpnd;
  3548. IR::ArrayRegOpnd *arrayOpnd;
  3549. switch(opnd->GetKind())
  3550. {
  3551. case IR::OpndKindIndir:
  3552. opnd = opnd->AsIndirOpnd()->GetBaseOpnd();
  3553. // fall-through
  3554. case IR::OpndKindReg:
  3555. {
  3556. IR::RegOpnd *const regOpnd = opnd->AsRegOpnd();
  3557. sym = regOpnd->m_sym;
  3558. arrayOpnd = regOpnd->IsArrayRegOpnd() ? regOpnd->AsArrayRegOpnd() : nullptr;
  3559. break;
  3560. }
  3561. case IR::OpndKindSym:
  3562. sym = opnd->AsSymOpnd()->m_sym;
  3563. if(!sym->IsPropertySym())
  3564. {
  3565. return;
  3566. }
  3567. arrayOpnd = nullptr;
  3568. break;
  3569. default:
  3570. return;
  3571. }
  3572. const ValueType valueType(opnd->GetValueType());
  3573. if(!valueType.IsAnyOptimizedArray())
  3574. {
  3575. return;
  3576. }
  3577. const bool isJsArray = valueType.IsArrayOrObjectWithArray();
  3578. Assert(!isJsArray == valueType.IsOptimizedTypedArray());
  3579. const bool noForwardImplicitCallUses = currentBlock->noImplicitCallUses->IsEmpty();
  3580. bool changeArray = isJsArray && !opnd->IsValueTypeFixed() && noForwardImplicitCallUses;
  3581. bool changeNativeArray =
  3582. isJsArray &&
  3583. !opnd->IsValueTypeFixed() &&
  3584. !valueType.HasVarElements() &&
  3585. currentBlock->noImplicitCallNativeArrayUses->IsEmpty();
  3586. bool changeNoMissingValues =
  3587. isJsArray &&
  3588. !opnd->IsValueTypeFixed() &&
  3589. valueType.HasNoMissingValues() &&
  3590. currentBlock->noImplicitCallNoMissingValuesUses->IsEmpty();
  3591. const bool noForwardJsArrayHeadSegmentSymUses = currentBlock->noImplicitCallJsArrayHeadSegmentSymUses->IsEmpty();
  3592. bool removeHeadSegmentSym = isJsArray && arrayOpnd && arrayOpnd->HeadSegmentSym() && noForwardJsArrayHeadSegmentSymUses;
  3593. bool removeHeadSegmentLengthSym =
  3594. arrayOpnd &&
  3595. arrayOpnd->HeadSegmentLengthSym() &&
  3596. (isJsArray ? noForwardJsArrayHeadSegmentSymUses : noForwardImplicitCallUses);
  3597. Assert(!isJsArray || !arrayOpnd || !arrayOpnd->LengthSym() || valueType.IsArray());
  3598. bool removeLengthSym =
  3599. isJsArray &&
  3600. arrayOpnd &&
  3601. arrayOpnd->LengthSym() &&
  3602. currentBlock->noImplicitCallArrayLengthSymUses->IsEmpty();
  3603. if(!(changeArray || changeNoMissingValues || changeNativeArray || removeHeadSegmentSym || removeHeadSegmentLengthSym))
  3604. {
  3605. return;
  3606. }
  3607. // We have a definitely-array value type for the base, but either implicit calls are not currently being disabled for
  3608. // legally using the value type as a definite array, or we are not currently bailing out upon creating a missing value
  3609. // for legally using the value type as a definite array with no missing values.
  3610. // For source opnds, ensure that a NoImplicitCallUses immediately precedes this instruction. Otherwise, convert the value
  3611. // type to an appropriate version so that the lowerer doesn't incorrectly treat it as it says.
  3612. if(opnd != opndOwnerInstr->GetDst())
  3613. {
  3614. if(isJsArray)
  3615. {
  3616. IR::Opnd *const checkedSrc =
  3617. FindNoImplicitCallUse(
  3618. instr,
  3619. opnd,
  3620. [&](IR::Opnd *const checkedSrc) -> bool
  3621. {
  3622. const ValueType checkedSrcValueType(checkedSrc->GetValueType());
  3623. return
  3624. checkedSrcValueType.IsLikelyObject() &&
  3625. checkedSrcValueType.GetObjectType() == valueType.GetObjectType();
  3626. });
  3627. if(checkedSrc)
  3628. {
  3629. // Implicit calls will be disabled to the point immediately before this instruction
  3630. changeArray = false;
  3631. const ValueType checkedSrcValueType(checkedSrc->GetValueType());
  3632. if(changeNativeArray &&
  3633. !checkedSrcValueType.HasVarElements() &&
  3634. checkedSrcValueType.HasIntElements() == valueType.HasIntElements())
  3635. {
  3636. // If necessary, instructions before this will bail out on converting a native array
  3637. changeNativeArray = false;
  3638. }
  3639. if(changeNoMissingValues && checkedSrcValueType.HasNoMissingValues())
  3640. {
  3641. // If necessary, instructions before this will bail out on creating a missing value
  3642. changeNoMissingValues = false;
  3643. }
  3644. if((removeHeadSegmentSym || removeHeadSegmentLengthSym || removeLengthSym) && checkedSrc->IsRegOpnd())
  3645. {
  3646. IR::RegOpnd *const checkedRegSrc = checkedSrc->AsRegOpnd();
  3647. if(checkedRegSrc->IsArrayRegOpnd())
  3648. {
  3649. IR::ArrayRegOpnd *const checkedArraySrc = checkedSrc->AsRegOpnd()->AsArrayRegOpnd();
  3650. if(removeHeadSegmentSym && checkedArraySrc->HeadSegmentSym() == arrayOpnd->HeadSegmentSym())
  3651. {
  3652. // If necessary, instructions before this will bail out upon invalidating head segment sym
  3653. removeHeadSegmentSym = false;
  3654. }
  3655. if(removeHeadSegmentLengthSym &&
  3656. checkedArraySrc->HeadSegmentLengthSym() == arrayOpnd->HeadSegmentLengthSym())
  3657. {
  3658. // If necessary, instructions before this will bail out upon invalidating head segment length sym
  3659. removeHeadSegmentLengthSym = false;
  3660. }
  3661. if(removeLengthSym && checkedArraySrc->LengthSym() == arrayOpnd->LengthSym())
  3662. {
  3663. // If necessary, instructions before this will bail out upon invalidating a length sym
  3664. removeLengthSym = false;
  3665. }
  3666. }
  3667. }
  3668. }
  3669. }
  3670. else
  3671. {
  3672. Assert(removeHeadSegmentLengthSym);
  3673. // A typed array's head segment length may be zeroed when the typed array's buffer is transferred to a web worker,
  3674. // so the head segment length sym use is included in a NoImplicitCallUses instruction. Since there are no forward
  3675. // uses of any head segment length syms, to allow removing the extracted head segment length
  3676. // load, the corresponding head segment length sym use in the NoImplicitCallUses instruction must also be
  3677. // removed.
  3678. IR::Opnd *const use =
  3679. FindNoImplicitCallUse(
  3680. instr,
  3681. arrayOpnd->HeadSegmentLengthSym(),
  3682. [&](IR::Opnd *const checkedSrc) -> bool
  3683. {
  3684. return checkedSrc->AsRegOpnd()->m_sym == arrayOpnd->HeadSegmentLengthSym();
  3685. });
  3686. if(use)
  3687. {
  3688. // Implicit calls will be disabled to the point immediately before this instruction
  3689. removeHeadSegmentLengthSym = false;
  3690. }
  3691. }
  3692. }
  3693. if(changeArray || changeNativeArray)
  3694. {
  3695. if(arrayOpnd)
  3696. {
  3697. opnd = arrayOpnd->CopyAsRegOpnd(opndOwnerInstr->m_func);
  3698. if (origOpnd->IsIndirOpnd())
  3699. {
  3700. origOpnd->AsIndirOpnd()->ReplaceBaseOpnd(opnd->AsRegOpnd());
  3701. }
  3702. else
  3703. {
  3704. opndOwnerInstr->Replace(arrayOpnd, opnd);
  3705. }
  3706. arrayOpnd = nullptr;
  3707. }
  3708. opnd->SetValueType(valueType.ToLikely());
  3709. }
  3710. else
  3711. {
  3712. if(changeNoMissingValues)
  3713. {
  3714. opnd->SetValueType(valueType.SetHasNoMissingValues(false));
  3715. }
  3716. if(removeHeadSegmentSym)
  3717. {
  3718. Assert(arrayOpnd);
  3719. arrayOpnd->RemoveHeadSegmentSym();
  3720. }
  3721. if(removeHeadSegmentLengthSym)
  3722. {
  3723. Assert(arrayOpnd);
  3724. arrayOpnd->RemoveHeadSegmentLengthSym();
  3725. }
  3726. if(removeLengthSym)
  3727. {
  3728. Assert(arrayOpnd);
  3729. arrayOpnd->RemoveLengthSym();
  3730. }
  3731. }
  3732. }
  3733. void
  3734. BackwardPass::UpdateArrayBailOutKind(IR::Instr *const instr)
  3735. {
  3736. Assert(!IsPrePass());
  3737. Assert(instr);
  3738. Assert(instr->HasBailOutInfo());
  3739. if ((instr->m_opcode != Js::OpCode::StElemI_A && instr->m_opcode != Js::OpCode::StElemI_A_Strict &&
  3740. instr->m_opcode != Js::OpCode::Memcopy && instr->m_opcode != Js::OpCode::Memset) ||
  3741. !instr->GetDst()->IsIndirOpnd())
  3742. {
  3743. return;
  3744. }
  3745. IR::RegOpnd *const baseOpnd = instr->GetDst()->AsIndirOpnd()->GetBaseOpnd();
  3746. const ValueType baseValueType(baseOpnd->GetValueType());
  3747. if(baseValueType.IsNotArrayOrObjectWithArray())
  3748. {
  3749. return;
  3750. }
  3751. IR::BailOutKind includeBailOutKinds = IR::BailOutInvalid;
  3752. if(!baseValueType.IsNotNativeArray() &&
  3753. (!baseValueType.IsLikelyNativeArray() || instr->GetSrc1()->IsVar()) &&
  3754. !currentBlock->noImplicitCallNativeArrayUses->IsEmpty())
  3755. {
  3756. // There is an upwards-exposed use of a native array. Since the array referenced by this instruction can be aliased,
  3757. // this instruction needs to bail out if it converts the native array even if this array specifically is not
  3758. // upwards-exposed.
  3759. includeBailOutKinds |= IR::BailOutConvertedNativeArray;
  3760. }
  3761. if(baseOpnd->IsArrayRegOpnd() && baseOpnd->AsArrayRegOpnd()->EliminatedUpperBoundCheck())
  3762. {
  3763. if(instr->extractedUpperBoundCheckWithoutHoisting && !currentBlock->noImplicitCallJsArrayHeadSegmentSymUses->IsEmpty())
  3764. {
  3765. // See comment below regarding head segment invalidation. A failed upper bound check usually means that it will
  3766. // invalidate the head segment length, so change the bailout kind on the upper bound check to have it bail out for
  3767. // the right reason. Even though the store may actually occur in a non-head segment, which would not invalidate the
  3768. // head segment or length, any store outside the head segment bounds causes head segment load elimination to be
  3769. // turned off for the store, because the segment structure of the array is not guaranteed to be the same every time.
  3770. IR::Instr *upperBoundCheck = this->globOpt->FindUpperBoundsCheckInstr(instr);
  3771. Assert(upperBoundCheck && upperBoundCheck != instr);
  3772. if(upperBoundCheck->GetBailOutKind() == IR::BailOutOnArrayAccessHelperCall)
  3773. {
  3774. upperBoundCheck->SetBailOutKind(IR::BailOutOnInvalidatedArrayHeadSegment);
  3775. }
  3776. else
  3777. {
  3778. Assert(upperBoundCheck->GetBailOutKind() == IR::BailOutOnFailedHoistedBoundCheck);
  3779. }
  3780. }
  3781. }
  3782. else
  3783. {
  3784. if(!currentBlock->noImplicitCallJsArrayHeadSegmentSymUses->IsEmpty())
  3785. {
  3786. // There is an upwards-exposed use of a segment sym. Since the head segment syms referenced by this instruction can
  3787. // be aliased, this instruction needs to bail out if it changes the segment syms it references even if the ones it
  3788. // references specifically are not upwards-exposed. This bailout kind also guarantees that this element store will
  3789. // not create missing values.
  3790. includeBailOutKinds |= IR::BailOutOnInvalidatedArrayHeadSegment;
  3791. }
  3792. else if(
  3793. !currentBlock->noImplicitCallNoMissingValuesUses->IsEmpty() &&
  3794. !(instr->GetBailOutKind() & IR::BailOutOnArrayAccessHelperCall))
  3795. {
  3796. // There is an upwards-exposed use of an array with no missing values. Since the array referenced by this
  3797. // instruction can be aliased, this instruction needs to bail out if it creates a missing value in the array even if
  3798. // this array specifically is not upwards-exposed.
  3799. includeBailOutKinds |= IR::BailOutOnMissingValue;
  3800. }
  3801. if(!baseValueType.IsNotArray() && !currentBlock->noImplicitCallArrayLengthSymUses->IsEmpty())
  3802. {
  3803. // There is an upwards-exposed use of a length sym. Since the length sym referenced by this instruction can be
  3804. // aliased, this instruction needs to bail out if it changes the length sym it references even if the ones it
  3805. // references specifically are not upwards-exposed.
  3806. includeBailOutKinds |= IR::BailOutOnInvalidatedArrayLength;
  3807. }
  3808. }
  3809. if(!includeBailOutKinds)
  3810. {
  3811. return;
  3812. }
  3813. Assert(!(includeBailOutKinds & ~IR::BailOutKindBits));
  3814. instr->SetBailOutKind(instr->GetBailOutKind() | includeBailOutKinds);
  3815. }
  3816. bool
  3817. BackwardPass::ProcessStackSymUse(StackSym * stackSym, BOOLEAN isNonByteCodeUse)
  3818. {
  3819. BasicBlock * block = this->currentBlock;
  3820. if (this->DoByteCodeUpwardExposedUsed())
  3821. {
  3822. if (!isNonByteCodeUse && stackSym->HasByteCodeRegSlot())
  3823. {
  3824. // Always track the sym use on the var sym.
  3825. StackSym * byteCodeUseSym = stackSym;
  3826. if (byteCodeUseSym->IsTypeSpec())
  3827. {
  3828. // It has to have a var version for byte code regs
  3829. byteCodeUseSym = byteCodeUseSym->GetVarEquivSym(nullptr);
  3830. }
  3831. block->byteCodeUpwardExposedUsed->Set(byteCodeUseSym->m_id);
  3832. #if DBG
  3833. // We can only track first level function stack syms right now
  3834. if (byteCodeUseSym->GetByteCodeFunc() == this->func)
  3835. {
  3836. Js::RegSlot byteCodeRegSlot = byteCodeUseSym->GetByteCodeRegSlot();
  3837. if (block->byteCodeRestoreSyms[byteCodeRegSlot] != byteCodeUseSym)
  3838. {
  3839. AssertMsg(block->byteCodeRestoreSyms[byteCodeRegSlot] == nullptr,
  3840. "Can't have two active lifetime for the same byte code register");
  3841. block->byteCodeRestoreSyms[byteCodeRegSlot] = byteCodeUseSym;
  3842. }
  3843. }
  3844. #endif
  3845. }
  3846. }
  3847. if(IsCollectionPass())
  3848. {
  3849. return true;
  3850. }
  3851. if (this->DoMarkTempObjects())
  3852. {
  3853. Assert((block->loop != nullptr) == block->tempObjectTracker->HasTempTransferDependencies());
  3854. block->tempObjectTracker->ProcessUse(stackSym, this);
  3855. }
  3856. #if DBG
  3857. if (this->DoMarkTempObjectVerify())
  3858. {
  3859. Assert((block->loop != nullptr) == block->tempObjectVerifyTracker->HasTempTransferDependencies());
  3860. block->tempObjectVerifyTracker->ProcessUse(stackSym, this);
  3861. }
  3862. #endif
  3863. return !!block->upwardExposedUses->TestAndSet(stackSym->m_id);
  3864. }
  3865. bool
  3866. BackwardPass::ProcessSymUse(Sym * sym, bool isRegOpndUse, BOOLEAN isNonByteCodeUse)
  3867. {
  3868. BasicBlock * block = this->currentBlock;
  3869. if (CanDeadStoreInstrForScopeObjRemoval(sym))
  3870. {
  3871. return false;
  3872. }
  3873. if (sym->IsPropertySym())
  3874. {
  3875. PropertySym * propertySym = sym->AsPropertySym();
  3876. ProcessStackSymUse(propertySym->m_stackSym, isNonByteCodeUse);
  3877. if(IsCollectionPass())
  3878. {
  3879. return true;
  3880. }
  3881. Assert((block->fieldHoistCandidates != nullptr) == this->DoFieldHoistCandidates());
  3882. if (block->fieldHoistCandidates && this->currentInstr->TransfersSrcValue())
  3883. {
  3884. // If the instruction doesn't transfer the src value to dst, it will not be copyprop'd
  3885. // So we can't hoist those.
  3886. block->fieldHoistCandidates->Set(propertySym->m_id);
  3887. }
  3888. if (this->DoDeadStoreSlots())
  3889. {
  3890. block->slotDeadStoreCandidates->Clear(propertySym->m_id);
  3891. }
  3892. if (tag == Js::BackwardPhase)
  3893. {
  3894. // Backward phase tracks liveness of fields to tell GlobOpt where we may need bailout.
  3895. return this->ProcessPropertySymUse(propertySym);
  3896. }
  3897. else
  3898. {
  3899. // Dead-store phase tracks copy propped syms, so it only cares about ByteCodeUses we inserted,
  3900. // not live fields.
  3901. return false;
  3902. }
  3903. }
  3904. StackSym * stackSym = sym->AsStackSym();
  3905. bool isUsed = ProcessStackSymUse(stackSym, isNonByteCodeUse);
  3906. if (!IsCollectionPass() && isRegOpndUse && this->DoMarkTempNumbers())
  3907. {
  3908. // Collect mark temp number information
  3909. Assert((block->loop != nullptr) == block->tempNumberTracker->HasTempTransferDependencies());
  3910. block->tempNumberTracker->ProcessUse(stackSym, this);
  3911. }
  3912. return isUsed;
  3913. }
  3914. bool
  3915. BackwardPass::MayPropertyBeWrittenTo(Js::PropertyId propertyId)
  3916. {
  3917. return this->func->anyPropertyMayBeWrittenTo ||
  3918. (this->func->propertiesWrittenTo != nullptr && this->func->propertiesWrittenTo->ContainsKey(propertyId));
  3919. }
  3920. void
  3921. BackwardPass::ProcessPropertySymOpndUse(IR::PropertySymOpnd * opnd)
  3922. {
  3923. // If this operand doesn't participate in the type check sequence it's a pass-through.
  3924. // We will not set any bits on the operand and we will ignore them when lowering.
  3925. if (!opnd->IsTypeCheckSeqCandidate())
  3926. {
  3927. return;
  3928. }
  3929. AssertMsg(opnd->HasObjectTypeSym(), "Optimized property sym operand without a type sym?");
  3930. SymID typeSymId = opnd->GetObjectTypeSym()->m_id;
  3931. BasicBlock * block = this->currentBlock;
  3932. if (this->tag == Js::BackwardPhase)
  3933. {
  3934. // In the backward phase, we have no availability info, and we're trying to see
  3935. // where there are live fields so we can decide where to put bailouts.
  3936. Assert(opnd->MayNeedTypeCheckProtection());
  3937. block->upwardExposedFields->Set(typeSymId);
  3938. TrackObjTypeSpecWriteGuards(opnd, block);
  3939. }
  3940. else
  3941. {
  3942. // In the dead-store phase, we're trying to see where the lowered code needs to make sure to check
  3943. // types for downstream load/stores. We're also setting up the upward-exposed uses at loop headers
  3944. // so register allocation will be correct.
  3945. Assert(opnd->MayNeedTypeCheckProtection());
  3946. const bool isStore = opnd == this->currentInstr->GetDst();
  3947. // Note that we don't touch upwardExposedUses here.
  3948. if (opnd->IsTypeAvailable())
  3949. {
  3950. opnd->SetTypeDead(!block->upwardExposedFields->TestAndSet(typeSymId));
  3951. if (opnd->IsTypeChecked() && opnd->IsObjectHeaderInlined())
  3952. {
  3953. // The object's type must not change in a way that changes the layout.
  3954. // If we see a StFld with a type check bailout between here and the type check that guards this
  3955. // property, we must not dead-store the StFld's type check bailout, even if that operand's type appears
  3956. // dead, because that object may alias this one.
  3957. BVSparse<JitArenaAllocator>* bv = block->typesNeedingKnownObjectLayout;
  3958. if (bv == nullptr)
  3959. {
  3960. bv = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  3961. block->typesNeedingKnownObjectLayout = bv;
  3962. }
  3963. bv->Set(typeSymId);
  3964. }
  3965. }
  3966. else
  3967. {
  3968. opnd->SetTypeDead(
  3969. !block->upwardExposedFields->TestAndClear(typeSymId) &&
  3970. (
  3971. // Don't set the type dead if this is a store that may change the layout in a way that invalidates
  3972. // optimized load/stores downstream. Leave it non-dead in that case so the type check bailout
  3973. // is preserved and so that Lower will generate the bailout properly.
  3974. !isStore ||
  3975. !block->typesNeedingKnownObjectLayout ||
  3976. block->typesNeedingKnownObjectLayout->IsEmpty()
  3977. )
  3978. );
  3979. BVSparse<JitArenaAllocator>* bv = block->typesNeedingKnownObjectLayout;
  3980. if (bv != nullptr)
  3981. {
  3982. bv->Clear(typeSymId);
  3983. }
  3984. }
  3985. bool mayNeedTypeTransition = true;
  3986. if (!opnd->HasTypeMismatch() && func->DoGlobOpt())
  3987. {
  3988. mayNeedTypeTransition = !isStore;
  3989. }
  3990. if (mayNeedTypeTransition &&
  3991. !this->IsPrePass() &&
  3992. !this->currentInstr->HasBailOutInfo() &&
  3993. (opnd->NeedsPrimaryTypeCheck() ||
  3994. opnd->NeedsLocalTypeCheck() ||
  3995. opnd->NeedsLoadFromProtoTypeCheck()))
  3996. {
  3997. // This is a "checked" opnd that nevertheless will have some kind of type check generated for it.
  3998. // (Typical case is a load from prototype with no upstream guard.)
  3999. // If the type check fails, we will call a helper, which will require that the type be correct here.
  4000. // Final type can't be pushed up past this point. Do whatever type transition is required.
  4001. if (block->stackSymToFinalType != nullptr)
  4002. {
  4003. StackSym *baseSym = opnd->GetObjectSym();
  4004. AddPropertyCacheBucket *pBucket = block->stackSymToFinalType->Get(baseSym->m_id);
  4005. if (pBucket &&
  4006. pBucket->GetFinalType() != nullptr &&
  4007. pBucket->GetFinalType() != pBucket->GetInitialType())
  4008. {
  4009. this->InsertTypeTransition(this->currentInstr->m_next, baseSym, pBucket);
  4010. pBucket->SetFinalType(pBucket->GetInitialType());
  4011. }
  4012. }
  4013. }
  4014. if (!opnd->HasTypeMismatch() && func->DoGlobOpt())
  4015. {
  4016. // Do this after the above code, as the value of the final type may change there.
  4017. TrackAddPropertyTypes(opnd, block);
  4018. }
  4019. TrackObjTypeSpecProperties(opnd, block);
  4020. TrackObjTypeSpecWriteGuards(opnd, block);
  4021. }
  4022. }
  4023. void
  4024. BackwardPass::TrackObjTypeSpecProperties(IR::PropertySymOpnd *opnd, BasicBlock *block)
  4025. {
  4026. Assert(tag == Js::DeadStorePhase);
  4027. Assert(opnd->IsTypeCheckSeqCandidate());
  4028. // Now that we're in the dead store pass and we know definitively which operations will have a type
  4029. // check and which are protected by an upstream type check, we can push the lists of guarded properties
  4030. // up the flow graph and drop them on the type checks for the corresponding object symbol.
  4031. if (opnd->IsTypeCheckSeqParticipant())
  4032. {
  4033. // Add this operation to the list of guarded operations for this object symbol.
  4034. HashTable<ObjTypeGuardBucket>* stackSymToGuardedProperties = block->stackSymToGuardedProperties;
  4035. if (stackSymToGuardedProperties == nullptr)
  4036. {
  4037. stackSymToGuardedProperties = HashTable<ObjTypeGuardBucket>::New(this->tempAlloc, 8);
  4038. block->stackSymToGuardedProperties = stackSymToGuardedProperties;
  4039. }
  4040. StackSym* objSym = opnd->GetObjectSym();
  4041. ObjTypeGuardBucket* bucket = stackSymToGuardedProperties->FindOrInsertNew(objSym->m_id);
  4042. BVSparse<JitArenaAllocator>* guardedPropertyOps = bucket->GetGuardedPropertyOps();
  4043. if (guardedPropertyOps == nullptr)
  4044. {
  4045. // The bit vectors we push around the flow graph only need to live as long as this phase.
  4046. guardedPropertyOps = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  4047. bucket->SetGuardedPropertyOps(guardedPropertyOps);
  4048. }
  4049. #if DBG
  4050. FOREACH_BITSET_IN_SPARSEBV(propOpId, guardedPropertyOps)
  4051. {
  4052. ObjTypeSpecFldInfo* existingFldInfo = this->func->GetGlobalObjTypeSpecFldInfo(propOpId);
  4053. Assert(existingFldInfo != nullptr);
  4054. if (existingFldInfo->GetPropertyId() != opnd->GetPropertyId())
  4055. {
  4056. continue;
  4057. }
  4058. // It would be very nice to assert that the info we have for this property matches all properties guarded thus far.
  4059. // Unfortunately, in some cases of object pointer copy propagation into a loop, we may end up with conflicting
  4060. // information for the same property. We simply ignore the conflict and emit an equivalent type check, which
  4061. // will attempt to check for one property on two different slots, and obviously fail. Thus we may have a
  4062. // guaranteed bailout, but we'll simply re-JIT with equivalent object type spec disabled. To avoid this
  4063. // issue altogether, we would need to track the set of guarded properties along with the type value in the
  4064. // forward pass, and when a conflict is detected either not optimize the offending instruction, or correct
  4065. // its information based on the info from the property in the type value info.
  4066. //Assert(!existingFldInfo->IsPoly() || !opnd->IsPoly() || GlobOpt::AreTypeSetsIdentical(existingFldInfo->GetEquivalentTypeSet(), opnd->GetEquivalentTypeSet()));
  4067. //Assert(existingFldInfo->GetSlotIndex() == opnd->GetSlotIndex());
  4068. if (PHASE_TRACE(Js::EquivObjTypeSpecPhase, this->func) && !JITManager::GetJITManager()->IsJITServer())
  4069. {
  4070. if (existingFldInfo->IsPoly() && opnd->IsPoly() &&
  4071. (!GlobOpt::AreTypeSetsIdentical(existingFldInfo->GetEquivalentTypeSet(), opnd->GetEquivalentTypeSet()) ||
  4072. (existingFldInfo->GetSlotIndex() != opnd->GetSlotIndex())))
  4073. {
  4074. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  4075. Output::Print(_u("EquivObjTypeSpec: top function %s (%s): duplicate property clash on %s(#%d) on operation %u \n"),
  4076. this->func->GetJITFunctionBody()->GetDisplayName(), this->func->GetDebugNumberSet(debugStringBuffer),
  4077. this->func->GetInProcThreadContext()->GetPropertyRecord(opnd->GetPropertyId())->GetBuffer(), opnd->GetPropertyId(), opnd->GetObjTypeSpecFldId());
  4078. Output::Flush();
  4079. }
  4080. }
  4081. }
  4082. NEXT_BITSET_IN_SPARSEBV
  4083. #endif
  4084. bucket->AddToGuardedPropertyOps(opnd->GetObjTypeSpecFldId());
  4085. if (opnd->NeedsMonoCheck())
  4086. {
  4087. Assert(opnd->IsMono());
  4088. JITTypeHolder monoGuardType = opnd->IsInitialTypeChecked() ? opnd->GetInitialType() : opnd->GetType();
  4089. bucket->SetMonoGuardType(monoGuardType);
  4090. }
  4091. if (opnd->NeedsPrimaryTypeCheck())
  4092. {
  4093. // Grab the guarded properties which match this type check with respect to polymorphism and drop them
  4094. // on the operand. Only equivalent type checks can protect polymorphic properties to avoid a case where
  4095. // we have 1) a cache with type set {t1, t2} and property a, followed by 2) a cache with type t3 and
  4096. // property b, and 3) a cache with type set {t1, t2} and property c, where the slot index of property c
  4097. // on t1 and t2 is different than on t3. If cache 2 were to protect property c it would not verify that
  4098. // it resides on the correct slot for cache 3. Yes, an equivalent type check could protect monomorphic
  4099. // properties, but it would then unnecessarily verify their equivalence on the slow path.
  4100. // Also, make sure the guarded properties on the operand are allocated from the func's allocator to
  4101. // persists until lowering.
  4102. Assert(guardedPropertyOps != nullptr);
  4103. opnd->EnsureGuardedPropOps(this->func->m_alloc);
  4104. opnd->AddGuardedPropOps(guardedPropertyOps);
  4105. if (this->currentInstr->HasTypeCheckBailOut())
  4106. {
  4107. // Stop pushing the mono guard type up if it is being checked here.
  4108. if (bucket->NeedsMonoCheck())
  4109. {
  4110. if (this->currentInstr->HasEquivalentTypeCheckBailOut())
  4111. {
  4112. // Some instr protected by this one requires a monomorphic type check. (E.g., final type opt,
  4113. // fixed field not loaded from prototype.) Note the IsTypeAvailable test above: only do this at
  4114. // the initial type check that protects this path.
  4115. opnd->SetMonoGuardType(bucket->GetMonoGuardType());
  4116. this->currentInstr->ChangeEquivalentToMonoTypeCheckBailOut();
  4117. }
  4118. bucket->SetMonoGuardType(nullptr);
  4119. }
  4120. if (!opnd->IsTypeAvailable())
  4121. {
  4122. // Stop tracking the guarded properties if there's not another type check upstream.
  4123. bucket->SetGuardedPropertyOps(nullptr);
  4124. JitAdelete(this->tempAlloc, guardedPropertyOps);
  4125. block->stackSymToGuardedProperties->Clear(objSym->m_id);
  4126. }
  4127. }
  4128. #if DBG
  4129. {
  4130. // If there is no upstream type check that is live and could protect guarded properties, we better
  4131. // not have any properties remaining.
  4132. ObjTypeGuardBucket* objTypeGuardBucket = block->stackSymToGuardedProperties->Get(opnd->GetObjectSym()->m_id);
  4133. Assert(opnd->IsTypeAvailable() || objTypeGuardBucket == nullptr || objTypeGuardBucket->GetGuardedPropertyOps()->IsEmpty());
  4134. }
  4135. #endif
  4136. }
  4137. }
  4138. else if (opnd->NeedsLocalTypeCheck())
  4139. {
  4140. opnd->EnsureGuardedPropOps(this->func->m_alloc);
  4141. opnd->SetGuardedPropOp(opnd->GetObjTypeSpecFldId());
  4142. }
  4143. }
  4144. void
  4145. BackwardPass::TrackObjTypeSpecWriteGuards(IR::PropertySymOpnd *opnd, BasicBlock *block)
  4146. {
  4147. // TODO (ObjTypeSpec): Move write guard tracking to the forward pass, by recording on the type value
  4148. // which property IDs have been written since the last type check. This will result in more accurate
  4149. // tracking in cases when object pointer copy prop kicks in.
  4150. if (this->tag == Js::BackwardPhase)
  4151. {
  4152. // If this operation may need a write guard (load from proto or fixed field check) then add its
  4153. // write guard symbol to the map for this object. If it remains live (hasn't been written to)
  4154. // until the type check upstream, it will get recorded there so that the type check can be registered
  4155. // for invalidation on this property used in this operation.
  4156. // (ObjTypeSpec): Consider supporting polymorphic write guards as well. We can't currently distinguish between mono and
  4157. // poly write guards, and a type check can only protect operations matching with respect to polymorphism (see
  4158. // BackwardPass::TrackObjTypeSpecProperties for details), so for now we only target monomorphic operations.
  4159. if (opnd->IsMono() && opnd->MayNeedWriteGuardProtection())
  4160. {
  4161. if (block->stackSymToWriteGuardsMap == nullptr)
  4162. {
  4163. block->stackSymToWriteGuardsMap = HashTable<ObjWriteGuardBucket>::New(this->tempAlloc, 8);
  4164. }
  4165. ObjWriteGuardBucket* bucket = block->stackSymToWriteGuardsMap->FindOrInsertNew(opnd->GetObjectSym()->m_id);
  4166. BVSparse<JitArenaAllocator>* writeGuards = bucket->GetWriteGuards();
  4167. if (writeGuards == nullptr)
  4168. {
  4169. // The bit vectors we push around the flow graph only need to live as long as this phase.
  4170. writeGuards = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  4171. bucket->SetWriteGuards(writeGuards);
  4172. }
  4173. PropertySym *propertySym = opnd->m_sym->AsPropertySym();
  4174. Assert(propertySym->m_writeGuardSym != nullptr);
  4175. SymID writeGuardSymId = propertySym->m_writeGuardSym->m_id;
  4176. writeGuards->Set(writeGuardSymId);
  4177. }
  4178. // Record any live (upward exposed) write guards on this operation, if this operation may end up with
  4179. // a type check. If we ultimately don't need a type check here, we will simply ignore the guards, because
  4180. // an earlier type check will protect them.
  4181. if (!IsPrePass() && opnd->IsMono() && !opnd->IsTypeDead())
  4182. {
  4183. Assert(opnd->GetWriteGuards() == nullptr);
  4184. if (block->stackSymToWriteGuardsMap != nullptr)
  4185. {
  4186. ObjWriteGuardBucket* bucket = block->stackSymToWriteGuardsMap->Get(opnd->GetObjectSym()->m_id);
  4187. if (bucket != nullptr)
  4188. {
  4189. // Get all the write guards associated with this object sym and filter them down to those that
  4190. // are upward exposed. If we end up emitting a type check for this instruction, we will create
  4191. // a type property guard registered for all guarded proto properties and we will set the write
  4192. // guard syms live during forward pass, such that we can avoid unnecessary write guard type
  4193. // checks and bailouts on every proto property (as long as it hasn't been written to since the
  4194. // primary type check).
  4195. auto writeGuards = bucket->GetWriteGuards()->CopyNew(this->func->m_alloc);
  4196. writeGuards->And(block->upwardExposedFields);
  4197. opnd->SetWriteGuards(writeGuards);
  4198. }
  4199. }
  4200. }
  4201. }
  4202. else
  4203. {
  4204. // If we know this property has never been written to in this function (either on this object or any
  4205. // of its aliases) we don't need the local type check.
  4206. if (opnd->MayNeedWriteGuardProtection() && !opnd->IsWriteGuardChecked() && !MayPropertyBeWrittenTo(opnd->GetPropertyId()))
  4207. {
  4208. opnd->SetWriteGuardChecked(true);
  4209. }
  4210. // If we don't need a primary type check here let's clear the write guards. The primary type check upstream will
  4211. // register the type check for the corresponding properties.
  4212. if (!IsPrePass() && !opnd->NeedsPrimaryTypeCheck())
  4213. {
  4214. opnd->ClearWriteGuards();
  4215. }
  4216. }
  4217. }
  4218. void
  4219. BackwardPass::TrackAddPropertyTypes(IR::PropertySymOpnd *opnd, BasicBlock *block)
  4220. {
  4221. // Do the work of objtypespec add-property opt even if it's disabled by PHASE option, so that we have
  4222. // the dataflow info that can be inspected.
  4223. Assert(this->tag == Js::DeadStorePhase);
  4224. Assert(opnd->IsMono() || opnd->HasEquivalentTypeSet());
  4225. JITTypeHolder typeWithProperty = opnd->IsMono() ? opnd->GetType() : opnd->GetFirstEquivalentType();
  4226. JITTypeHolder typeWithoutProperty = opnd->HasInitialType() ? opnd->GetInitialType() : JITTypeHolder(nullptr);
  4227. if (typeWithoutProperty == nullptr ||
  4228. typeWithProperty == typeWithoutProperty ||
  4229. (opnd->IsTypeChecked() && !opnd->IsInitialTypeChecked()))
  4230. {
  4231. if (!this->IsPrePass() && block->stackSymToFinalType != nullptr && !this->currentInstr->HasBailOutInfo())
  4232. {
  4233. PropertySym *propertySym = opnd->m_sym->AsPropertySym();
  4234. AddPropertyCacheBucket *pBucket =
  4235. block->stackSymToFinalType->Get(propertySym->m_stackSym->m_id);
  4236. if (pBucket && pBucket->GetFinalType() != nullptr && pBucket->GetInitialType() != pBucket->GetFinalType())
  4237. {
  4238. opnd->SetFinalType(pBucket->GetFinalType());
  4239. }
  4240. }
  4241. return;
  4242. }
  4243. #if DBG
  4244. Assert(typeWithProperty != nullptr);
  4245. const JITTypeHandler * typeWithoutPropertyTypeHandler = typeWithoutProperty->GetTypeHandler();
  4246. const JITTypeHandler * typeWithPropertyTypeHandler = typeWithProperty->GetTypeHandler();
  4247. // TODO: OOP JIT, reenable assert
  4248. //Assert(typeWithoutPropertyTypeHandler->GetPropertyCount() + 1 == typeWithPropertyTypeHandler->GetPropertyCount());
  4249. AssertMsg(JITTypeHandler::IsTypeHandlerCompatibleForObjectHeaderInlining(typeWithoutPropertyTypeHandler, typeWithPropertyTypeHandler),
  4250. "TypeHandlers are not compatible for transition?");
  4251. Assert(typeWithoutPropertyTypeHandler->GetSlotCapacity() <= typeWithPropertyTypeHandler->GetSlotCapacity());
  4252. #endif
  4253. // If there's already a final type for this instance, record it on the operand.
  4254. // If not, start tracking it.
  4255. if (block->stackSymToFinalType == nullptr)
  4256. {
  4257. block->stackSymToFinalType = HashTable<AddPropertyCacheBucket>::New(this->tempAlloc, 8);
  4258. }
  4259. // Find or create the type-tracking record for this instance in this block.
  4260. PropertySym *propertySym = opnd->m_sym->AsPropertySym();
  4261. AddPropertyCacheBucket *pBucket =
  4262. block->stackSymToFinalType->FindOrInsertNew(propertySym->m_stackSym->m_id);
  4263. JITTypeHolder finalType(nullptr);
  4264. #if DBG
  4265. JITTypeHolder deadStoreUnavailableFinalType(nullptr);
  4266. #endif
  4267. if (pBucket->GetInitialType() == nullptr || opnd->GetType() != pBucket->GetInitialType())
  4268. {
  4269. #if DBG
  4270. if (opnd->GetType() == pBucket->deadStoreUnavailableInitialType)
  4271. {
  4272. deadStoreUnavailableFinalType = pBucket->deadStoreUnavailableFinalType;
  4273. }
  4274. #endif
  4275. // No info found, or the info was bad, so initialize it from this cache.
  4276. finalType = opnd->GetType();
  4277. pBucket->SetFinalType(finalType);
  4278. }
  4279. else
  4280. {
  4281. // Match: The type we push upward is now the typeWithoutProperty at this point,
  4282. // and the final type is the one we've been tracking.
  4283. finalType = pBucket->GetFinalType();
  4284. #if DBG
  4285. deadStoreUnavailableFinalType = pBucket->deadStoreUnavailableFinalType;
  4286. #endif
  4287. }
  4288. pBucket->SetInitialType(typeWithoutProperty);
  4289. if (!PHASE_OFF(Js::ObjTypeSpecStorePhase, this->func))
  4290. {
  4291. #if DBG
  4292. // We may regress in this case:
  4293. // if (b)
  4294. // t1 = {};
  4295. // o = t1;
  4296. // o.x =
  4297. // else
  4298. // t2 = {};
  4299. // o = t2;
  4300. // o.x =
  4301. // o.y =
  4302. //
  4303. // 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.
  4304. // 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
  4305. // respectively, thus regression the final type. However, in both cases, the types of t1 and t2 are dead anyways.
  4306. //
  4307. // 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
  4308. if (!opnd->IsTypeDead())
  4309. {
  4310. // This is the type that would have been propagated if we didn't kill it because the type isn't available
  4311. JITTypeHolder checkFinalType = deadStoreUnavailableFinalType != nullptr ? deadStoreUnavailableFinalType : finalType;
  4312. if (opnd->HasFinalType() && opnd->GetFinalType() != checkFinalType)
  4313. {
  4314. // Final type discovery must be progressively better (unless we kill it in the deadstore pass
  4315. // when the type is not available during the forward pass)
  4316. const JITTypeHandler * oldFinalTypeHandler = opnd->GetFinalType()->GetTypeHandler();
  4317. const JITTypeHandler * checkFinalTypeHandler = checkFinalType->GetTypeHandler();
  4318. // TODO: OOP JIT, enable assert
  4319. //Assert(oldFinalTypeHandler->GetPropertyCount() < checkFinalTypeHandler->GetPropertyCount());
  4320. AssertMsg(JITTypeHandler::IsTypeHandlerCompatibleForObjectHeaderInlining(oldFinalTypeHandler, checkFinalTypeHandler),
  4321. "TypeHandlers should be compatible for transition.");
  4322. Assert(oldFinalTypeHandler->GetSlotCapacity() <= checkFinalTypeHandler->GetSlotCapacity());
  4323. }
  4324. }
  4325. #endif
  4326. Assert(opnd->IsBeingAdded());
  4327. if (!this->IsPrePass())
  4328. {
  4329. opnd->SetFinalType(finalType);
  4330. }
  4331. if (!opnd->IsTypeChecked())
  4332. {
  4333. // Transition from initial to final type will only happen at type check points.
  4334. if (opnd->IsTypeAvailable())
  4335. {
  4336. pBucket->SetFinalType(pBucket->GetInitialType());
  4337. }
  4338. }
  4339. }
  4340. #if DBG_DUMP
  4341. if (PHASE_TRACE(Js::ObjTypeSpecStorePhase, this->func))
  4342. {
  4343. Output::Print(_u("ObjTypeSpecStore: "));
  4344. this->currentInstr->Dump();
  4345. pBucket->Dump();
  4346. }
  4347. #endif
  4348. // In the dead-store pass, we have forward information that tells us whether a "final type"
  4349. // reached this point from an earlier store. If it didn't (i.e., it's not available here),
  4350. // remove it from the backward map so that upstream stores will use the final type that is
  4351. // live there. (This avoids unnecessary bailouts in cases where the final type is only live
  4352. // on one branch of an "if", a case that the initial backward pass can't detect.)
  4353. // An example:
  4354. // if (cond)
  4355. // o.x =
  4356. // o.y =
  4357. if (!opnd->IsTypeAvailable())
  4358. {
  4359. #if DBG
  4360. pBucket->deadStoreUnavailableInitialType = pBucket->GetInitialType();
  4361. if (pBucket->deadStoreUnavailableFinalType == nullptr)
  4362. {
  4363. pBucket->deadStoreUnavailableFinalType = pBucket->GetFinalType();
  4364. }
  4365. pBucket->SetInitialType(nullptr);
  4366. pBucket->SetFinalType(nullptr);
  4367. #else
  4368. block->stackSymToFinalType->Clear(propertySym->m_stackSym->m_id);
  4369. #endif
  4370. }
  4371. }
  4372. void
  4373. BackwardPass::InsertTypeTransition(IR::Instr *instrInsertBefore, int symId, AddPropertyCacheBucket *data)
  4374. {
  4375. StackSym *objSym = this->func->m_symTable->FindStackSym(symId);
  4376. Assert(objSym);
  4377. this->InsertTypeTransition(instrInsertBefore, objSym, data);
  4378. }
  4379. void
  4380. BackwardPass::InsertTypeTransition(IR::Instr *instrInsertBefore, StackSym *objSym, AddPropertyCacheBucket *data)
  4381. {
  4382. IR::RegOpnd *baseOpnd = IR::RegOpnd::New(objSym, TyMachReg, this->func);
  4383. baseOpnd->SetIsJITOptimizedReg(true);
  4384. IR::AddrOpnd *initialTypeOpnd =
  4385. IR::AddrOpnd::New(data->GetInitialType()->GetAddr(), IR::AddrOpndKindDynamicType, this->func);
  4386. initialTypeOpnd->m_metadata = data->GetInitialType().t;
  4387. IR::AddrOpnd *finalTypeOpnd =
  4388. IR::AddrOpnd::New(data->GetFinalType()->GetAddr(), IR::AddrOpndKindDynamicType, this->func);
  4389. finalTypeOpnd->m_metadata = data->GetFinalType().t;
  4390. IR::Instr *adjustTypeInstr =
  4391. IR::Instr::New(Js::OpCode::AdjustObjType, finalTypeOpnd, baseOpnd, initialTypeOpnd, this->func);
  4392. instrInsertBefore->InsertBefore(adjustTypeInstr);
  4393. }
  4394. void
  4395. BackwardPass::InsertTypeTransitionAfterInstr(IR::Instr *instr, int symId, AddPropertyCacheBucket *data)
  4396. {
  4397. if (!this->IsPrePass())
  4398. {
  4399. // Transition to the final type if we don't bail out.
  4400. if (instr->EndsBasicBlock())
  4401. {
  4402. // The instr with the bailout is something like a branch that may not fall through.
  4403. // Insert the transitions instead at the beginning of each successor block.
  4404. this->InsertTypeTransitionsAtPriorSuccessors(this->currentBlock, nullptr, symId, data);
  4405. }
  4406. else
  4407. {
  4408. this->InsertTypeTransition(instr->m_next, symId, data);
  4409. }
  4410. }
  4411. // Note: we could probably clear this entry out of the table, but I don't know
  4412. // whether it's worth it, because it's likely coming right back.
  4413. data->SetFinalType(data->GetInitialType());
  4414. }
  4415. void
  4416. BackwardPass::InsertTypeTransitionAtBlock(BasicBlock *block, int symId, AddPropertyCacheBucket *data)
  4417. {
  4418. bool inserted = false;
  4419. FOREACH_INSTR_IN_BLOCK(instr, block)
  4420. {
  4421. if (instr->IsRealInstr())
  4422. {
  4423. // Check for pre-existing type transition. There may be more than one AdjustObjType here,
  4424. // so look at them all.
  4425. if (instr->m_opcode == Js::OpCode::AdjustObjType)
  4426. {
  4427. if (instr->GetSrc1()->AsRegOpnd()->m_sym->m_id == (SymID)symId)
  4428. {
  4429. // This symbol already has a type transition at this point.
  4430. // It *must* be doing the same transition we're already trying to do.
  4431. Assert((intptr_t)instr->GetDst()->AsAddrOpnd()->m_address == data->GetFinalType()->GetAddr() &&
  4432. (intptr_t)instr->GetSrc2()->AsAddrOpnd()->m_address == data->GetInitialType()->GetAddr());
  4433. // Nothing to do.
  4434. return;
  4435. }
  4436. }
  4437. else
  4438. {
  4439. this->InsertTypeTransition(instr, symId, data);
  4440. inserted = true;
  4441. break;
  4442. }
  4443. }
  4444. }
  4445. NEXT_INSTR_IN_BLOCK;
  4446. if (!inserted)
  4447. {
  4448. Assert(block->GetLastInstr()->m_next);
  4449. this->InsertTypeTransition(block->GetLastInstr()->m_next, symId, data);
  4450. }
  4451. }
  4452. void
  4453. BackwardPass::InsertTypeTransitionsAtPriorSuccessors(
  4454. BasicBlock *block,
  4455. BasicBlock *blockSucc,
  4456. int symId,
  4457. AddPropertyCacheBucket *data)
  4458. {
  4459. // For each successor of block prior to blockSucc, adjust the type.
  4460. FOREACH_SUCCESSOR_BLOCK(blockFix, block)
  4461. {
  4462. if (blockFix == blockSucc)
  4463. {
  4464. return;
  4465. }
  4466. this->InsertTypeTransitionAtBlock(blockFix, symId, data);
  4467. }
  4468. NEXT_SUCCESSOR_BLOCK;
  4469. }
  4470. void
  4471. BackwardPass::InsertTypeTransitionsAtPotentialKills()
  4472. {
  4473. // Final types can't be pushed up past certain instructions.
  4474. IR::Instr *instr = this->currentInstr;
  4475. if (instr->HasBailOutInfo() || instr->m_opcode == Js::OpCode::UpdateNewScObjectCache)
  4476. {
  4477. // Final types can't be pushed up past a bailout point.
  4478. // Insert any transitions called for by the current state of add-property buckets.
  4479. // Also do this for ctor cache updates, to avoid putting a type in the ctor cache that extends past
  4480. // the end of the ctor that the cache covers.
  4481. this->ForEachAddPropertyCacheBucket([&](int symId, AddPropertyCacheBucket *data)->bool {
  4482. this->InsertTypeTransitionAfterInstr(instr, symId, data);
  4483. return false;
  4484. });
  4485. }
  4486. else
  4487. {
  4488. // If this is a load/store that expects an object-header-inlined type, don't push another sym's transition from
  4489. // object-header-inlined to non-object-header-inlined type past it, because the two syms may be aliases.
  4490. IR::PropertySymOpnd *propertySymOpnd = instr->GetPropertySymOpnd();
  4491. if (propertySymOpnd && propertySymOpnd->IsObjectHeaderInlined())
  4492. {
  4493. SymID opndId = propertySymOpnd->m_sym->AsPropertySym()->m_stackSym->m_id;
  4494. this->ForEachAddPropertyCacheBucket([&](int symId, AddPropertyCacheBucket *data)->bool {
  4495. if ((SymID)symId == opndId)
  4496. {
  4497. // This is the sym we're tracking. No aliasing to worry about.
  4498. return false;
  4499. }
  4500. if (propertySymOpnd->IsMono() && data->GetInitialType() != propertySymOpnd->GetType())
  4501. {
  4502. // Type mismatch in a monomorphic case -- no aliasing.
  4503. return false;
  4504. }
  4505. if (this->TransitionUndoesObjectHeaderInlining(data))
  4506. {
  4507. // We're transitioning from inlined to non-inlined, so we can't push it up any farther.
  4508. this->InsertTypeTransitionAfterInstr(instr, symId, data);
  4509. }
  4510. return false;
  4511. });
  4512. }
  4513. }
  4514. }
  4515. template<class Fn>
  4516. void
  4517. BackwardPass::ForEachAddPropertyCacheBucket(Fn fn)
  4518. {
  4519. BasicBlock *block = this->currentBlock;
  4520. if (block->stackSymToFinalType == nullptr)
  4521. {
  4522. return;
  4523. }
  4524. FOREACH_HASHTABLE_ENTRY(AddPropertyCacheBucket, bucket, block->stackSymToFinalType)
  4525. {
  4526. AddPropertyCacheBucket *data = &bucket.element;
  4527. if (data->GetInitialType() != nullptr &&
  4528. data->GetInitialType() != data->GetFinalType())
  4529. {
  4530. bool done = fn(bucket.value, data);
  4531. if (done)
  4532. {
  4533. break;
  4534. }
  4535. }
  4536. }
  4537. NEXT_HASHTABLE_ENTRY;
  4538. }
  4539. bool
  4540. BackwardPass::TransitionUndoesObjectHeaderInlining(AddPropertyCacheBucket *data) const
  4541. {
  4542. JITTypeHolder type = data->GetInitialType();
  4543. if (type == nullptr || !Js::DynamicType::Is(type->GetTypeId()))
  4544. {
  4545. return false;
  4546. }
  4547. if (!type->GetTypeHandler()->IsObjectHeaderInlinedTypeHandler())
  4548. {
  4549. return false;
  4550. }
  4551. type = data->GetFinalType();
  4552. if (type == nullptr || !Js::DynamicType::Is(type->GetTypeId()))
  4553. {
  4554. return false;
  4555. }
  4556. return !type->GetTypeHandler()->IsObjectHeaderInlinedTypeHandler();
  4557. }
  4558. void
  4559. BackwardPass::CollectCloneStrCandidate(IR::Opnd * opnd)
  4560. {
  4561. IR::RegOpnd *regOpnd = opnd->AsRegOpnd();
  4562. Assert(regOpnd != nullptr);
  4563. StackSym *sym = regOpnd->m_sym;
  4564. if (tag == Js::BackwardPhase
  4565. && currentInstr->m_opcode == Js::OpCode::Add_A
  4566. && currentInstr->GetSrc1() == opnd
  4567. && !this->IsPrePass()
  4568. && !this->IsCollectionPass()
  4569. && this->currentBlock->loop)
  4570. {
  4571. Assert(currentBlock->cloneStrCandidates != nullptr);
  4572. currentBlock->cloneStrCandidates->Set(sym->m_id);
  4573. }
  4574. }
  4575. void
  4576. BackwardPass::InvalidateCloneStrCandidate(IR::Opnd * opnd)
  4577. {
  4578. IR::RegOpnd *regOpnd = opnd->AsRegOpnd();
  4579. Assert(regOpnd != nullptr);
  4580. StackSym *sym = regOpnd->m_sym;
  4581. if (tag == Js::BackwardPhase &&
  4582. (currentInstr->m_opcode != Js::OpCode::Add_A || currentInstr->GetSrc1()->AsRegOpnd()->m_sym->m_id != sym->m_id) &&
  4583. !this->IsPrePass() &&
  4584. !this->IsCollectionPass() &&
  4585. this->currentBlock->loop)
  4586. {
  4587. currentBlock->cloneStrCandidates->Clear(sym->m_id);
  4588. }
  4589. }
  4590. void
  4591. BackwardPass::ProcessUse(IR::Opnd * opnd)
  4592. {
  4593. switch (opnd->GetKind())
  4594. {
  4595. case IR::OpndKindReg:
  4596. {
  4597. IR::RegOpnd *regOpnd = opnd->AsRegOpnd();
  4598. StackSym *sym = regOpnd->m_sym;
  4599. if (!IsCollectionPass())
  4600. {
  4601. // isTempLastUse is only used for string concat right now, so lets not mark it if it's not a string.
  4602. // If it's upward exposed, it is not it's last use.
  4603. if (regOpnd->m_isTempLastUse && (regOpnd->GetValueType().IsNotString() || this->currentBlock->upwardExposedUses->Test(sym->m_id) || sym->m_mayNotBeTempLastUse))
  4604. {
  4605. regOpnd->m_isTempLastUse = false;
  4606. }
  4607. this->CollectCloneStrCandidate(opnd);
  4608. }
  4609. this->DoSetDead(regOpnd, !this->ProcessSymUse(sym, true, regOpnd->GetIsJITOptimizedReg()));
  4610. if (IsCollectionPass())
  4611. {
  4612. break;
  4613. }
  4614. if (tag == Js::DeadStorePhase && regOpnd->IsArrayRegOpnd())
  4615. {
  4616. ProcessArrayRegOpndUse(currentInstr, regOpnd->AsArrayRegOpnd());
  4617. }
  4618. if (currentInstr->m_opcode == Js::OpCode::BailOnNotArray)
  4619. {
  4620. Assert(tag == Js::DeadStorePhase);
  4621. const ValueType valueType(regOpnd->GetValueType());
  4622. if(valueType.IsLikelyArrayOrObjectWithArray())
  4623. {
  4624. currentBlock->noImplicitCallUses->Clear(sym->m_id);
  4625. // We are being conservative here to always check for missing value
  4626. // if any of them expect no missing value. That is because we don't know
  4627. // what set of sym is equivalent (copied) from the one we are testing for right now.
  4628. if(valueType.HasNoMissingValues() &&
  4629. !currentBlock->noImplicitCallNoMissingValuesUses->IsEmpty() &&
  4630. !IsPrePass())
  4631. {
  4632. // There is a use of this sym that requires this array to have no missing values, so this instruction
  4633. // needs to bail out if the array has missing values.
  4634. Assert(currentInstr->GetBailOutKind() == IR::BailOutOnNotArray ||
  4635. currentInstr->GetBailOutKind() == IR::BailOutOnNotNativeArray);
  4636. currentInstr->SetBailOutKind(currentInstr->GetBailOutKind() | IR::BailOutOnMissingValue);
  4637. }
  4638. currentBlock->noImplicitCallNoMissingValuesUses->Clear(sym->m_id);
  4639. currentBlock->noImplicitCallNativeArrayUses->Clear(sym->m_id);
  4640. }
  4641. }
  4642. }
  4643. break;
  4644. case IR::OpndKindSym:
  4645. {
  4646. IR::SymOpnd *symOpnd = opnd->AsSymOpnd();
  4647. Sym * sym = symOpnd->m_sym;
  4648. this->DoSetDead(symOpnd, !this->ProcessSymUse(sym, false, opnd->GetIsJITOptimizedReg()));
  4649. if (IsCollectionPass())
  4650. {
  4651. break;
  4652. }
  4653. if (sym->IsPropertySym())
  4654. {
  4655. // TODO: We don't have last use info for property sym
  4656. // and we don't set the last use of the stacksym inside the property sym
  4657. if (tag == Js::BackwardPhase)
  4658. {
  4659. if (opnd->AsSymOpnd()->IsPropertySymOpnd())
  4660. {
  4661. this->globOpt->PreparePropertySymOpndForTypeCheckSeq(symOpnd->AsPropertySymOpnd(), this->currentInstr, this->currentBlock->loop);
  4662. }
  4663. }
  4664. if (this->DoMarkTempNumbersOnTempObjects())
  4665. {
  4666. this->currentBlock->tempNumberTracker->ProcessPropertySymUse(symOpnd, this->currentInstr, this);
  4667. }
  4668. if (symOpnd->IsPropertySymOpnd())
  4669. {
  4670. this->ProcessPropertySymOpndUse(symOpnd->AsPropertySymOpnd());
  4671. }
  4672. }
  4673. }
  4674. break;
  4675. case IR::OpndKindIndir:
  4676. {
  4677. IR::IndirOpnd * indirOpnd = opnd->AsIndirOpnd();
  4678. IR::RegOpnd * baseOpnd = indirOpnd->GetBaseOpnd();
  4679. this->DoSetDead(baseOpnd, !this->ProcessSymUse(baseOpnd->m_sym, false, baseOpnd->GetIsJITOptimizedReg()));
  4680. IR::RegOpnd * indexOpnd = indirOpnd->GetIndexOpnd();
  4681. if (indexOpnd)
  4682. {
  4683. this->DoSetDead(indexOpnd, !this->ProcessSymUse(indexOpnd->m_sym, false, indexOpnd->GetIsJITOptimizedReg()));
  4684. }
  4685. if(IsCollectionPass())
  4686. {
  4687. break;
  4688. }
  4689. if (this->DoMarkTempNumbersOnTempObjects())
  4690. {
  4691. this->currentBlock->tempNumberTracker->ProcessIndirUse(indirOpnd, currentInstr, this);
  4692. }
  4693. if(tag == Js::DeadStorePhase && baseOpnd->IsArrayRegOpnd())
  4694. {
  4695. ProcessArrayRegOpndUse(currentInstr, baseOpnd->AsArrayRegOpnd());
  4696. }
  4697. }
  4698. break;
  4699. }
  4700. }
  4701. bool
  4702. BackwardPass::ProcessPropertySymUse(PropertySym *propertySym)
  4703. {
  4704. Assert(this->tag == Js::BackwardPhase);
  4705. BasicBlock *block = this->currentBlock;
  4706. bool isLive = !!block->upwardExposedFields->TestAndSet(propertySym->m_id);
  4707. if (propertySym->m_propertyEquivSet)
  4708. {
  4709. block->upwardExposedFields->Or(propertySym->m_propertyEquivSet);
  4710. }
  4711. return isLive;
  4712. }
  4713. void
  4714. BackwardPass::MarkTemp(StackSym * sym)
  4715. {
  4716. Assert(!IsCollectionPass());
  4717. // Don't care about type specialized syms
  4718. if (!sym->IsVar())
  4719. {
  4720. return;
  4721. }
  4722. BasicBlock * block = this->currentBlock;
  4723. if (this->DoMarkTempNumbers())
  4724. {
  4725. Assert((block->loop != nullptr) == block->tempNumberTracker->HasTempTransferDependencies());
  4726. block->tempNumberTracker->MarkTemp(sym, this);
  4727. }
  4728. if (this->DoMarkTempObjects())
  4729. {
  4730. Assert((block->loop != nullptr) == block->tempObjectTracker->HasTempTransferDependencies());
  4731. block->tempObjectTracker->MarkTemp(sym, this);
  4732. }
  4733. #if DBG
  4734. if (this->DoMarkTempObjectVerify())
  4735. {
  4736. Assert((block->loop != nullptr) == block->tempObjectVerifyTracker->HasTempTransferDependencies());
  4737. block->tempObjectVerifyTracker->MarkTemp(sym, this);
  4738. }
  4739. #endif
  4740. }
  4741. void
  4742. BackwardPass::MarkTempProcessInstr(IR::Instr * instr)
  4743. {
  4744. Assert(!IsCollectionPass());
  4745. if (this->currentBlock->isDead)
  4746. {
  4747. return;
  4748. }
  4749. BasicBlock * block;
  4750. block = this->currentBlock;
  4751. if (this->DoMarkTempNumbers())
  4752. {
  4753. block->tempNumberTracker->ProcessInstr(instr, this);
  4754. }
  4755. if (this->DoMarkTempObjects())
  4756. {
  4757. block->tempObjectTracker->ProcessInstr(instr);
  4758. }
  4759. #if DBG
  4760. if (this->DoMarkTempObjectVerify())
  4761. {
  4762. block->tempObjectVerifyTracker->ProcessInstr(instr, this);
  4763. }
  4764. #endif
  4765. }
  4766. #if DBG_DUMP
  4767. void
  4768. BackwardPass::DumpMarkTemp()
  4769. {
  4770. Assert(!IsCollectionPass());
  4771. BasicBlock * block = this->currentBlock;
  4772. if (this->DoMarkTempNumbers())
  4773. {
  4774. block->tempNumberTracker->Dump();
  4775. }
  4776. if (this->DoMarkTempObjects())
  4777. {
  4778. block->tempObjectTracker->Dump();
  4779. }
  4780. #if DBG
  4781. if (this->DoMarkTempObjectVerify())
  4782. {
  4783. block->tempObjectVerifyTracker->Dump();
  4784. }
  4785. #endif
  4786. }
  4787. #endif
  4788. void
  4789. BackwardPass::SetSymIsUsedOnlyInNumberIfLastUse(IR::Opnd *const opnd)
  4790. {
  4791. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  4792. if (stackSym && !currentBlock->upwardExposedUses->Test(stackSym->m_id))
  4793. {
  4794. symUsedOnlyForNumberBySymId->Set(stackSym->m_id);
  4795. }
  4796. }
  4797. void
  4798. BackwardPass::SetSymIsNotUsedOnlyInNumber(IR::Opnd *const opnd)
  4799. {
  4800. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  4801. if (stackSym)
  4802. {
  4803. symUsedOnlyForNumberBySymId->Clear(stackSym->m_id);
  4804. }
  4805. }
  4806. void
  4807. BackwardPass::SetSymIsUsedOnlyInBitOpsIfLastUse(IR::Opnd *const opnd)
  4808. {
  4809. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  4810. if (stackSym && !currentBlock->upwardExposedUses->Test(stackSym->m_id))
  4811. {
  4812. symUsedOnlyForBitOpsBySymId->Set(stackSym->m_id);
  4813. }
  4814. }
  4815. void
  4816. BackwardPass::SetSymIsNotUsedOnlyInBitOps(IR::Opnd *const opnd)
  4817. {
  4818. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  4819. if (stackSym)
  4820. {
  4821. symUsedOnlyForBitOpsBySymId->Clear(stackSym->m_id);
  4822. }
  4823. }
  4824. void
  4825. BackwardPass::TrackBitWiseOrNumberOp(IR::Instr *const instr)
  4826. {
  4827. Assert(instr);
  4828. const bool trackBitWiseop = DoTrackBitOpsOrNumber();
  4829. const bool trackNumberop = trackBitWiseop;
  4830. const Js::OpCode opcode = instr->m_opcode;
  4831. StackSym *const dstSym = IR::RegOpnd::TryGetStackSym(instr->GetDst());
  4832. if (!trackBitWiseop && !trackNumberop)
  4833. {
  4834. return;
  4835. }
  4836. if (!instr->IsRealInstr())
  4837. {
  4838. return;
  4839. }
  4840. if (dstSym)
  4841. {
  4842. // For a dst where the def is in this block, transfer the current info into the instruction
  4843. if (trackBitWiseop && symUsedOnlyForBitOpsBySymId->TestAndClear(dstSym->m_id))
  4844. {
  4845. instr->dstIsAlwaysConvertedToInt32 = true;
  4846. }
  4847. if (trackNumberop && symUsedOnlyForNumberBySymId->TestAndClear(dstSym->m_id))
  4848. {
  4849. instr->dstIsAlwaysConvertedToNumber = true;
  4850. }
  4851. }
  4852. // If the instruction can cause src values to escape the local scope, the srcs can't be optimized
  4853. if (OpCodeAttr::NonTempNumberSources(opcode))
  4854. {
  4855. if (trackBitWiseop)
  4856. {
  4857. SetSymIsNotUsedOnlyInBitOps(instr->GetSrc1());
  4858. SetSymIsNotUsedOnlyInBitOps(instr->GetSrc2());
  4859. }
  4860. if (trackNumberop)
  4861. {
  4862. SetSymIsNotUsedOnlyInNumber(instr->GetSrc1());
  4863. SetSymIsNotUsedOnlyInNumber(instr->GetSrc2());
  4864. }
  4865. return;
  4866. }
  4867. if (trackBitWiseop)
  4868. {
  4869. switch (opcode)
  4870. {
  4871. // Instructions that can cause src values to escape the local scope have already been excluded
  4872. case Js::OpCode::Not_A:
  4873. case Js::OpCode::And_A:
  4874. case Js::OpCode::Or_A:
  4875. case Js::OpCode::Xor_A:
  4876. case Js::OpCode::Shl_A:
  4877. case Js::OpCode::Shr_A:
  4878. case Js::OpCode::Not_I4:
  4879. case Js::OpCode::And_I4:
  4880. case Js::OpCode::Or_I4:
  4881. case Js::OpCode::Xor_I4:
  4882. case Js::OpCode::Shl_I4:
  4883. case Js::OpCode::Shr_I4:
  4884. // These instructions don't generate -0, and their behavior is the same for any src that is -0 or +0
  4885. SetSymIsUsedOnlyInBitOpsIfLastUse(instr->GetSrc1());
  4886. SetSymIsUsedOnlyInBitOpsIfLastUse(instr->GetSrc2());
  4887. break;
  4888. default:
  4889. SetSymIsNotUsedOnlyInBitOps(instr->GetSrc1());
  4890. SetSymIsNotUsedOnlyInBitOps(instr->GetSrc2());
  4891. break;
  4892. }
  4893. }
  4894. if (trackNumberop)
  4895. {
  4896. switch (opcode)
  4897. {
  4898. // Instructions that can cause src values to escape the local scope have already been excluded
  4899. case Js::OpCode::Conv_Num:
  4900. case Js::OpCode::Div_A:
  4901. case Js::OpCode::Mul_A:
  4902. case Js::OpCode::Sub_A:
  4903. case Js::OpCode::Rem_A:
  4904. case Js::OpCode::Incr_A:
  4905. case Js::OpCode::Decr_A:
  4906. case Js::OpCode::Neg_A:
  4907. case Js::OpCode::Not_A:
  4908. case Js::OpCode::ShrU_A:
  4909. case Js::OpCode::ShrU_I4:
  4910. case Js::OpCode::And_A:
  4911. case Js::OpCode::Or_A:
  4912. case Js::OpCode::Xor_A:
  4913. case Js::OpCode::Shl_A:
  4914. case Js::OpCode::Shr_A:
  4915. // These instructions don't generate -0, and their behavior is the same for any src that is -0 or +0
  4916. SetSymIsUsedOnlyInNumberIfLastUse(instr->GetSrc1());
  4917. SetSymIsUsedOnlyInNumberIfLastUse(instr->GetSrc2());
  4918. break;
  4919. default:
  4920. SetSymIsNotUsedOnlyInNumber(instr->GetSrc1());
  4921. SetSymIsNotUsedOnlyInNumber(instr->GetSrc2());
  4922. break;
  4923. }
  4924. }
  4925. }
  4926. void
  4927. BackwardPass::RemoveNegativeZeroBailout(IR::Instr* instr)
  4928. {
  4929. Assert(instr->HasBailOutInfo() && (instr->GetBailOutKind() & IR::BailOutOnNegativeZero));
  4930. IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  4931. bailOutKind = bailOutKind & ~IR::BailOutOnNegativeZero;
  4932. if (bailOutKind)
  4933. {
  4934. instr->SetBailOutKind(bailOutKind);
  4935. }
  4936. else
  4937. {
  4938. instr->ClearBailOutInfo();
  4939. if (preOpBailOutInstrToProcess == instr)
  4940. {
  4941. preOpBailOutInstrToProcess = nullptr;
  4942. }
  4943. }
  4944. }
  4945. void
  4946. BackwardPass::TrackIntUsage(IR::Instr *const instr)
  4947. {
  4948. Assert(instr);
  4949. const bool trackNegativeZero = DoTrackNegativeZero();
  4950. const bool trackIntOverflow = DoTrackIntOverflow();
  4951. const bool trackCompoundedIntOverflow = DoTrackCompoundedIntOverflow();
  4952. const bool trackNon32BitOverflow = DoTrackNon32BitOverflow();
  4953. if(!(trackNegativeZero || trackIntOverflow || trackCompoundedIntOverflow))
  4954. {
  4955. return;
  4956. }
  4957. const Js::OpCode opcode = instr->m_opcode;
  4958. if(trackCompoundedIntOverflow && opcode == Js::OpCode::StatementBoundary && instr->AsPragmaInstr()->m_statementIndex == 0)
  4959. {
  4960. // Cannot bail out before the first statement boundary, so the range cannot extend beyond this instruction
  4961. Assert(!instr->ignoreIntOverflowInRange);
  4962. EndIntOverflowDoesNotMatterRange();
  4963. return;
  4964. }
  4965. if(!instr->IsRealInstr())
  4966. {
  4967. return;
  4968. }
  4969. StackSym *const dstSym = IR::RegOpnd::TryGetStackSym(instr->GetDst());
  4970. bool ignoreIntOverflowCandidate = false;
  4971. if(dstSym)
  4972. {
  4973. // For a dst where the def is in this block, transfer the current info into the instruction
  4974. if(trackNegativeZero)
  4975. {
  4976. if (negativeZeroDoesNotMatterBySymId->Test(dstSym->m_id))
  4977. {
  4978. instr->ignoreNegativeZero = true;
  4979. }
  4980. if (tag == Js::DeadStorePhase)
  4981. {
  4982. if (negativeZeroDoesNotMatterBySymId->TestAndClear(dstSym->m_id))
  4983. {
  4984. if (instr->HasBailOutInfo())
  4985. {
  4986. IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  4987. if (bailOutKind & IR::BailOutOnNegativeZero)
  4988. {
  4989. RemoveNegativeZeroBailout(instr);
  4990. }
  4991. }
  4992. }
  4993. else
  4994. {
  4995. if (instr->HasBailOutInfo())
  4996. {
  4997. if (instr->GetBailOutKind() & IR::BailOutOnNegativeZero)
  4998. {
  4999. if (this->currentBlock->couldRemoveNegZeroBailoutForDef->TestAndClear(dstSym->m_id))
  5000. {
  5001. RemoveNegativeZeroBailout(instr);
  5002. }
  5003. }
  5004. // This instruction could potentially bail out. Hence, we cannot reliably remove negative zero
  5005. // bailouts upstream. If we did, and the operation actually produced a -0, and this instruction
  5006. // bailed out, we'd use +0 instead of -0 in the interpreter.
  5007. this->currentBlock->couldRemoveNegZeroBailoutForDef->ClearAll();
  5008. }
  5009. }
  5010. }
  5011. else
  5012. {
  5013. this->negativeZeroDoesNotMatterBySymId->Clear(dstSym->m_id);
  5014. }
  5015. }
  5016. if(trackIntOverflow)
  5017. {
  5018. ignoreIntOverflowCandidate = !!intOverflowDoesNotMatterBySymId->TestAndClear(dstSym->m_id);
  5019. if(trackCompoundedIntOverflow)
  5020. {
  5021. instr->ignoreIntOverflowInRange = !!intOverflowDoesNotMatterInRangeBySymId->TestAndClear(dstSym->m_id);
  5022. }
  5023. }
  5024. }
  5025. // If the instruction can cause src values to escape the local scope, the srcs can't be optimized
  5026. if(OpCodeAttr::NonTempNumberSources(opcode))
  5027. {
  5028. if(trackNegativeZero)
  5029. {
  5030. SetNegativeZeroMatters(instr->GetSrc1());
  5031. SetNegativeZeroMatters(instr->GetSrc2());
  5032. }
  5033. if(trackIntOverflow)
  5034. {
  5035. SetIntOverflowMatters(instr->GetSrc1());
  5036. SetIntOverflowMatters(instr->GetSrc2());
  5037. if(trackCompoundedIntOverflow)
  5038. {
  5039. instr->ignoreIntOverflowInRange = false;
  5040. SetIntOverflowMattersInRange(instr->GetSrc1());
  5041. SetIntOverflowMattersInRange(instr->GetSrc2());
  5042. EndIntOverflowDoesNotMatterRange();
  5043. }
  5044. }
  5045. return;
  5046. }
  5047. // -0 tracking
  5048. if(trackNegativeZero)
  5049. {
  5050. switch(opcode)
  5051. {
  5052. // Instructions that can cause src values to escape the local scope have already been excluded
  5053. case Js::OpCode::FromVar:
  5054. case Js::OpCode::Conv_Prim:
  5055. Assert(dstSym);
  5056. Assert(instr->GetSrc1());
  5057. Assert(!instr->GetSrc2() || instr->GetDst()->GetType() == instr->GetSrc1()->GetType());
  5058. if(instr->GetDst()->IsInt32())
  5059. {
  5060. // Conversion to int32 that is either explicit, or has a bailout check ensuring that it's an int value
  5061. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5062. break;
  5063. }
  5064. // fall-through
  5065. default:
  5066. if(dstSym && !instr->ignoreNegativeZero)
  5067. {
  5068. // -0 matters for dst, so -0 also matters for srcs
  5069. SetNegativeZeroMatters(instr->GetSrc1());
  5070. SetNegativeZeroMatters(instr->GetSrc2());
  5071. break;
  5072. }
  5073. if(opcode == Js::OpCode::Div_A || opcode == Js::OpCode::Div_I4)
  5074. {
  5075. // src1 is being divided by src2, so -0 matters for src2
  5076. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5077. SetNegativeZeroMatters(instr->GetSrc2());
  5078. break;
  5079. }
  5080. // fall-through
  5081. case Js::OpCode::Incr_A:
  5082. case Js::OpCode::Decr_A:
  5083. // Adding 1 to something or subtracting 1 from something does not generate -0
  5084. case Js::OpCode::Not_A:
  5085. case Js::OpCode::And_A:
  5086. case Js::OpCode::Or_A:
  5087. case Js::OpCode::Xor_A:
  5088. case Js::OpCode::Shl_A:
  5089. case Js::OpCode::Shr_A:
  5090. case Js::OpCode::ShrU_A:
  5091. case Js::OpCode::Not_I4:
  5092. case Js::OpCode::And_I4:
  5093. case Js::OpCode::Or_I4:
  5094. case Js::OpCode::Xor_I4:
  5095. case Js::OpCode::Shl_I4:
  5096. case Js::OpCode::Shr_I4:
  5097. case Js::OpCode::ShrU_I4:
  5098. case Js::OpCode::Conv_Str:
  5099. case Js::OpCode::Coerce_Str:
  5100. case Js::OpCode::Coerce_Regex:
  5101. case Js::OpCode::Coerce_StrOrRegex:
  5102. case Js::OpCode::Conv_PrimStr:
  5103. // These instructions don't generate -0, and their behavior is the same for any src that is -0 or +0
  5104. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5105. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc2());
  5106. break;
  5107. case Js::OpCode::Add_I4:
  5108. {
  5109. Assert(dstSym);
  5110. Assert(instr->GetSrc1());
  5111. Assert(instr->GetSrc1()->IsRegOpnd() || instr->GetSrc1()->IsImmediateOpnd());
  5112. Assert(instr->GetSrc2());
  5113. Assert(instr->GetSrc2()->IsRegOpnd() || instr->GetSrc2()->IsImmediateOpnd());
  5114. if (instr->ignoreNegativeZero ||
  5115. (instr->GetSrc1()->IsImmediateOpnd() && instr->GetSrc1()->GetImmediateValue(func) != 0) ||
  5116. (instr->GetSrc2()->IsImmediateOpnd() && instr->GetSrc2()->GetImmediateValue(func) != 0))
  5117. {
  5118. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5119. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc2());
  5120. break;
  5121. }
  5122. // -0 + -0 == -0. As long as one src is guaranteed to not be -0, -0 does not matter for the other src. Pick a
  5123. // src for which to ignore negative zero, based on which sym is last-use. If both syms are last-use, src2 is
  5124. // picked arbitrarily.
  5125. SetNegativeZeroMatters(instr->GetSrc1());
  5126. SetNegativeZeroMatters(instr->GetSrc2());
  5127. if (tag == Js::DeadStorePhase)
  5128. {
  5129. if (instr->GetSrc2()->IsRegOpnd() &&
  5130. !currentBlock->upwardExposedUses->Test(instr->GetSrc2()->AsRegOpnd()->m_sym->m_id))
  5131. {
  5132. SetCouldRemoveNegZeroBailoutForDefIfLastUse(instr->GetSrc2());
  5133. }
  5134. else
  5135. {
  5136. SetCouldRemoveNegZeroBailoutForDefIfLastUse(instr->GetSrc1());
  5137. }
  5138. }
  5139. break;
  5140. }
  5141. case Js::OpCode::Add_A:
  5142. Assert(dstSym);
  5143. Assert(instr->GetSrc1());
  5144. Assert(instr->GetSrc1()->IsRegOpnd() || instr->GetSrc1()->IsAddrOpnd());
  5145. Assert(instr->GetSrc2());
  5146. Assert(instr->GetSrc2()->IsRegOpnd() || instr->GetSrc2()->IsAddrOpnd());
  5147. if(instr->ignoreNegativeZero || instr->GetSrc1()->IsAddrOpnd() || instr->GetSrc2()->IsAddrOpnd())
  5148. {
  5149. // -0 does not matter for dst, or this instruction does not generate -0 since one of the srcs is not -0
  5150. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5151. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc2());
  5152. break;
  5153. }
  5154. SetNegativeZeroMatters(instr->GetSrc1());
  5155. SetNegativeZeroMatters(instr->GetSrc2());
  5156. break;
  5157. case Js::OpCode::Sub_I4:
  5158. {
  5159. Assert(dstSym);
  5160. Assert(instr->GetSrc1());
  5161. Assert(instr->GetSrc1()->IsRegOpnd() || instr->GetSrc1()->IsImmediateOpnd());
  5162. Assert(instr->GetSrc2());
  5163. Assert(instr->GetSrc2()->IsRegOpnd() || instr->GetSrc2()->IsImmediateOpnd());
  5164. if (instr->ignoreNegativeZero ||
  5165. (instr->GetSrc1()->IsImmediateOpnd() && instr->GetSrc1()->GetImmediateValue(func) != 0) ||
  5166. (instr->GetSrc2()->IsImmediateOpnd() && instr->GetSrc2()->GetImmediateValue(func) != 0))
  5167. {
  5168. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5169. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc2());
  5170. }
  5171. else
  5172. {
  5173. goto NegativeZero_Sub_Default;
  5174. }
  5175. break;
  5176. }
  5177. case Js::OpCode::Sub_A:
  5178. Assert(dstSym);
  5179. Assert(instr->GetSrc1());
  5180. Assert(instr->GetSrc1()->IsRegOpnd() || instr->GetSrc1()->IsAddrOpnd());
  5181. Assert(instr->GetSrc2());
  5182. Assert(instr->GetSrc2()->IsRegOpnd() || instr->GetSrc2()->IsAddrOpnd() || instr->GetSrc2()->IsIntConstOpnd());
  5183. if(instr->ignoreNegativeZero ||
  5184. instr->GetSrc1()->IsAddrOpnd() ||
  5185. (
  5186. instr->GetSrc2()->IsAddrOpnd() &&
  5187. instr->GetSrc2()->AsAddrOpnd()->IsVar() &&
  5188. Js::TaggedInt::ToInt32(instr->GetSrc2()->AsAddrOpnd()->m_address) != 0
  5189. ))
  5190. {
  5191. // At least one of the following is true:
  5192. // - -0 does not matter for dst
  5193. // - Src1 is not -0, and so this instruction cannot generate -0
  5194. // - Src2 is a nonzero tagged int constant, and so this instruction cannot generate -0
  5195. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1());
  5196. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc2());
  5197. break;
  5198. }
  5199. // fall-through
  5200. NegativeZero_Sub_Default:
  5201. // -0 - 0 == -0. As long as src1 is guaranteed to not be -0, -0 does not matter for src2.
  5202. SetNegativeZeroMatters(instr->GetSrc1());
  5203. SetNegativeZeroMatters(instr->GetSrc2());
  5204. if (this->tag == Js::DeadStorePhase)
  5205. {
  5206. SetCouldRemoveNegZeroBailoutForDefIfLastUse(instr->GetSrc2());
  5207. }
  5208. break;
  5209. case Js::OpCode::BrEq_I4:
  5210. case Js::OpCode::BrTrue_I4:
  5211. case Js::OpCode::BrFalse_I4:
  5212. case Js::OpCode::BrGe_I4:
  5213. case Js::OpCode::BrUnGe_I4:
  5214. case Js::OpCode::BrGt_I4:
  5215. case Js::OpCode::BrUnGt_I4:
  5216. case Js::OpCode::BrLt_I4:
  5217. case Js::OpCode::BrUnLt_I4:
  5218. case Js::OpCode::BrLe_I4:
  5219. case Js::OpCode::BrUnLe_I4:
  5220. case Js::OpCode::BrNeq_I4:
  5221. // Int-specialized branches may prove that one of the src must be zero purely based on the int range, in which
  5222. // case they rely on prior -0 bailouts to guarantee that the src cannot be -0. So, consider that -0 matters for
  5223. // the srcs.
  5224. // fall-through
  5225. case Js::OpCode::InlineMathAtan2:
  5226. // Atan(y,x) - signs of y, x is used to determine the quadrant of the result
  5227. SetNegativeZeroMatters(instr->GetSrc1());
  5228. SetNegativeZeroMatters(instr->GetSrc2());
  5229. break;
  5230. case Js::OpCode::Expo_A:
  5231. case Js::OpCode::InlineMathPow:
  5232. // Negative zero matters for src1
  5233. // Pow( 0, <neg>) is Infinity
  5234. // Pow(-0, <neg>) is -Infinity
  5235. SetNegativeZeroMatters(instr->GetSrc1());
  5236. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc2());
  5237. break;
  5238. case Js::OpCode::LdElemI_A:
  5239. // There is an implicit ToString on the index operand, which doesn't differentiate -0 from +0
  5240. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetSrc1()->AsIndirOpnd()->GetIndexOpnd());
  5241. break;
  5242. case Js::OpCode::StElemI_A:
  5243. case Js::OpCode::StElemI_A_Strict:
  5244. // There is an implicit ToString on the index operand, which doesn't differentiate -0 from +0
  5245. SetNegativeZeroDoesNotMatterIfLastUse(instr->GetDst()->AsIndirOpnd()->GetIndexOpnd());
  5246. break;
  5247. }
  5248. }
  5249. // Int overflow tracking
  5250. if(!trackIntOverflow)
  5251. {
  5252. return;
  5253. }
  5254. switch(opcode)
  5255. {
  5256. // Instructions that can cause src values to escape the local scope have already been excluded
  5257. default:
  5258. // Unlike the -0 tracking, we use an inclusion list of op-codes for overflow tracking rather than an exclusion list.
  5259. // Assume for any instructions other than those listed above, that int-overflowed values in the srcs are
  5260. // insufficient.
  5261. ignoreIntOverflowCandidate = false;
  5262. // fall-through
  5263. case Js::OpCode::Incr_A:
  5264. case Js::OpCode::Decr_A:
  5265. case Js::OpCode::Add_A:
  5266. case Js::OpCode::Sub_A:
  5267. // The sources are not guaranteed to be converted to int32. Let the compounded int overflow tracking handle this.
  5268. SetIntOverflowMatters(instr->GetSrc1());
  5269. SetIntOverflowMatters(instr->GetSrc2());
  5270. break;
  5271. case Js::OpCode::Mul_A:
  5272. if (trackNon32BitOverflow)
  5273. {
  5274. if (ignoreIntOverflowCandidate)
  5275. instr->ignoreOverflowBitCount = 53;
  5276. }
  5277. else
  5278. {
  5279. ignoreIntOverflowCandidate = false;
  5280. }
  5281. SetIntOverflowMatters(instr->GetSrc1());
  5282. SetIntOverflowMatters(instr->GetSrc2());
  5283. break;
  5284. case Js::OpCode::Neg_A:
  5285. case Js::OpCode::Ld_A:
  5286. case Js::OpCode::Conv_Num:
  5287. case Js::OpCode::ShrU_A:
  5288. if(!ignoreIntOverflowCandidate)
  5289. {
  5290. // Int overflow matters for dst, so int overflow also matters for srcs
  5291. SetIntOverflowMatters(instr->GetSrc1());
  5292. SetIntOverflowMatters(instr->GetSrc2());
  5293. break;
  5294. }
  5295. // fall-through
  5296. case Js::OpCode::Not_A:
  5297. case Js::OpCode::And_A:
  5298. case Js::OpCode::Or_A:
  5299. case Js::OpCode::Xor_A:
  5300. case Js::OpCode::Shl_A:
  5301. case Js::OpCode::Shr_A:
  5302. // These instructions convert their srcs to int32s, and hence don't care about int-overflowed values in the srcs (as
  5303. // long as the overflowed values did not overflow the 53 bits that 'double' values have to precisely represent
  5304. // ints). ShrU_A is not included here because it converts its srcs to uint32 rather than int32, so it would make a
  5305. // difference if the srcs have int32-overflowed values.
  5306. SetIntOverflowDoesNotMatterIfLastUse(instr->GetSrc1());
  5307. SetIntOverflowDoesNotMatterIfLastUse(instr->GetSrc2());
  5308. break;
  5309. }
  5310. if(ignoreIntOverflowCandidate)
  5311. {
  5312. instr->ignoreIntOverflow = true;
  5313. }
  5314. // Compounded int overflow tracking
  5315. if(!trackCompoundedIntOverflow)
  5316. {
  5317. return;
  5318. }
  5319. if(instr->GetByteCodeOffset() == Js::Constants::NoByteCodeOffset)
  5320. {
  5321. // The forward pass may need to insert conversions with bailouts before the first instruction in the range. Since this
  5322. // instruction does not have a valid byte code offset for bailout purposes, end the current range now.
  5323. instr->ignoreIntOverflowInRange = false;
  5324. SetIntOverflowMattersInRange(instr->GetSrc1());
  5325. SetIntOverflowMattersInRange(instr->GetSrc2());
  5326. EndIntOverflowDoesNotMatterRange();
  5327. return;
  5328. }
  5329. if(ignoreIntOverflowCandidate)
  5330. {
  5331. instr->ignoreIntOverflowInRange = true;
  5332. if(dstSym)
  5333. {
  5334. dstSym->scratch.globOpt.numCompoundedAddSubUses = 0;
  5335. }
  5336. }
  5337. bool lossy = false;
  5338. switch(opcode)
  5339. {
  5340. // Instructions that can cause src values to escape the local scope have already been excluded
  5341. case Js::OpCode::Incr_A:
  5342. case Js::OpCode::Decr_A:
  5343. case Js::OpCode::Add_A:
  5344. case Js::OpCode::Sub_A:
  5345. {
  5346. if(!instr->ignoreIntOverflowInRange)
  5347. {
  5348. // Int overflow matters for dst, so int overflow also matters for srcs
  5349. SetIntOverflowMattersInRange(instr->GetSrc1());
  5350. SetIntOverflowMattersInRange(instr->GetSrc2());
  5351. break;
  5352. }
  5353. AnalysisAssert(dstSym);
  5354. // The number of compounded add/sub uses of each src is at least the number of compounded add/sub uses of the dst,
  5355. // + 1 for the current instruction
  5356. Assert(dstSym->scratch.globOpt.numCompoundedAddSubUses >= 0);
  5357. Assert(dstSym->scratch.globOpt.numCompoundedAddSubUses <= MaxCompoundedUsesInAddSubForIgnoringIntOverflow);
  5358. const int addSubUses = dstSym->scratch.globOpt.numCompoundedAddSubUses + 1;
  5359. if(addSubUses > MaxCompoundedUsesInAddSubForIgnoringIntOverflow)
  5360. {
  5361. // There are too many compounded add/sub uses of the srcs. There is a possibility that combined, the number
  5362. // eventually overflows the 53 bits that 'double' values have to precisely represent ints
  5363. instr->ignoreIntOverflowInRange = false;
  5364. SetIntOverflowMattersInRange(instr->GetSrc1());
  5365. SetIntOverflowMattersInRange(instr->GetSrc2());
  5366. break;
  5367. }
  5368. TransferCompoundedAddSubUsesToSrcs(instr, addSubUses);
  5369. break;
  5370. }
  5371. case Js::OpCode::Neg_A:
  5372. case Js::OpCode::Ld_A:
  5373. case Js::OpCode::Conv_Num:
  5374. case Js::OpCode::ShrU_A:
  5375. {
  5376. if(!instr->ignoreIntOverflowInRange)
  5377. {
  5378. // Int overflow matters for dst, so int overflow also matters for srcs
  5379. SetIntOverflowMattersInRange(instr->GetSrc1());
  5380. SetIntOverflowMattersInRange(instr->GetSrc2());
  5381. break;
  5382. }
  5383. AnalysisAssert(dstSym);
  5384. TransferCompoundedAddSubUsesToSrcs(instr, dstSym->scratch.globOpt.numCompoundedAddSubUses);
  5385. lossy = opcode == Js::OpCode::ShrU_A;
  5386. break;
  5387. }
  5388. case Js::OpCode::Not_A:
  5389. case Js::OpCode::And_A:
  5390. case Js::OpCode::Or_A:
  5391. case Js::OpCode::Xor_A:
  5392. case Js::OpCode::Shl_A:
  5393. case Js::OpCode::Shr_A:
  5394. // These instructions convert their srcs to int32s, and hence don't care about int-overflowed values in the srcs (as
  5395. // long as the overflowed values did not overflow the 53 bits that 'double' values have to precisely represent
  5396. // ints). ShrU_A is not included here because it converts its srcs to uint32 rather than int32, so it would make a
  5397. // difference if the srcs have int32-overflowed values.
  5398. instr->ignoreIntOverflowInRange = true;
  5399. lossy = true;
  5400. SetIntOverflowDoesNotMatterInRangeIfLastUse(instr->GetSrc1(), 0);
  5401. SetIntOverflowDoesNotMatterInRangeIfLastUse(instr->GetSrc2(), 0);
  5402. break;
  5403. case Js::OpCode::LdSlotArr:
  5404. case Js::OpCode::LdSlot:
  5405. {
  5406. Assert(dstSym);
  5407. Assert(!instr->GetSrc2()); // at the moment, this list contains only unary operations
  5408. if(intOverflowCurrentlyMattersInRange)
  5409. {
  5410. // These instructions will not begin a range, so just return. They don't begin a range because their initial
  5411. // value may not be available until after the instruction is processed in the forward pass.
  5412. Assert(!instr->ignoreIntOverflowInRange);
  5413. return;
  5414. }
  5415. Assert(currentBlock->intOverflowDoesNotMatterRange);
  5416. // Int overflow does not matter for dst, so the srcs need to be tracked as inputs into the region of
  5417. // instructions where int overflow does not matter. Since these instructions will not begin or end a range, they
  5418. // are tracked in separate candidates bit-vectors and once we have confirmed that they don't begin the range,
  5419. // they will be transferred to 'SymsRequiredToBe[Lossy]Int'. Furthermore, once this instruction is included in
  5420. // the range, its dst sym has to be removed. Since this instructions may not be included in the range, add the
  5421. // dst sym to the candidates bit-vectors. If they are included, the process of transferring will remove the dst
  5422. // syms and add the src syms.
  5423. // Remove the dst using the candidate bit-vectors
  5424. Assert(
  5425. !instr->ignoreIntOverflowInRange ||
  5426. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Test(dstSym->m_id));
  5427. if(instr->ignoreIntOverflowInRange ||
  5428. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Test(dstSym->m_id))
  5429. {
  5430. candidateSymsRequiredToBeInt->Set(dstSym->m_id);
  5431. if(currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Test(dstSym->m_id))
  5432. {
  5433. candidateSymsRequiredToBeLossyInt->Set(dstSym->m_id);
  5434. }
  5435. }
  5436. if(!instr->ignoreIntOverflowInRange)
  5437. {
  5438. // These instructions will not end a range, so just return. They may be included in the middle of a range, but
  5439. // since int overflow matters for the dst, the src does not need to be counted as an input into the range.
  5440. return;
  5441. }
  5442. instr->ignoreIntOverflowInRange = false;
  5443. // Add the src using the candidate bit-vectors. The src property sym may already be included in the range or as
  5444. // a candidate. The xor of the final bit-vector with the candidate is the set of syms required to be int,
  5445. // assuming all instructions up to and not including this one are included in the range.
  5446. const SymID srcSymId = instr->GetSrc1()->AsSymOpnd()->m_sym->m_id;
  5447. const bool srcIncluded =
  5448. !!currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Test(srcSymId) ^
  5449. !!candidateSymsRequiredToBeInt->Test(srcSymId);
  5450. const bool srcIncludedAsLossy =
  5451. srcIncluded &&
  5452. !!currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Test(srcSymId) ^
  5453. !!candidateSymsRequiredToBeLossyInt->Test(srcSymId);
  5454. const bool srcNeedsToBeLossless =
  5455. !currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Test(dstSym->m_id) ||
  5456. (srcIncluded && !srcIncludedAsLossy);
  5457. if(srcIncluded)
  5458. {
  5459. if(srcIncludedAsLossy && srcNeedsToBeLossless)
  5460. {
  5461. candidateSymsRequiredToBeLossyInt->Compliment(srcSymId);
  5462. }
  5463. }
  5464. else
  5465. {
  5466. candidateSymsRequiredToBeInt->Compliment(srcSymId);
  5467. if(!srcNeedsToBeLossless)
  5468. {
  5469. candidateSymsRequiredToBeLossyInt->Compliment(srcSymId);
  5470. }
  5471. }
  5472. // These instructions will not end a range, so just return. They may be included in the middle of a range, and the
  5473. // src has been included as a candidate input into the range.
  5474. return;
  5475. }
  5476. case Js::OpCode::Mul_A:
  5477. if (trackNon32BitOverflow)
  5478. {
  5479. // 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.
  5480. // That's why it cannot be in the middle of a range.
  5481. if (instr->ignoreIntOverflowInRange)
  5482. {
  5483. AnalysisAssert(dstSym);
  5484. Assert(dstSym->scratch.globOpt.numCompoundedAddSubUses >= 0);
  5485. Assert(dstSym->scratch.globOpt.numCompoundedAddSubUses <= MaxCompoundedUsesInAddSubForIgnoringIntOverflow);
  5486. instr->ignoreOverflowBitCount = (uint8) (53 - dstSym->scratch.globOpt.numCompoundedAddSubUses);
  5487. // We have the max number of compounded adds/subs. 32-bit overflow cannot be ignored.
  5488. if (instr->ignoreOverflowBitCount == 32)
  5489. {
  5490. instr->ignoreIntOverflowInRange = false;
  5491. }
  5492. }
  5493. SetIntOverflowMattersInRange(instr->GetSrc1());
  5494. SetIntOverflowMattersInRange(instr->GetSrc2());
  5495. break;
  5496. }
  5497. // fall-through
  5498. default:
  5499. // Unlike the -0 tracking, we use an inclusion list of op-codes for overflow tracking rather than an exclusion list.
  5500. // Assume for any instructions other than those listed above, that int-overflowed values in the srcs are
  5501. // insufficient.
  5502. instr->ignoreIntOverflowInRange = false;
  5503. SetIntOverflowMattersInRange(instr->GetSrc1());
  5504. SetIntOverflowMattersInRange(instr->GetSrc2());
  5505. break;
  5506. }
  5507. if(!instr->ignoreIntOverflowInRange)
  5508. {
  5509. EndIntOverflowDoesNotMatterRange();
  5510. return;
  5511. }
  5512. if(intOverflowCurrentlyMattersInRange)
  5513. {
  5514. // This is the last instruction in a new range of instructions where int overflow does not matter
  5515. intOverflowCurrentlyMattersInRange = false;
  5516. IR::Instr *const boundaryInstr = IR::PragmaInstr::New(Js::OpCode::NoIntOverflowBoundary, 0, instr->m_func);
  5517. boundaryInstr->SetByteCodeOffset(instr);
  5518. currentBlock->InsertInstrAfter(boundaryInstr, instr);
  5519. currentBlock->intOverflowDoesNotMatterRange =
  5520. IntOverflowDoesNotMatterRange::New(
  5521. globOpt->alloc,
  5522. instr,
  5523. boundaryInstr,
  5524. currentBlock->intOverflowDoesNotMatterRange);
  5525. }
  5526. else
  5527. {
  5528. Assert(currentBlock->intOverflowDoesNotMatterRange);
  5529. // Extend the current range of instructions where int overflow does not matter, to include this instruction. We also need to
  5530. // include the tracked syms for instructions that have not yet been included in the range, which are tracked in the range's
  5531. // bit-vector. 'SymsRequiredToBeInt' will contain both the dst and src syms of instructions not yet included in the range;
  5532. // the xor will remove the dst syms and add the src syms.
  5533. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Xor(candidateSymsRequiredToBeInt);
  5534. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Xor(candidateSymsRequiredToBeLossyInt);
  5535. candidateSymsRequiredToBeInt->ClearAll();
  5536. candidateSymsRequiredToBeLossyInt->ClearAll();
  5537. currentBlock->intOverflowDoesNotMatterRange->SetFirstInstr(instr);
  5538. }
  5539. // Track syms that are inputs into the range based on the current instruction, which was just added to the range. The dst
  5540. // 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.
  5541. if(dstSym)
  5542. {
  5543. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Clear(dstSym->m_id);
  5544. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Clear(dstSym->m_id);
  5545. }
  5546. IR::Opnd *const srcs[] = { instr->GetSrc1(), instr->GetSrc2() };
  5547. for(int i = 0; i < sizeof(srcs) / sizeof(srcs[0]) && srcs[i]; ++i)
  5548. {
  5549. StackSym *srcSym = IR::RegOpnd::TryGetStackSym(srcs[i]);
  5550. if(!srcSym)
  5551. {
  5552. continue;
  5553. }
  5554. if(currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->TestAndSet(srcSym->m_id))
  5555. {
  5556. if(!lossy)
  5557. {
  5558. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Clear(srcSym->m_id);
  5559. }
  5560. }
  5561. else if(lossy)
  5562. {
  5563. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Set(srcSym->m_id);
  5564. }
  5565. }
  5566. // If the last instruction included in the range is a MUL, we have to end the range.
  5567. // MULs with ignoreIntOverflow can still bailout on 53-bit overflow, so they cannot be in the middle of a range
  5568. if (trackNon32BitOverflow && instr->m_opcode == Js::OpCode::Mul_A)
  5569. {
  5570. // range would have ended already if int32 overflow matters
  5571. Assert(instr->ignoreIntOverflowInRange && instr->ignoreOverflowBitCount != 32);
  5572. EndIntOverflowDoesNotMatterRange();
  5573. }
  5574. }
  5575. void
  5576. BackwardPass::SetNegativeZeroDoesNotMatterIfLastUse(IR::Opnd *const opnd)
  5577. {
  5578. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5579. if(stackSym && !currentBlock->upwardExposedUses->Test(stackSym->m_id))
  5580. {
  5581. negativeZeroDoesNotMatterBySymId->Set(stackSym->m_id);
  5582. }
  5583. }
  5584. void
  5585. BackwardPass::SetNegativeZeroMatters(IR::Opnd *const opnd)
  5586. {
  5587. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5588. if(stackSym)
  5589. {
  5590. negativeZeroDoesNotMatterBySymId->Clear(stackSym->m_id);
  5591. }
  5592. }
  5593. void
  5594. BackwardPass::SetCouldRemoveNegZeroBailoutForDefIfLastUse(IR::Opnd *const opnd)
  5595. {
  5596. StackSym * stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5597. if (stackSym && !this->currentBlock->upwardExposedUses->Test(stackSym->m_id))
  5598. {
  5599. this->currentBlock->couldRemoveNegZeroBailoutForDef->Set(stackSym->m_id);
  5600. }
  5601. }
  5602. void
  5603. BackwardPass::SetIntOverflowDoesNotMatterIfLastUse(IR::Opnd *const opnd)
  5604. {
  5605. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5606. if(stackSym && !currentBlock->upwardExposedUses->Test(stackSym->m_id))
  5607. {
  5608. intOverflowDoesNotMatterBySymId->Set(stackSym->m_id);
  5609. }
  5610. }
  5611. void
  5612. BackwardPass::SetIntOverflowMatters(IR::Opnd *const opnd)
  5613. {
  5614. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5615. if(stackSym)
  5616. {
  5617. intOverflowDoesNotMatterBySymId->Clear(stackSym->m_id);
  5618. }
  5619. }
  5620. bool
  5621. BackwardPass::SetIntOverflowDoesNotMatterInRangeIfLastUse(IR::Opnd *const opnd, const int addSubUses)
  5622. {
  5623. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5624. return stackSym && SetIntOverflowDoesNotMatterInRangeIfLastUse(stackSym, addSubUses);
  5625. }
  5626. bool
  5627. BackwardPass::SetIntOverflowDoesNotMatterInRangeIfLastUse(StackSym *const stackSym, const int addSubUses)
  5628. {
  5629. Assert(stackSym);
  5630. Assert(addSubUses >= 0);
  5631. Assert(addSubUses <= MaxCompoundedUsesInAddSubForIgnoringIntOverflow);
  5632. if(currentBlock->upwardExposedUses->Test(stackSym->m_id))
  5633. {
  5634. return false;
  5635. }
  5636. intOverflowDoesNotMatterInRangeBySymId->Set(stackSym->m_id);
  5637. stackSym->scratch.globOpt.numCompoundedAddSubUses = addSubUses;
  5638. return true;
  5639. }
  5640. void
  5641. BackwardPass::SetIntOverflowMattersInRange(IR::Opnd *const opnd)
  5642. {
  5643. StackSym *const stackSym = IR::RegOpnd::TryGetStackSym(opnd);
  5644. if(stackSym)
  5645. {
  5646. intOverflowDoesNotMatterInRangeBySymId->Clear(stackSym->m_id);
  5647. }
  5648. }
  5649. void
  5650. BackwardPass::TransferCompoundedAddSubUsesToSrcs(IR::Instr *const instr, const int addSubUses)
  5651. {
  5652. Assert(instr);
  5653. Assert(addSubUses >= 0);
  5654. Assert(addSubUses <= MaxCompoundedUsesInAddSubForIgnoringIntOverflow);
  5655. IR::Opnd *const srcs[] = { instr->GetSrc1(), instr->GetSrc2() };
  5656. for(int i = 0; i < _countof(srcs) && srcs[i]; ++i)
  5657. {
  5658. StackSym *const srcSym = IR::RegOpnd::TryGetStackSym(srcs[i]);
  5659. if(!srcSym)
  5660. {
  5661. // Int overflow tracking is only done for StackSyms in RegOpnds. Int overflow matters for the src, so it is
  5662. // guaranteed to be in the int range at this point if the instruction is int-specialized.
  5663. continue;
  5664. }
  5665. Assert(srcSym->scratch.globOpt.numCompoundedAddSubUses >= 0);
  5666. Assert(srcSym->scratch.globOpt.numCompoundedAddSubUses <= MaxCompoundedUsesInAddSubForIgnoringIntOverflow);
  5667. if(SetIntOverflowDoesNotMatterInRangeIfLastUse(srcSym, addSubUses))
  5668. {
  5669. // This is the last use of the src
  5670. continue;
  5671. }
  5672. if(intOverflowDoesNotMatterInRangeBySymId->Test(srcSym->m_id))
  5673. {
  5674. // Since a src may be compounded through different chains of add/sub instructions, the greater number must be
  5675. // preserved
  5676. srcSym->scratch.globOpt.numCompoundedAddSubUses =
  5677. max(srcSym->scratch.globOpt.numCompoundedAddSubUses, addSubUses);
  5678. }
  5679. else
  5680. {
  5681. // Int overflow matters for the src, so it is guaranteed to be in the int range at this point if the instruction is
  5682. // int-specialized
  5683. }
  5684. }
  5685. }
  5686. void
  5687. BackwardPass::EndIntOverflowDoesNotMatterRange()
  5688. {
  5689. if(intOverflowCurrentlyMattersInRange)
  5690. {
  5691. return;
  5692. }
  5693. intOverflowCurrentlyMattersInRange = true;
  5694. if(currentBlock->intOverflowDoesNotMatterRange->FirstInstr()->m_next ==
  5695. currentBlock->intOverflowDoesNotMatterRange->LastInstr())
  5696. {
  5697. // Don't need a range for a single-instruction range
  5698. IntOverflowDoesNotMatterRange *const rangeToDelete = currentBlock->intOverflowDoesNotMatterRange;
  5699. currentBlock->intOverflowDoesNotMatterRange = currentBlock->intOverflowDoesNotMatterRange->Next();
  5700. currentBlock->RemoveInstr(rangeToDelete->LastInstr());
  5701. rangeToDelete->Delete(globOpt->alloc);
  5702. }
  5703. else
  5704. {
  5705. // End the current range of instructions where int overflow does not matter
  5706. IR::Instr *const boundaryInstr =
  5707. IR::PragmaInstr::New(
  5708. Js::OpCode::NoIntOverflowBoundary,
  5709. 0,
  5710. currentBlock->intOverflowDoesNotMatterRange->FirstInstr()->m_func);
  5711. boundaryInstr->SetByteCodeOffset(currentBlock->intOverflowDoesNotMatterRange->FirstInstr());
  5712. currentBlock->InsertInstrBefore(boundaryInstr, currentBlock->intOverflowDoesNotMatterRange->FirstInstr());
  5713. currentBlock->intOverflowDoesNotMatterRange->SetFirstInstr(boundaryInstr);
  5714. #if DBG_DUMP
  5715. if(PHASE_TRACE(Js::TrackCompoundedIntOverflowPhase, func))
  5716. {
  5717. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5718. Output::Print(
  5719. _u("TrackCompoundedIntOverflow - Top function: %s (%s), Phase: %s, Block: %u\n"),
  5720. func->GetJITFunctionBody()->GetDisplayName(),
  5721. func->GetDebugNumberSet(debugStringBuffer),
  5722. Js::PhaseNames[Js::BackwardPhase],
  5723. currentBlock->GetBlockNum());
  5724. Output::Print(_u(" Input syms to be int-specialized (lossless): "));
  5725. candidateSymsRequiredToBeInt->Minus(
  5726. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeInt(),
  5727. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()); // candidate bit-vectors are cleared below anyway
  5728. candidateSymsRequiredToBeInt->Dump();
  5729. Output::Print(_u(" Input syms to be converted to int (lossy): "));
  5730. currentBlock->intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Dump();
  5731. Output::Print(_u(" First instr: "));
  5732. currentBlock->intOverflowDoesNotMatterRange->FirstInstr()->m_next->Dump();
  5733. Output::Flush();
  5734. }
  5735. #endif
  5736. }
  5737. // Reset candidates for the next range
  5738. candidateSymsRequiredToBeInt->ClearAll();
  5739. candidateSymsRequiredToBeLossyInt->ClearAll();
  5740. // Syms are not tracked across different ranges of instructions where int overflow does not matter, since instructions
  5741. // between the ranges may bail out. The value of the dst of an int operation where overflow is ignored is incorrect until
  5742. // 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
  5743. // and an instruction between the ranges bails out, other inputs into the second range are no longer guaranteed to be ints,
  5744. // so the incorrect value of the sym may be used in non-int operations.
  5745. intOverflowDoesNotMatterInRangeBySymId->ClearAll();
  5746. }
  5747. void
  5748. BackwardPass::TrackFloatSymEquivalence(IR::Instr *const instr)
  5749. {
  5750. /*
  5751. This function determines sets of float-specialized syms where any two syms in a set may have the same value number at some
  5752. point in the function. Conversely, if two float-specialized syms are not in the same set, it guarantees that those two syms
  5753. will never have the same value number. These sets are referred to as equivalence classes here.
  5754. The equivalence class for a sym is used to determine whether a bailout FromVar generating a float value for the sym needs to
  5755. 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
  5756. 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
  5757. 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
  5758. 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
  5759. not +0, so the equivalence class is used to determine that since s5 requires a bailout on any non-number value, so does s1.
  5760. The tracking is very conservative because the bit that says "I require bailout on any non-number value" is on the sym itself
  5761. (referred to as non-number bailout bit below).
  5762. Data:
  5763. - BackwardPass::floatSymEquivalenceMap
  5764. - hash table mapping a float sym ID to its equivalence class
  5765. - FloatSymEquivalenceClass
  5766. - bit vector of float sym IDs that are in the equivalence class
  5767. - one non-number bailout bit for all syms in the equivalence class
  5768. Algorithm:
  5769. - In a loop prepass or when not in loop:
  5770. - For a float sym transfer (s0.f = s1.f), add both syms to an equivalence class (set the syms in a bit vector)
  5771. - If either sym requires bailout on any non-number value, set the equivalence class' non-number bailout bit
  5772. - If one of the syms is already in an equivalence class, merge the two equivalence classes by OR'ing the two bit vectors
  5773. and the non-number bailout bit.
  5774. - Note that for functions with a loop, dependency tracking is done using equivalence classes and that information is not
  5775. transferred back into each sym's non-number bailout bit
  5776. - In a loop non-prepass or when not in loop, for a FromVar instruction that requires bailout only on strings and
  5777. non-primitives:
  5778. - If the destination float sym's non-number bailout bit is set, or the sym is in an equivalence class whose non-number
  5779. bailout bit is set, change the bailout to bail out on any non-number value
  5780. 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
  5781. through any other float-specialized sym that acquires the value, the FromVar generating the float value will be modified to
  5782. bail out on any non-number value.
  5783. */
  5784. Assert(instr);
  5785. if(tag != Js::DeadStorePhase || instr->GetSrc2() || !instr->m_func->hasBailout)
  5786. {
  5787. return;
  5788. }
  5789. if(!instr->GetDst() || !instr->GetDst()->IsRegOpnd())
  5790. {
  5791. return;
  5792. }
  5793. const auto dst = instr->GetDst()->AsRegOpnd()->m_sym;
  5794. if(!dst->IsFloat64())
  5795. {
  5796. return;
  5797. }
  5798. if(!instr->GetSrc1() || !instr->GetSrc1()->IsRegOpnd())
  5799. {
  5800. return;
  5801. }
  5802. const auto src = instr->GetSrc1()->AsRegOpnd()->m_sym;
  5803. if(OpCodeAttr::NonIntTransfer(instr->m_opcode) && (!currentBlock->loop || IsPrePass()))
  5804. {
  5805. Assert(src->IsFloat64()); // dst is specialized, and since this is a float transfer, src must be specialized too
  5806. if(dst == src)
  5807. {
  5808. return;
  5809. }
  5810. if(!func->m_fg->hasLoop)
  5811. {
  5812. // Special case for functions with no loops, since there can only be in-order dependencies. Just merge the two
  5813. // non-number bailout bits and put the result in the source.
  5814. if(dst->m_requiresBailOnNotNumber)
  5815. {
  5816. src->m_requiresBailOnNotNumber = true;
  5817. }
  5818. return;
  5819. }
  5820. FloatSymEquivalenceClass *dstEquivalenceClass = nullptr, *srcEquivalenceClass = nullptr;
  5821. const bool dstHasEquivalenceClass = floatSymEquivalenceMap->TryGetValue(dst->m_id, &dstEquivalenceClass);
  5822. const bool srcHasEquivalenceClass = floatSymEquivalenceMap->TryGetValue(src->m_id, &srcEquivalenceClass);
  5823. if(!dstHasEquivalenceClass)
  5824. {
  5825. if(srcHasEquivalenceClass)
  5826. {
  5827. // Just add the destination into the source's equivalence class
  5828. srcEquivalenceClass->Set(dst);
  5829. floatSymEquivalenceMap->Add(dst->m_id, srcEquivalenceClass);
  5830. return;
  5831. }
  5832. dstEquivalenceClass = JitAnew(tempAlloc, FloatSymEquivalenceClass, tempAlloc);
  5833. dstEquivalenceClass->Set(dst);
  5834. floatSymEquivalenceMap->Add(dst->m_id, dstEquivalenceClass);
  5835. }
  5836. if(!srcHasEquivalenceClass)
  5837. {
  5838. // Just add the source into the destination's equivalence class
  5839. dstEquivalenceClass->Set(src);
  5840. floatSymEquivalenceMap->Add(src->m_id, dstEquivalenceClass);
  5841. return;
  5842. }
  5843. if(dstEquivalenceClass == srcEquivalenceClass)
  5844. {
  5845. return;
  5846. }
  5847. Assert(!dstEquivalenceClass->Bv()->Test(src->m_id));
  5848. Assert(!srcEquivalenceClass->Bv()->Test(dst->m_id));
  5849. // Merge the two equivalence classes. The source's equivalence class is typically smaller, so it's merged into the
  5850. // destination's equivalence class. To save space and prevent a potential explosion of bit vector size,
  5851. // 'floatSymEquivalenceMap' is updated for syms in the source's equivalence class to map to the destination's now merged
  5852. // equivalence class, and the source's equivalence class is discarded.
  5853. dstEquivalenceClass->Or(srcEquivalenceClass);
  5854. FOREACH_BITSET_IN_SPARSEBV(id, srcEquivalenceClass->Bv())
  5855. {
  5856. floatSymEquivalenceMap->Item(id, dstEquivalenceClass);
  5857. } NEXT_BITSET_IN_SPARSEBV;
  5858. JitAdelete(tempAlloc, srcEquivalenceClass);
  5859. return;
  5860. }
  5861. // Not a float transfer, and non-prepass (not necessarily in a loop)
  5862. if(!instr->HasBailOutInfo() || instr->GetBailOutKind() != IR::BailOutPrimitiveButString)
  5863. {
  5864. return;
  5865. }
  5866. Assert(instr->m_opcode == Js::OpCode::FromVar);
  5867. // If either the destination or its equivalence class says it requires bailout on any non-number value, adjust the bailout
  5868. // kind on the instruction. Both are checked because in functions without loops, equivalence tracking is not done and only
  5869. // the sym's non-number bailout bit will have the information, and in functions with loops, equivalence tracking is done
  5870. // throughout the function and checking just the sym's non-number bailout bit is insufficient.
  5871. FloatSymEquivalenceClass *dstEquivalenceClass = nullptr;
  5872. if(dst->m_requiresBailOnNotNumber ||
  5873. (floatSymEquivalenceMap->TryGetValue(dst->m_id, &dstEquivalenceClass) && dstEquivalenceClass->RequiresBailOnNotNumber()))
  5874. {
  5875. instr->SetBailOutKind(IR::BailOutNumberOnly);
  5876. }
  5877. }
  5878. bool
  5879. BackwardPass::ProcessDef(IR::Opnd * opnd)
  5880. {
  5881. BOOLEAN isJITOptimizedReg = false;
  5882. Sym * sym;
  5883. if (opnd->IsRegOpnd())
  5884. {
  5885. sym = opnd->AsRegOpnd()->m_sym;
  5886. isJITOptimizedReg = opnd->GetIsJITOptimizedReg();
  5887. if (!IsCollectionPass())
  5888. {
  5889. this->InvalidateCloneStrCandidate(opnd);
  5890. }
  5891. }
  5892. else if (opnd->IsSymOpnd())
  5893. {
  5894. sym = opnd->AsSymOpnd()->m_sym;
  5895. isJITOptimizedReg = opnd->GetIsJITOptimizedReg();
  5896. }
  5897. else
  5898. {
  5899. if (opnd->IsIndirOpnd())
  5900. {
  5901. this->ProcessUse(opnd);
  5902. }
  5903. return false;
  5904. }
  5905. BasicBlock * block = this->currentBlock;
  5906. BOOLEAN isUsed = true;
  5907. BOOLEAN keepSymLiveForException = false;
  5908. BOOLEAN keepVarSymLiveForException = false;
  5909. IR::Instr * instr = this->currentInstr;
  5910. Assert(!instr->IsByteCodeUsesInstr());
  5911. if (sym->IsPropertySym())
  5912. {
  5913. if(IsCollectionPass())
  5914. {
  5915. return false;
  5916. }
  5917. Assert((block->fieldHoistCandidates != nullptr) == this->DoFieldHoistCandidates());
  5918. if (block->fieldHoistCandidates)
  5919. {
  5920. block->fieldHoistCandidates->Clear(sym->m_id);
  5921. }
  5922. PropertySym *propertySym = sym->AsPropertySym();
  5923. if (this->DoDeadStoreSlots())
  5924. {
  5925. if (propertySym->m_fieldKind == PropertyKindLocalSlots || propertySym->m_fieldKind == PropertyKindSlots)
  5926. {
  5927. BOOLEAN isPropertySymUsed = !block->slotDeadStoreCandidates->TestAndSet(propertySym->m_id);
  5928. Assert(isPropertySymUsed || !block->upwardExposedUses->Test(propertySym->m_id));
  5929. isUsed = isPropertySymUsed || block->upwardExposedUses->Test(propertySym->m_stackSym->m_id);
  5930. }
  5931. }
  5932. this->DoSetDead(opnd, !block->upwardExposedFields->TestAndClear(propertySym->m_id));
  5933. ProcessStackSymUse(propertySym->m_stackSym, isJITOptimizedReg);
  5934. if (tag == Js::BackwardPhase)
  5935. {
  5936. if (opnd->AsSymOpnd()->IsPropertySymOpnd())
  5937. {
  5938. this->globOpt->PreparePropertySymOpndForTypeCheckSeq(opnd->AsPropertySymOpnd(), instr, this->currentBlock->loop);
  5939. }
  5940. }
  5941. if (opnd->AsSymOpnd()->IsPropertySymOpnd())
  5942. {
  5943. this->ProcessPropertySymOpndUse(opnd->AsPropertySymOpnd());
  5944. }
  5945. }
  5946. else
  5947. {
  5948. Assert(!instr->IsByteCodeUsesInstr());
  5949. if (this->DoByteCodeUpwardExposedUsed())
  5950. {
  5951. if (sym->AsStackSym()->HasByteCodeRegSlot())
  5952. {
  5953. StackSym * varSym = sym->AsStackSym();
  5954. if (varSym->IsTypeSpec())
  5955. {
  5956. // It has to have a var version for byte code regs
  5957. varSym = varSym->GetVarEquivSym(nullptr);
  5958. }
  5959. if (this->currentRegion)
  5960. {
  5961. keepSymLiveForException = this->CheckWriteThroughSymInRegion(this->currentRegion, sym->AsStackSym());
  5962. keepVarSymLiveForException = this->CheckWriteThroughSymInRegion(this->currentRegion, varSym);
  5963. }
  5964. if (!isJITOptimizedReg)
  5965. {
  5966. if (!DoDeadStore(this->func, sym->AsStackSym()))
  5967. {
  5968. // Don't deadstore the bytecodereg sym, so that we could do write to get the locals inspection
  5969. if (opnd->IsRegOpnd())
  5970. {
  5971. opnd->AsRegOpnd()->m_dontDeadStore = true;
  5972. }
  5973. }
  5974. // write through symbols should not be cleared from the byteCodeUpwardExposedUsed BV upon defs in the Try region:
  5975. // try
  5976. // x =
  5977. // <bailout> <-- this bailout should restore x from its first def. This would not happen if x is cleared
  5978. // from byteCodeUpwardExposedUsed when we process its second def
  5979. // <exception>
  5980. // x =
  5981. // catch
  5982. // = x
  5983. if (!keepVarSymLiveForException)
  5984. {
  5985. // Always track the sym use on the var sym.
  5986. block->byteCodeUpwardExposedUsed->Clear(varSym->m_id);
  5987. #if DBG
  5988. // TODO: We can only track first level function stack syms right now
  5989. if (varSym->GetByteCodeFunc() == this->func)
  5990. {
  5991. block->byteCodeRestoreSyms[varSym->GetByteCodeRegSlot()] = nullptr;
  5992. }
  5993. #endif
  5994. }
  5995. }
  5996. }
  5997. }
  5998. if(IsCollectionPass())
  5999. {
  6000. return false;
  6001. }
  6002. // Don't care about property sym for mark temps
  6003. if (opnd->IsRegOpnd())
  6004. {
  6005. this->MarkTemp(sym->AsStackSym());
  6006. }
  6007. if (this->tag == Js::BackwardPhase &&
  6008. instr->m_opcode == Js::OpCode::Ld_A &&
  6009. instr->GetSrc1()->IsRegOpnd() &&
  6010. block->upwardExposedFields->Test(sym->m_id))
  6011. {
  6012. block->upwardExposedFields->Set(instr->GetSrc1()->AsRegOpnd()->m_sym->m_id);
  6013. }
  6014. if (!keepSymLiveForException)
  6015. {
  6016. isUsed = block->upwardExposedUses->TestAndClear(sym->m_id);
  6017. }
  6018. }
  6019. if (isUsed || !this->DoDeadStore())
  6020. {
  6021. return false;
  6022. }
  6023. // FromVar on a primitive value has no side-effects
  6024. // TODO: There may be more cases where FromVars can be dead-stored, such as cases where they have a bailout that would bail
  6025. // out on non-primitive vars, thereby causing no side effects anyway. However, it needs to be ensured that no assumptions
  6026. // that depend on the bailout are made later in the function.
  6027. // Special case StFld for trackable fields
  6028. bool hasSideEffects = instr->HasAnySideEffects()
  6029. && instr->m_opcode != Js::OpCode::StFld
  6030. && instr->m_opcode != Js::OpCode::StRootFld
  6031. && instr->m_opcode != Js::OpCode::StFldStrict
  6032. && instr->m_opcode != Js::OpCode::StRootFldStrict;
  6033. if (this->IsPrePass() || hasSideEffects)
  6034. {
  6035. return false;
  6036. }
  6037. if (opnd->IsRegOpnd() && opnd->AsRegOpnd()->m_dontDeadStore)
  6038. {
  6039. return false;
  6040. }
  6041. if (instr->HasBailOutInfo())
  6042. {
  6043. // A bailout inserted for aggressive or lossy int type specialization causes assumptions to be made on the value of
  6044. // the instruction's destination later on, as though the bailout did not happen. If the value is an int constant and
  6045. // that value is propagated forward, it can cause the bailout instruction to become a dead store and be removed,
  6046. // thereby invalidating the assumptions made. Or for lossy int type specialization, the lossy conversion to int32
  6047. // may have side effects and so cannot be dead-store-removed. As one way of solving that problem, bailout
  6048. // instructions resulting from aggressive or lossy int type spec are not dead-stored.
  6049. const auto bailOutKind = instr->GetBailOutKind();
  6050. if(bailOutKind & IR::BailOutOnResultConditions)
  6051. {
  6052. return false;
  6053. }
  6054. switch(bailOutKind & ~IR::BailOutKindBits)
  6055. {
  6056. case IR::BailOutIntOnly:
  6057. case IR::BailOutNumberOnly:
  6058. case IR::BailOutExpectingInteger:
  6059. case IR::BailOutPrimitiveButString:
  6060. case IR::BailOutExpectingString:
  6061. case IR::BailOutOnNotPrimitive:
  6062. case IR::BailOutFailedInlineTypeCheck:
  6063. case IR::BailOutOnFloor:
  6064. case IR::BailOnModByPowerOf2:
  6065. case IR::BailOnDivResultNotInt:
  6066. case IR::BailOnIntMin:
  6067. return false;
  6068. }
  6069. }
  6070. // Dead store
  6071. DeadStoreInstr(instr);
  6072. return true;
  6073. }
  6074. bool
  6075. BackwardPass::DeadStoreInstr(IR::Instr *instr)
  6076. {
  6077. BasicBlock * block = this->currentBlock;
  6078. #if DBG_DUMP
  6079. if (this->IsTraceEnabled())
  6080. {
  6081. Output::Print(_u("Deadstore instr: "));
  6082. instr->Dump();
  6083. }
  6084. this->numDeadStore++;
  6085. #endif
  6086. // Before we remove the dead store, we need to track the byte code uses
  6087. if (this->DoByteCodeUpwardExposedUsed())
  6088. {
  6089. #if DBG
  6090. BVSparse<JitArenaAllocator> tempBv(this->tempAlloc);
  6091. tempBv.Copy(this->currentBlock->byteCodeUpwardExposedUsed);
  6092. #endif
  6093. PropertySym *unusedPropertySym = nullptr;
  6094. GlobOpt::TrackByteCodeSymUsed(instr, this->currentBlock->byteCodeUpwardExposedUsed, &unusedPropertySym);
  6095. #if DBG
  6096. BVSparse<JitArenaAllocator> tempBv2(this->tempAlloc);
  6097. tempBv2.Copy(this->currentBlock->byteCodeUpwardExposedUsed);
  6098. tempBv2.Minus(&tempBv);
  6099. FOREACH_BITSET_IN_SPARSEBV(symId, &tempBv2)
  6100. {
  6101. StackSym * stackSym = this->func->m_symTable->FindStackSym(symId);
  6102. Assert(stackSym->GetType() == TyVar);
  6103. // TODO: We can only track first level function stack syms right now
  6104. if (stackSym->GetByteCodeFunc() == this->func)
  6105. {
  6106. Js::RegSlot byteCodeRegSlot = stackSym->GetByteCodeRegSlot();
  6107. Assert(byteCodeRegSlot != Js::Constants::NoRegister);
  6108. if (this->currentBlock->byteCodeRestoreSyms[byteCodeRegSlot] != stackSym)
  6109. {
  6110. AssertMsg(this->currentBlock->byteCodeRestoreSyms[byteCodeRegSlot] == nullptr,
  6111. "Can't have two active lifetime for the same byte code register");
  6112. this->currentBlock->byteCodeRestoreSyms[byteCodeRegSlot] = stackSym;
  6113. }
  6114. }
  6115. }
  6116. NEXT_BITSET_IN_SPARSEBV;
  6117. #endif
  6118. }
  6119. // If this is a pre-op bailout instruction, we may have saved it for bailout info processing. It's being removed now, so no
  6120. // need to process the bailout info anymore.
  6121. Assert(!preOpBailOutInstrToProcess || preOpBailOutInstrToProcess == instr);
  6122. preOpBailOutInstrToProcess = nullptr;
  6123. #if DBG
  6124. if (this->DoMarkTempObjectVerify())
  6125. {
  6126. this->currentBlock->tempObjectVerifyTracker->NotifyDeadStore(instr, this);
  6127. }
  6128. #endif
  6129. if (instr->m_opcode == Js::OpCode::ArgIn_A)
  6130. {
  6131. //Ignore tracking ArgIn for "this", as argInsCount only tracks other params - unless it is a asmjs function(which doesn't have a "this").
  6132. if (instr->GetSrc1()->AsSymOpnd()->m_sym->AsStackSym()->GetParamSlotNum() != 1 || func->GetJITFunctionBody()->IsAsmJsMode())
  6133. {
  6134. Assert(this->func->argInsCount > 0);
  6135. this->func->argInsCount--;
  6136. }
  6137. }
  6138. TraceDeadStoreOfInstrsForScopeObjectRemoval();
  6139. block->RemoveInstr(instr);
  6140. return true;
  6141. }
  6142. void
  6143. BackwardPass::ProcessTransfers(IR::Instr * instr)
  6144. {
  6145. if (this->tag == Js::DeadStorePhase &&
  6146. this->currentBlock->upwardExposedFields &&
  6147. instr->m_opcode == Js::OpCode::Ld_A &&
  6148. instr->GetDst()->GetStackSym() &&
  6149. !instr->GetDst()->GetStackSym()->IsTypeSpec() &&
  6150. instr->GetDst()->GetStackSym()->HasObjectInfo() &&
  6151. instr->GetSrc1() &&
  6152. instr->GetSrc1()->GetStackSym() &&
  6153. !instr->GetSrc1()->GetStackSym()->IsTypeSpec() &&
  6154. instr->GetSrc1()->GetStackSym()->HasObjectInfo())
  6155. {
  6156. StackSym * dstStackSym = instr->GetDst()->GetStackSym();
  6157. PropertySym * dstPropertySym = dstStackSym->GetObjectInfo()->m_propertySymList;
  6158. BVSparse<JitArenaAllocator> transferFields(this->tempAlloc);
  6159. while (dstPropertySym != nullptr)
  6160. {
  6161. Assert(dstPropertySym->m_stackSym == dstStackSym);
  6162. transferFields.Set(dstPropertySym->m_id);
  6163. dstPropertySym = dstPropertySym->m_nextInStackSymList;
  6164. }
  6165. StackSym * srcStackSym = instr->GetSrc1()->GetStackSym();
  6166. PropertySym * srcPropertySym = srcStackSym->GetObjectInfo()->m_propertySymList;
  6167. BVSparse<JitArenaAllocator> equivFields(this->tempAlloc);
  6168. while (srcPropertySym != nullptr && !transferFields.IsEmpty())
  6169. {
  6170. Assert(srcPropertySym->m_stackSym == srcStackSym);
  6171. if (srcPropertySym->m_propertyEquivSet)
  6172. {
  6173. equivFields.And(&transferFields, srcPropertySym->m_propertyEquivSet);
  6174. if (!equivFields.IsEmpty())
  6175. {
  6176. transferFields.Minus(&equivFields);
  6177. this->currentBlock->upwardExposedFields->Set(srcPropertySym->m_id);
  6178. }
  6179. }
  6180. srcPropertySym = srcPropertySym->m_nextInStackSymList;
  6181. }
  6182. }
  6183. }
  6184. void
  6185. BackwardPass::ProcessFieldKills(IR::Instr * instr)
  6186. {
  6187. if (this->currentBlock->upwardExposedFields)
  6188. {
  6189. this->globOpt->ProcessFieldKills(instr, this->currentBlock->upwardExposedFields, false);
  6190. }
  6191. this->ClearBucketsOnFieldKill(instr, currentBlock->stackSymToFinalType);
  6192. this->ClearBucketsOnFieldKill(instr, currentBlock->stackSymToGuardedProperties);
  6193. }
  6194. template<typename T>
  6195. void
  6196. BackwardPass::ClearBucketsOnFieldKill(IR::Instr *instr, HashTable<T> *table)
  6197. {
  6198. if (table)
  6199. {
  6200. if (instr->UsesAllFields())
  6201. {
  6202. table->ClearAll();
  6203. }
  6204. else
  6205. {
  6206. IR::Opnd *dst = instr->GetDst();
  6207. if (dst && dst->IsRegOpnd())
  6208. {
  6209. table->Clear(dst->AsRegOpnd()->m_sym->m_id);
  6210. }
  6211. }
  6212. }
  6213. }
  6214. void
  6215. BackwardPass::ProcessFieldHoistKills(IR::Instr * instr)
  6216. {
  6217. // The backward pass, we optimistically will not kill on a[] access
  6218. // So that the field hoist candidate will be more then what can be hoisted
  6219. // The root prepass will figure out the exact set of field that is hoisted
  6220. this->globOpt->ProcessFieldKills(instr, this->currentBlock->fieldHoistCandidates, false);
  6221. switch (instr->m_opcode)
  6222. {
  6223. case Js::OpCode::BrOnHasProperty:
  6224. case Js::OpCode::BrOnNoProperty:
  6225. // Should not hoist pass these instructions
  6226. this->currentBlock->fieldHoistCandidates->Clear(instr->GetSrc1()->AsSymOpnd()->m_sym->m_id);
  6227. break;
  6228. }
  6229. }
  6230. bool
  6231. BackwardPass::TrackNoImplicitCallInlinees(IR::Instr *instr)
  6232. {
  6233. if (this->tag != Js::DeadStorePhase || this->IsPrePass())
  6234. {
  6235. return false;
  6236. }
  6237. if (instr->HasBailOutInfo()
  6238. || OpCodeAttr::CallInstr(instr->m_opcode)
  6239. || instr->CallsAccessor()
  6240. || GlobOpt::MayNeedBailOnImplicitCall(instr, nullptr, nullptr)
  6241. || instr->HasAnyLoadHeapArgsOpCode()
  6242. || instr->m_opcode == Js::OpCode::LdFuncExpr)
  6243. {
  6244. // This func has instrs with bailouts or implicit calls
  6245. Assert(instr->m_opcode != Js::OpCode::InlineeStart);
  6246. instr->m_func->SetHasImplicitCallsOnSelfAndParents();
  6247. return false;
  6248. }
  6249. if (instr->m_opcode == Js::OpCode::InlineeStart)
  6250. {
  6251. if (!instr->GetSrc1())
  6252. {
  6253. Assert(instr->m_func->m_hasInlineArgsOpt);
  6254. return false;
  6255. }
  6256. return this->ProcessInlineeStart(instr);
  6257. }
  6258. return false;
  6259. }
  6260. bool
  6261. BackwardPass::ProcessInlineeStart(IR::Instr* inlineeStart)
  6262. {
  6263. inlineeStart->m_func->SetFirstArgOffset(inlineeStart);
  6264. IR::Instr* startCallInstr = nullptr;
  6265. bool noImplicitCallsInInlinee = false;
  6266. // Inlinee has no bailouts or implicit calls. Get rid of the inline overhead.
  6267. auto removeInstr = [&](IR::Instr* argInstr)
  6268. {
  6269. Assert(argInstr->m_opcode == Js::OpCode::InlineeStart || argInstr->m_opcode == Js::OpCode::ArgOut_A || argInstr->m_opcode == Js::OpCode::ArgOut_A_Inline);
  6270. IR::Opnd *opnd = argInstr->GetSrc1();
  6271. StackSym *sym = opnd->GetStackSym();
  6272. if (!opnd->GetIsJITOptimizedReg() && sym && sym->HasByteCodeRegSlot())
  6273. {
  6274. // Replace instrs with bytecodeUses
  6275. IR::ByteCodeUsesInstr *bytecodeUse = IR::ByteCodeUsesInstr::New(argInstr);
  6276. bytecodeUse->Set(opnd);
  6277. argInstr->InsertBefore(bytecodeUse);
  6278. }
  6279. startCallInstr = argInstr->GetSrc2()->GetStackSym()->m_instrDef;
  6280. FlowGraph::SafeRemoveInstr(argInstr);
  6281. return false;
  6282. };
  6283. // If there are no implicit calls - bailouts/throws - we can remove all inlining overhead.
  6284. if (!inlineeStart->m_func->GetHasImplicitCalls())
  6285. {
  6286. noImplicitCallsInInlinee = true;
  6287. inlineeStart->IterateArgInstrs(removeInstr);
  6288. inlineeStart->IterateMetaArgs([](IR::Instr* metArg)
  6289. {
  6290. FlowGraph::SafeRemoveInstr(metArg);
  6291. return false;
  6292. });
  6293. inlineeStart->m_func->m_hasInlineArgsOpt = false;
  6294. removeInstr(inlineeStart);
  6295. return true;
  6296. }
  6297. if (!inlineeStart->m_func->m_hasInlineArgsOpt)
  6298. {
  6299. 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"),
  6300. func->GetJITFunctionBody()->GetDisplayName(), func->GetJITFunctionBody()->GetFunctionNumber(),
  6301. inlineeStart->m_func->GetJITFunctionBody()->GetDisplayName(), inlineeStart->m_func->GetJITFunctionBody()->GetFunctionNumber(),
  6302. IsTrueOrFalse(inlineeStart->m_func->GetHasCalls()),
  6303. IsTrueOrFalse(inlineeStart->m_func->GetHasUnoptimizedArgumentsAccess()),
  6304. IsTrueOrFalse(inlineeStart->m_func->m_canDoInlineArgsOpt));
  6305. return false;
  6306. }
  6307. if (!inlineeStart->m_func->frameInfo->isRecorded)
  6308. {
  6309. PHASE_PRINT_TESTTRACE(Js::InlineArgsOptPhase, func, _u("%s[%d]: InlineeEnd not found - usually due to a throw or a BailOnNoProfile (stressed, most likely)\n"),
  6310. func->GetJITFunctionBody()->GetDisplayName(), func->GetJITFunctionBody()->GetFunctionNumber());
  6311. inlineeStart->m_func->DisableCanDoInlineArgOpt();
  6312. return false;
  6313. }
  6314. inlineeStart->IterateArgInstrs(removeInstr);
  6315. int i = 0;
  6316. inlineeStart->IterateMetaArgs([&](IR::Instr* metaArg)
  6317. {
  6318. if (i == Js::Constants::InlineeMetaArgIndex_ArgumentsObject &&
  6319. inlineeStart->m_func->GetJITFunctionBody()->UsesArgumentsObject())
  6320. {
  6321. Assert(!inlineeStart->m_func->GetHasUnoptimizedArgumentsAccess());
  6322. // Do not remove arguments object meta arg if there is a reference to arguments object
  6323. }
  6324. else
  6325. {
  6326. FlowGraph::SafeRemoveInstr(metaArg);
  6327. }
  6328. i++;
  6329. return false;
  6330. });
  6331. IR::Opnd *src1 = inlineeStart->GetSrc1();
  6332. StackSym *sym = src1->GetStackSym();
  6333. if (!src1->GetIsJITOptimizedReg() && sym && sym->HasByteCodeRegSlot())
  6334. {
  6335. // Replace instrs with bytecodeUses
  6336. IR::ByteCodeUsesInstr *bytecodeUse = IR::ByteCodeUsesInstr::New(inlineeStart);
  6337. bytecodeUse->Set(src1);
  6338. inlineeStart->InsertBefore(bytecodeUse);
  6339. }
  6340. // This indicates to the lowerer that this inlinee has been optimized
  6341. // and it should not be lowered - Now this instruction is used to mark inlineeStart
  6342. inlineeStart->FreeSrc1();
  6343. inlineeStart->FreeSrc2();
  6344. inlineeStart->FreeDst();
  6345. return true;
  6346. }
  6347. void
  6348. BackwardPass::ProcessInlineeEnd(IR::Instr* instr)
  6349. {
  6350. if (this->IsPrePass())
  6351. {
  6352. return;
  6353. }
  6354. if (this->tag == Js::BackwardPhase)
  6355. {
  6356. if (!GlobOpt::DoInlineArgsOpt(instr->m_func))
  6357. {
  6358. return;
  6359. }
  6360. // This adds a use for function sym as part of InlineeStart & all the syms referenced by the args.
  6361. // It ensure they do not get cleared from the copy prop sym map.
  6362. instr->IterateArgInstrs([=](IR::Instr* argInstr){
  6363. if (argInstr->GetSrc1()->IsRegOpnd())
  6364. {
  6365. this->currentBlock->upwardExposedUses->Set(argInstr->GetSrc1()->AsRegOpnd()->m_sym->m_id);
  6366. }
  6367. return false;
  6368. });
  6369. }
  6370. else if (this->tag == Js::DeadStorePhase)
  6371. {
  6372. if (instr->m_func->m_hasInlineArgsOpt)
  6373. {
  6374. Assert(instr->m_func->frameInfo);
  6375. instr->m_func->frameInfo->IterateSyms([=](StackSym* argSym)
  6376. {
  6377. this->currentBlock->upwardExposedUses->Set(argSym->m_id);
  6378. });
  6379. }
  6380. }
  6381. }
  6382. bool
  6383. BackwardPass::ProcessBailOnNoProfile(IR::Instr *instr, BasicBlock *block)
  6384. {
  6385. Assert(this->tag == Js::BackwardPhase);
  6386. Assert(instr->m_opcode == Js::OpCode::BailOnNoProfile);
  6387. Assert(!instr->HasBailOutInfo());
  6388. AnalysisAssert(block);
  6389. if (this->IsPrePass())
  6390. {
  6391. return false;
  6392. }
  6393. if (this->currentRegion && (this->currentRegion->GetType() == RegionTypeCatch || this->currentRegion->GetType() == RegionTypeFinally))
  6394. {
  6395. return false;
  6396. }
  6397. IR::Instr *curInstr = instr->m_prev;
  6398. if (curInstr->IsLabelInstr() && curInstr->AsLabelInstr()->isOpHelper)
  6399. {
  6400. // Already processed
  6401. if (this->DoMarkTempObjects())
  6402. {
  6403. block->tempObjectTracker->ProcessBailOnNoProfile(instr);
  6404. }
  6405. return false;
  6406. }
  6407. // Don't hoist if we see calls with profile data (recursive calls)
  6408. while(!curInstr->StartsBasicBlock())
  6409. {
  6410. // If a function was inlined, it must have had profile info.
  6411. if (curInstr->m_opcode == Js::OpCode::InlineeEnd || curInstr->m_opcode == Js::OpCode::InlineBuiltInEnd || curInstr->m_opcode == Js::OpCode::InlineNonTrackingBuiltInEnd
  6412. || curInstr->m_opcode == Js::OpCode::InlineeStart || curInstr->m_opcode == Js::OpCode::EndCallForPolymorphicInlinee)
  6413. {
  6414. break;
  6415. }
  6416. else if (OpCodeAttr::CallInstr(curInstr->m_opcode))
  6417. {
  6418. if (curInstr->m_prev->m_opcode != Js::OpCode::BailOnNoProfile)
  6419. {
  6420. break;
  6421. }
  6422. }
  6423. curInstr = curInstr->m_prev;
  6424. }
  6425. // Didn't get to the top of the block, delete this BailOnNoProfile.
  6426. if (!curInstr->IsLabelInstr())
  6427. {
  6428. block->RemoveInstr(instr);
  6429. return true;
  6430. }
  6431. // Save the head instruction for later use.
  6432. IR::LabelInstr *blockHeadInstr = curInstr->AsLabelInstr();
  6433. // We can't bail in the middle of a "tmp = CmEq s1, s2; BrTrue tmp" turned into a "BrEq s1, s2",
  6434. // because the bailout wouldn't be able to restore tmp.
  6435. IR::Instr *curNext = curInstr->GetNextRealInstrOrLabel();
  6436. IR::Instr *instrNope = nullptr;
  6437. if (curNext->m_opcode == Js::OpCode::Ld_A && curNext->GetDst()->IsRegOpnd() && curNext->GetDst()->AsRegOpnd()->m_fgPeepTmp)
  6438. {
  6439. block->RemoveInstr(instr);
  6440. return true;
  6441. /*while (curNext->m_opcode == Js::OpCode::Ld_A && curNext->GetDst()->IsRegOpnd() && curNext->GetDst()->AsRegOpnd()->m_fgPeepTmp)
  6442. {
  6443. // Instead of just giving up, we can be a little trickier. We can instead treat the tmp declaration(s) as a
  6444. // part of the block prefix, and put the bailonnoprofile immediately after them. This has the added benefit
  6445. // that we can still merge up blocks beginning with bailonnoprofile, even if they would otherwise not allow
  6446. // us to, due to the fact that these tmp declarations would be pre-empted by the higher-level bailout.
  6447. instrNope = curNext;
  6448. curNext = curNext->GetNextRealInstrOrLabel();
  6449. }*/
  6450. }
  6451. curInstr = instr->m_prev;
  6452. // Move to top of block (but just below any fgpeeptemp lds).
  6453. while(!curInstr->StartsBasicBlock() && curInstr != instrNope)
  6454. {
  6455. // Delete redundant BailOnNoProfile
  6456. if (curInstr->m_opcode == Js::OpCode::BailOnNoProfile)
  6457. {
  6458. Assert(!curInstr->HasBailOutInfo());
  6459. curInstr = curInstr->m_next;
  6460. curInstr->m_prev->Remove();
  6461. }
  6462. curInstr = curInstr->m_prev;
  6463. }
  6464. if (instr == block->GetLastInstr())
  6465. {
  6466. block->SetLastInstr(instr->m_prev);
  6467. }
  6468. instr->Unlink();
  6469. // Now try to move this up the flowgraph to the predecessor blocks
  6470. FOREACH_PREDECESSOR_BLOCK(pred, block)
  6471. {
  6472. bool hoistBailToPred = true;
  6473. if (block->isLoopHeader && pred->loop == block->loop)
  6474. {
  6475. // Skip loop back-edges
  6476. continue;
  6477. }
  6478. if (pred->GetFirstInstr()->AsLabelInstr()->GetRegion() != this->currentRegion)
  6479. {
  6480. break;
  6481. }
  6482. // If all successors of this predecessor start with a BailOnNoProfile, we should be
  6483. // okay to hoist this bail to the predecessor.
  6484. FOREACH_SUCCESSOR_BLOCK(predSucc, pred)
  6485. {
  6486. if (predSucc == block)
  6487. {
  6488. continue;
  6489. }
  6490. if (!predSucc->beginsBailOnNoProfile)
  6491. {
  6492. hoistBailToPred = false;
  6493. break;
  6494. }
  6495. } NEXT_SUCCESSOR_BLOCK;
  6496. if (hoistBailToPred)
  6497. {
  6498. IR::Instr *predInstr = pred->GetLastInstr();
  6499. IR::Instr *instrCopy = instr->Copy();
  6500. if (predInstr->EndsBasicBlock())
  6501. {
  6502. if (predInstr->m_prev->m_opcode == Js::OpCode::BailOnNoProfile)
  6503. {
  6504. // We already have one, we don't need a second.
  6505. instrCopy->Free();
  6506. }
  6507. else if (!predInstr->AsBranchInstr()->m_isSwitchBr)
  6508. {
  6509. // Don't put a bailout in the middle of a switch dispatch sequence.
  6510. // The bytecode offsets are not in order, and it would lead to incorrect
  6511. // bailout info.
  6512. instrCopy->m_func = predInstr->m_func;
  6513. predInstr->InsertBefore(instrCopy);
  6514. }
  6515. }
  6516. else
  6517. {
  6518. if (predInstr->m_opcode == Js::OpCode::BailOnNoProfile)
  6519. {
  6520. // We already have one, we don't need a second.
  6521. instrCopy->Free();
  6522. }
  6523. else
  6524. {
  6525. instrCopy->m_func = predInstr->m_func;
  6526. predInstr->InsertAfter(instrCopy);
  6527. pred->SetLastInstr(instrCopy);
  6528. }
  6529. }
  6530. }
  6531. } NEXT_PREDECESSOR_BLOCK;
  6532. // If we have a BailOnNoProfile in the first block, there must have been at least one path out of this block that always throws.
  6533. // Don't bother keeping the bailout in the first block as there are some issues in restoring the ArgIn bytecode registers on bailout
  6534. // and throw case should be rare enough that it won't matter for perf.
  6535. if (block->GetBlockNum() != 0)
  6536. {
  6537. blockHeadInstr->isOpHelper = true;
  6538. #if DBG
  6539. blockHeadInstr->m_noHelperAssert = true;
  6540. #endif
  6541. block->beginsBailOnNoProfile = true;
  6542. instr->m_func = curInstr->m_func;
  6543. curInstr->InsertAfter(instr);
  6544. bool setLastInstr = (curInstr == block->GetLastInstr());
  6545. if (setLastInstr)
  6546. {
  6547. block->SetLastInstr(instr);
  6548. }
  6549. if (this->DoMarkTempObjects())
  6550. {
  6551. block->tempObjectTracker->ProcessBailOnNoProfile(instr);
  6552. }
  6553. return false;
  6554. }
  6555. else
  6556. {
  6557. instr->Free();
  6558. return true;
  6559. }
  6560. }
  6561. bool
  6562. BackwardPass::ReverseCopyProp(IR::Instr *instr)
  6563. {
  6564. // Look for :
  6565. //
  6566. // t1 = instr
  6567. // [bytecodeuse t1]
  6568. // t2 = Ld_A t1 >> t1 !upwardExposed
  6569. //
  6570. // Transform into:
  6571. //
  6572. // t2 = instr
  6573. //
  6574. if (PHASE_OFF(Js::ReverseCopyPropPhase, this->func))
  6575. {
  6576. return false;
  6577. }
  6578. if (this->tag != Js::DeadStorePhase || this->IsPrePass() || this->IsCollectionPass())
  6579. {
  6580. return false;
  6581. }
  6582. if (this->func->HasTry())
  6583. {
  6584. // UpwardExposedUsed info can't be relied on
  6585. return false;
  6586. }
  6587. // Find t2 = Ld_A t1
  6588. switch (instr->m_opcode)
  6589. {
  6590. case Js::OpCode::Ld_A:
  6591. case Js::OpCode::Ld_I4:
  6592. break;
  6593. default:
  6594. return false;
  6595. }
  6596. if (!instr->GetDst()->IsRegOpnd())
  6597. {
  6598. return false;
  6599. }
  6600. if (!instr->GetSrc1()->IsRegOpnd())
  6601. {
  6602. return false;
  6603. }
  6604. if (instr->HasBailOutInfo())
  6605. {
  6606. return false;
  6607. }
  6608. IR::RegOpnd *dst = instr->GetDst()->AsRegOpnd();
  6609. IR::RegOpnd *src = instr->GetSrc1()->AsRegOpnd();
  6610. IR::Instr *instrPrev = instr->GetPrevRealInstrOrLabel();
  6611. IR::ByteCodeUsesInstr *byteCodeUseInstr = nullptr;
  6612. StackSym *varSym = src->m_sym;
  6613. if (varSym->IsTypeSpec())
  6614. {
  6615. varSym = varSym->GetVarEquivSym(this->func);
  6616. }
  6617. // SKip ByteCodeUse instr if possible
  6618. // [bytecodeuse t1]
  6619. if (!instrPrev->GetDst())
  6620. {
  6621. if (instrPrev->m_opcode == Js::OpCode::ByteCodeUses)
  6622. {
  6623. byteCodeUseInstr = instrPrev->AsByteCodeUsesInstr();
  6624. const BVSparse<JitArenaAllocator>* byteCodeUpwardExposedUsed = byteCodeUseInstr->GetByteCodeUpwardExposedUsed();
  6625. if (byteCodeUpwardExposedUsed && byteCodeUpwardExposedUsed->Test(varSym->m_id) && byteCodeUpwardExposedUsed->Count() == 1)
  6626. {
  6627. instrPrev = byteCodeUseInstr->GetPrevRealInstrOrLabel();
  6628. if (!instrPrev->GetDst())
  6629. {
  6630. return false;
  6631. }
  6632. }
  6633. else
  6634. {
  6635. return false;
  6636. }
  6637. }
  6638. else
  6639. {
  6640. return false;
  6641. }
  6642. }
  6643. // The fast-path for these doesn't handle dst == src.
  6644. // REVIEW: I believe the fast-path for LdElemI_A has been fixed... Nope, still broken for "i = A[i]" for prejit
  6645. switch (instrPrev->m_opcode)
  6646. {
  6647. case Js::OpCode::LdElemI_A:
  6648. case Js::OpCode::IsInst:
  6649. case Js::OpCode::ByteCodeUses:
  6650. return false;
  6651. }
  6652. // Can't do it if post-op bailout would need result
  6653. // REVIEW: enable for pre-opt bailout?
  6654. if (instrPrev->HasBailOutInfo() && instrPrev->GetByteCodeOffset() != instrPrev->GetBailOutInfo()->bailOutOffset)
  6655. {
  6656. return false;
  6657. }
  6658. // Make sure src of Ld_A == dst of instr
  6659. // t1 = instr
  6660. if (!instrPrev->GetDst()->IsEqual(src))
  6661. {
  6662. return false;
  6663. }
  6664. // Make sure t1 isn't used later
  6665. if (this->currentBlock->upwardExposedUses->Test(src->m_sym->m_id))
  6666. {
  6667. return false;
  6668. }
  6669. if (this->currentBlock->byteCodeUpwardExposedUsed && this->currentBlock->byteCodeUpwardExposedUsed->Test(varSym->m_id))
  6670. {
  6671. return false;
  6672. }
  6673. // Make sure we can dead-store this sym (debugger mode?)
  6674. if (!this->DoDeadStore(this->func, src->m_sym))
  6675. {
  6676. return false;
  6677. }
  6678. StackSym *const dstSym = dst->m_sym;
  6679. if(instrPrev->HasBailOutInfo() && dstSym->IsInt32() && dstSym->IsTypeSpec())
  6680. {
  6681. StackSym *const prevDstSym = IR::RegOpnd::TryGetStackSym(instrPrev->GetDst());
  6682. if(instrPrev->GetBailOutKind() & IR::BailOutOnResultConditions &&
  6683. prevDstSym &&
  6684. prevDstSym->IsInt32() &&
  6685. prevDstSym->IsTypeSpec() &&
  6686. instrPrev->GetSrc1() &&
  6687. !instrPrev->GetDst()->IsEqual(instrPrev->GetSrc1()) &&
  6688. !(instrPrev->GetSrc2() && instrPrev->GetDst()->IsEqual(instrPrev->GetSrc2())))
  6689. {
  6690. // The previous instruction's dst value may be trashed by the time of the pre-op bailout. Skip reverse copy-prop if
  6691. // it would replace the previous instruction's dst with a sym that bailout had decided to use to restore a value for
  6692. // the pre-op bailout, which can't be trashed before bailout. See big comment in ProcessBailOutCopyProps for the
  6693. // reasoning behind the tests above.
  6694. FOREACH_SLISTBASE_ENTRY(
  6695. CopyPropSyms,
  6696. usedCopyPropSym,
  6697. &instrPrev->GetBailOutInfo()->usedCapturedValues.copyPropSyms)
  6698. {
  6699. if(dstSym == usedCopyPropSym.Value())
  6700. {
  6701. return false;
  6702. }
  6703. } NEXT_SLISTBASE_ENTRY;
  6704. }
  6705. }
  6706. if (byteCodeUseInstr)
  6707. {
  6708. if (this->currentBlock->byteCodeUpwardExposedUsed && instrPrev->GetDst()->AsRegOpnd()->GetIsJITOptimizedReg() && varSym->HasByteCodeRegSlot())
  6709. {
  6710. if(varSym->HasByteCodeRegSlot())
  6711. {
  6712. this->currentBlock->byteCodeUpwardExposedUsed->Set(varSym->m_id);
  6713. }
  6714. if (src->IsEqual(dst) && instrPrev->GetDst()->GetIsJITOptimizedReg())
  6715. {
  6716. // s2(s1).i32 = FromVar s1.var #0000 Bailout: #0000 (BailOutIntOnly)
  6717. // ByteCodeUses s1
  6718. // s2(s1).i32 = Ld_A s2(s1).i32
  6719. //
  6720. // Since the dst on the FromVar is marked JITOptimized, we need to set it on the new dst as well,
  6721. // or we'll change the bytecode liveness of s1
  6722. dst->SetIsJITOptimizedReg(true);
  6723. }
  6724. }
  6725. byteCodeUseInstr->Remove();
  6726. }
  6727. else if (instrPrev->GetDst()->AsRegOpnd()->GetIsJITOptimizedReg() && !src->GetIsJITOptimizedReg() && varSym->HasByteCodeRegSlot())
  6728. {
  6729. this->currentBlock->byteCodeUpwardExposedUsed->Set(varSym->m_id);
  6730. }
  6731. #if DBG
  6732. if (this->DoMarkTempObjectVerify())
  6733. {
  6734. this->currentBlock->tempObjectVerifyTracker->NotifyReverseCopyProp(instrPrev);
  6735. }
  6736. #endif
  6737. dst->SetValueType(instrPrev->GetDst()->GetValueType());
  6738. instrPrev->ReplaceDst(dst);
  6739. instr->Remove();
  6740. return true;
  6741. }
  6742. bool
  6743. BackwardPass::FoldCmBool(IR::Instr *instr)
  6744. {
  6745. Assert(instr->m_opcode == Js::OpCode::Conv_Bool);
  6746. if (this->tag != Js::DeadStorePhase || this->IsPrePass() || this->IsCollectionPass())
  6747. {
  6748. return false;
  6749. }
  6750. if (this->func->HasTry())
  6751. {
  6752. // UpwardExposedUsed info can't be relied on
  6753. return false;
  6754. }
  6755. IR::RegOpnd *intOpnd = instr->GetSrc1()->AsRegOpnd();
  6756. Assert(intOpnd->m_sym->IsInt32());
  6757. if (!intOpnd->m_sym->IsSingleDef())
  6758. {
  6759. return false;
  6760. }
  6761. IR::Instr *cmInstr = intOpnd->m_sym->GetInstrDef();
  6762. // Should be a Cm instr...
  6763. if (!cmInstr->GetSrc2())
  6764. {
  6765. return false;
  6766. }
  6767. IR::Instr *instrPrev = instr->GetPrevRealInstrOrLabel();
  6768. if (instrPrev != cmInstr)
  6769. {
  6770. return false;
  6771. }
  6772. switch (cmInstr->m_opcode)
  6773. {
  6774. case Js::OpCode::CmEq_A:
  6775. case Js::OpCode::CmGe_A:
  6776. case Js::OpCode::CmUnGe_A:
  6777. case Js::OpCode::CmGt_A:
  6778. case Js::OpCode::CmUnGt_A:
  6779. case Js::OpCode::CmLt_A:
  6780. case Js::OpCode::CmUnLt_A:
  6781. case Js::OpCode::CmLe_A:
  6782. case Js::OpCode::CmUnLe_A:
  6783. case Js::OpCode::CmNeq_A:
  6784. case Js::OpCode::CmSrEq_A:
  6785. case Js::OpCode::CmSrNeq_A:
  6786. case Js::OpCode::CmEq_I4:
  6787. case Js::OpCode::CmNeq_I4:
  6788. case Js::OpCode::CmLt_I4:
  6789. case Js::OpCode::CmLe_I4:
  6790. case Js::OpCode::CmGt_I4:
  6791. case Js::OpCode::CmGe_I4:
  6792. case Js::OpCode::CmUnLt_I4:
  6793. case Js::OpCode::CmUnLe_I4:
  6794. case Js::OpCode::CmUnGt_I4:
  6795. case Js::OpCode::CmUnGe_I4:
  6796. break;
  6797. default:
  6798. return false;
  6799. }
  6800. IR::RegOpnd *varDst = instr->GetDst()->AsRegOpnd();
  6801. if (this->currentBlock->upwardExposedUses->Test(intOpnd->m_sym->m_id) || !this->currentBlock->upwardExposedUses->Test(varDst->m_sym->m_id))
  6802. {
  6803. return false;
  6804. }
  6805. varDst = instr->UnlinkDst()->AsRegOpnd();
  6806. cmInstr->ReplaceDst(varDst);
  6807. this->currentBlock->RemoveInstr(instr);
  6808. return true;
  6809. }
  6810. void
  6811. BackwardPass::SetWriteThroughSymbolsSetForRegion(BasicBlock * catchOrFinallyBlock, Region * tryRegion)
  6812. {
  6813. tryRegion->writeThroughSymbolsSet = JitAnew(this->func->m_alloc, BVSparse<JitArenaAllocator>, this->func->m_alloc);
  6814. if (this->DoByteCodeUpwardExposedUsed())
  6815. {
  6816. Assert(catchOrFinallyBlock->byteCodeUpwardExposedUsed);
  6817. if (!catchOrFinallyBlock->byteCodeUpwardExposedUsed->IsEmpty())
  6818. {
  6819. FOREACH_BITSET_IN_SPARSEBV(id, catchOrFinallyBlock->byteCodeUpwardExposedUsed)
  6820. {
  6821. tryRegion->writeThroughSymbolsSet->Set(id);
  6822. }
  6823. NEXT_BITSET_IN_SPARSEBV
  6824. }
  6825. #if DBG
  6826. // Symbols write-through in the parent try region should be marked as write-through in the current try region as well.
  6827. // x =
  6828. // try{
  6829. // try{
  6830. // x = <-- x needs to be write-through here. With the current mechanism of not clearing a write-through
  6831. // symbol from the bytecode upward-exposed on a def, x should be marked as write-through as
  6832. // write-through symbols for a try are basically the bytecode upward exposed symbols at the
  6833. // beginning of the corresponding catch block).
  6834. // Verify that it still holds.
  6835. // <exception>
  6836. // }
  6837. // catch(){}
  6838. // x =
  6839. // }
  6840. // catch(){}
  6841. // = x
  6842. if (tryRegion->GetParent()->GetType() == RegionTypeTry)
  6843. {
  6844. Region * parentTry = tryRegion->GetParent();
  6845. Assert(parentTry->writeThroughSymbolsSet);
  6846. FOREACH_BITSET_IN_SPARSEBV(id, parentTry->writeThroughSymbolsSet)
  6847. {
  6848. Assert(tryRegion->writeThroughSymbolsSet->Test(id));
  6849. }
  6850. NEXT_BITSET_IN_SPARSEBV
  6851. }
  6852. #endif
  6853. }
  6854. else
  6855. {
  6856. // this can happen with -off:globopt
  6857. return;
  6858. }
  6859. }
  6860. bool
  6861. BackwardPass::CheckWriteThroughSymInRegion(Region* region, StackSym* sym)
  6862. {
  6863. if (region->GetType() == RegionTypeRoot)
  6864. {
  6865. return false;
  6866. }
  6867. // if the current region is a try region, check in its write-through set,
  6868. // otherwise (current = catch region) look in the first try ancestor's write-through set
  6869. Region * selfOrFirstTryAncestor = region->GetSelfOrFirstTryAncestor();
  6870. if (!selfOrFirstTryAncestor)
  6871. {
  6872. return false;
  6873. }
  6874. Assert(selfOrFirstTryAncestor->GetType() == RegionTypeTry);
  6875. return selfOrFirstTryAncestor->writeThroughSymbolsSet && selfOrFirstTryAncestor->writeThroughSymbolsSet->Test(sym->m_id);
  6876. }
  6877. bool
  6878. BackwardPass::DoDeadStoreLdStForMemop(IR::Instr *instr)
  6879. {
  6880. Assert(this->tag == Js::DeadStorePhase && this->currentBlock->loop != nullptr);
  6881. Loop *loop = this->currentBlock->loop;
  6882. if (globOpt->HasMemOp(loop))
  6883. {
  6884. if (instr->m_opcode == Js::OpCode::StElemI_A && instr->GetDst()->IsIndirOpnd())
  6885. {
  6886. SymID base = this->globOpt->GetVarSymID(instr->GetDst()->AsIndirOpnd()->GetBaseOpnd()->GetStackSym());
  6887. SymID index = this->globOpt->GetVarSymID(instr->GetDst()->AsIndirOpnd()->GetIndexOpnd()->GetStackSym());
  6888. FOREACH_MEMOP_CANDIDATES(candidate, loop)
  6889. {
  6890. if (base == candidate->base && index == candidate->index)
  6891. {
  6892. return true;
  6893. }
  6894. } NEXT_MEMOP_CANDIDATE
  6895. }
  6896. else if (instr->m_opcode == Js::OpCode::LdElemI_A && instr->GetSrc1()->IsIndirOpnd())
  6897. {
  6898. SymID base = this->globOpt->GetVarSymID(instr->GetSrc1()->AsIndirOpnd()->GetBaseOpnd()->GetStackSym());
  6899. SymID index = this->globOpt->GetVarSymID(instr->GetSrc1()->AsIndirOpnd()->GetIndexOpnd()->GetStackSym());
  6900. FOREACH_MEMCOPY_CANDIDATES(candidate, loop)
  6901. {
  6902. if (base == candidate->ldBase && index == candidate->index)
  6903. {
  6904. return true;
  6905. }
  6906. } NEXT_MEMCOPY_CANDIDATE
  6907. }
  6908. }
  6909. return false;
  6910. }
  6911. void
  6912. BackwardPass::RestoreInductionVariableValuesAfterMemOp(Loop *loop)
  6913. {
  6914. const auto RestoreInductionVariable = [&](SymID symId, Loop::InductionVariableChangeInfo inductionVariableChangeInfo, Loop *loop)
  6915. {
  6916. Js::OpCode opCode = Js::OpCode::Add_I4;
  6917. if (!inductionVariableChangeInfo.isIncremental)
  6918. {
  6919. opCode = Js::OpCode::Sub_I4;
  6920. }
  6921. Func *localFunc = loop->GetFunc();
  6922. StackSym *sym = localFunc->m_symTable->FindStackSym(symId)->GetInt32EquivSym(localFunc);
  6923. IR::Opnd *inductionVariableOpnd = IR::RegOpnd::New(sym, IRType::TyInt32, localFunc);
  6924. IR::Opnd *sizeOpnd = globOpt->GenerateInductionVariableChangeForMemOp(loop, inductionVariableChangeInfo.unroll);
  6925. loop->landingPad->InsertAfter(IR::Instr::New(opCode, inductionVariableOpnd, inductionVariableOpnd, sizeOpnd, loop->GetFunc()));
  6926. };
  6927. for (auto it = loop->memOpInfo->inductionVariableChangeInfoMap->GetIterator(); it.IsValid(); it.MoveNext())
  6928. {
  6929. Loop::InductionVariableChangeInfo iv = it.CurrentValue();
  6930. SymID sym = it.CurrentKey();
  6931. if (iv.unroll != Js::Constants::InvalidLoopUnrollFactor)
  6932. {
  6933. // if the variable is being used after the loop restore it
  6934. if (loop->memOpInfo->inductionVariablesUsedAfterLoop->Test(sym))
  6935. {
  6936. RestoreInductionVariable(sym, iv, loop);
  6937. }
  6938. }
  6939. }
  6940. }
  6941. bool
  6942. BackwardPass::IsEmptyLoopAfterMemOp(Loop *loop)
  6943. {
  6944. if (globOpt->HasMemOp(loop))
  6945. {
  6946. const auto IsInductionVariableUse = [&](IR::Opnd *opnd) -> bool
  6947. {
  6948. Loop::InductionVariableChangeInfo inductionVariableChangeInfo = { 0, 0 };
  6949. return (opnd &&
  6950. opnd->GetStackSym() &&
  6951. loop->memOpInfo->inductionVariableChangeInfoMap->ContainsKey(this->globOpt->GetVarSymID(opnd->GetStackSym())) &&
  6952. (((Loop::InductionVariableChangeInfo)
  6953. loop->memOpInfo->inductionVariableChangeInfoMap->
  6954. LookupWithKey(this->globOpt->GetVarSymID(opnd->GetStackSym()), inductionVariableChangeInfo)).unroll != Js::Constants::InvalidLoopUnrollFactor));
  6955. };
  6956. Assert(loop->blockList.HasTwo());
  6957. FOREACH_BLOCK_IN_LOOP(bblock, loop)
  6958. {
  6959. FOREACH_INSTR_IN_BLOCK_EDITING(instr, instrPrev, bblock)
  6960. {
  6961. if (instr->IsLabelInstr() || !instr->IsRealInstr() || instr->m_opcode == Js::OpCode::IncrLoopBodyCount || instr->m_opcode == Js::OpCode::StLoopBodyCount
  6962. || (instr->IsBranchInstr() && instr->AsBranchInstr()->IsUnconditional()))
  6963. {
  6964. continue;
  6965. }
  6966. else
  6967. {
  6968. switch (instr->m_opcode)
  6969. {
  6970. case Js::OpCode::Nop:
  6971. break;
  6972. case Js::OpCode::Ld_I4:
  6973. case Js::OpCode::Add_I4:
  6974. case Js::OpCode::Sub_I4:
  6975. if (!IsInductionVariableUse(instr->GetDst()))
  6976. {
  6977. Assert(instr->GetDst());
  6978. if (instr->GetDst()->GetStackSym()
  6979. && loop->memOpInfo->inductionVariablesUsedAfterLoop->Test(globOpt->GetVarSymID(instr->GetDst()->GetStackSym())))
  6980. {
  6981. // We have use after the loop for a variable defined inside the loop. So the loop can't be removed.
  6982. return false;
  6983. }
  6984. }
  6985. break;
  6986. case Js::OpCode::Decr_A:
  6987. case Js::OpCode::Incr_A:
  6988. if (!IsInductionVariableUse(instr->GetSrc1()))
  6989. {
  6990. return false;
  6991. }
  6992. break;
  6993. default:
  6994. if (instr->IsBranchInstr())
  6995. {
  6996. if (IsInductionVariableUse(instr->GetSrc1()) || IsInductionVariableUse(instr->GetSrc2()))
  6997. {
  6998. break;
  6999. }
  7000. }
  7001. return false;
  7002. }
  7003. }
  7004. }
  7005. NEXT_INSTR_IN_BLOCK_EDITING;
  7006. }NEXT_BLOCK_IN_LIST;
  7007. return true;
  7008. }
  7009. return false;
  7010. }
  7011. void
  7012. BackwardPass::RemoveEmptyLoops()
  7013. {
  7014. if (PHASE_OFF(Js::MemOpPhase, this->func))
  7015. {
  7016. return;
  7017. }
  7018. const auto DeleteMemOpInfo = [&](Loop *loop)
  7019. {
  7020. JitArenaAllocator *alloc = this->func->GetTopFunc()->m_fg->alloc;
  7021. if (!loop->memOpInfo)
  7022. {
  7023. return;
  7024. }
  7025. if (loop->memOpInfo->candidates)
  7026. {
  7027. loop->memOpInfo->candidates->Clear();
  7028. JitAdelete(alloc, loop->memOpInfo->candidates);
  7029. }
  7030. if (loop->memOpInfo->inductionVariableChangeInfoMap)
  7031. {
  7032. loop->memOpInfo->inductionVariableChangeInfoMap->Clear();
  7033. JitAdelete(alloc, loop->memOpInfo->inductionVariableChangeInfoMap);
  7034. }
  7035. if (loop->memOpInfo->inductionVariableOpndPerUnrollMap)
  7036. {
  7037. loop->memOpInfo->inductionVariableOpndPerUnrollMap->Clear();
  7038. JitAdelete(alloc, loop->memOpInfo->inductionVariableOpndPerUnrollMap);
  7039. }
  7040. if (loop->memOpInfo->inductionVariablesUsedAfterLoop)
  7041. {
  7042. JitAdelete(this->tempAlloc, loop->memOpInfo->inductionVariablesUsedAfterLoop);
  7043. }
  7044. JitAdelete(alloc, loop->memOpInfo);
  7045. };
  7046. FOREACH_LOOP_IN_FUNC_EDITING(loop, this->func)
  7047. {
  7048. if (IsEmptyLoopAfterMemOp(loop))
  7049. {
  7050. RestoreInductionVariableValuesAfterMemOp(loop);
  7051. RemoveEmptyLoopAfterMemOp(loop);
  7052. }
  7053. // Remove memop info as we don't need them after this point.
  7054. DeleteMemOpInfo(loop);
  7055. } NEXT_LOOP_IN_FUNC_EDITING;
  7056. }
  7057. void
  7058. BackwardPass::RemoveEmptyLoopAfterMemOp(Loop *loop)
  7059. {
  7060. BasicBlock *head = loop->GetHeadBlock();
  7061. BasicBlock *tail = head->next;
  7062. BasicBlock *landingPad = loop->landingPad;
  7063. BasicBlock *outerBlock = nullptr;
  7064. SListBaseCounted<FlowEdge *> *succList = head->GetSuccList();
  7065. Assert(succList->HasTwo());
  7066. // Between the two successors of head, one is tail and the other one is the outerBlock
  7067. SListBaseCounted<FlowEdge *>::Iterator iter(succList);
  7068. iter.Next();
  7069. if (iter.Data()->GetSucc() == tail)
  7070. {
  7071. iter.Next();
  7072. outerBlock = iter.Data()->GetSucc();
  7073. }
  7074. else
  7075. {
  7076. outerBlock = iter.Data()->GetSucc();
  7077. #ifdef DBG
  7078. iter.Next();
  7079. Assert(iter.Data()->GetSucc() == tail);
  7080. #endif
  7081. }
  7082. outerBlock->RemovePred(head, this->func->m_fg);
  7083. landingPad->RemoveSucc(head, this->func->m_fg);
  7084. Assert(landingPad->GetSuccList()->Count() == 0);
  7085. IR::Instr* firstOuterInstr = outerBlock->GetFirstInstr();
  7086. AssertOrFailFast(firstOuterInstr->IsLabelInstr() && !landingPad->GetLastInstr()->EndsBasicBlock());
  7087. IR::LabelInstr* label = firstOuterInstr->AsLabelInstr();
  7088. // Add br to Outer block to keep coherence between branches and flow graph
  7089. IR::BranchInstr *outerBr = IR::BranchInstr::New(Js::OpCode::Br, label, this->func);
  7090. landingPad->InsertAfter(outerBr);
  7091. this->func->m_fg->AddEdge(landingPad, outerBlock);
  7092. this->func->m_fg->RemoveBlock(head, nullptr);
  7093. if (head != tail)
  7094. {
  7095. this->func->m_fg->RemoveBlock(tail, nullptr);
  7096. }
  7097. }
  7098. #if DBG_DUMP
  7099. bool
  7100. BackwardPass::IsTraceEnabled() const
  7101. {
  7102. return
  7103. Js::Configuration::Global.flags.Trace.IsEnabled(tag, this->func->GetSourceContextId(), this->func->GetLocalFunctionId()) &&
  7104. (PHASE_TRACE(Js::SimpleJitPhase, func) || !func->IsSimpleJit());
  7105. }
  7106. #endif