BackwardPass.cpp 283 KB

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