GlobOpt.cpp 794 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271
  1. //-------------------------------------------------------------------------------------------------------
  2. // Copyright (C) Microsoft. All rights reserved.
  3. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
  4. //-------------------------------------------------------------------------------------------------------
  5. #include "Backend.h"
  6. #if ENABLE_DEBUG_CONFIG_OPTIONS
  7. #define TESTTRACE_PHASE_INSTR(phase, instr, ...) \
  8. if(PHASE_TESTTRACE(phase, this->func)) \
  9. { \
  10. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE]; \
  11. Output::Print( \
  12. _u("Testtrace: %s function %s (%s): "), \
  13. Js::PhaseNames[phase], \
  14. instr->m_func->GetJnFunction()->GetDisplayName(), \
  15. instr->m_func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer)); \
  16. Output::Print(__VA_ARGS__); \
  17. Output::Flush(); \
  18. }
  19. #else // ENABLE_DEBUG_CONFIG_OPTIONS
  20. #define TESTTRACE_PHASE_INSTR(phase, instr, ...)
  21. #endif // ENABLE_DEBUG_CONFIG_OPTIONS
  22. #if ENABLE_DEBUG_CONFIG_OPTIONS && DBG_DUMP
  23. #define GOPT_TRACE_OPND(opnd, ...) \
  24. if (PHASE_TRACE(Js::GlobOptPhase, this->func) && !this->IsLoopPrePass()) \
  25. { \
  26. Output::Print(_u("TRACE: ")); \
  27. opnd->Dump(); \
  28. Output::Print(_u(" : ")); \
  29. Output::Print(__VA_ARGS__); \
  30. Output::Flush(); \
  31. }
  32. #define GOPT_TRACE(...) \
  33. if (PHASE_TRACE(Js::GlobOptPhase, this->func) && !this->IsLoopPrePass()) \
  34. { \
  35. Output::Print(_u("TRACE: ")); \
  36. Output::Print(__VA_ARGS__); \
  37. Output::Flush(); \
  38. }
  39. #define GOPT_TRACE_INSTRTRACE(instr) \
  40. if (PHASE_TRACE(Js::GlobOptPhase, this->func) && !this->IsLoopPrePass()) \
  41. { \
  42. instr->Dump(); \
  43. Output::Flush(); \
  44. }
  45. #define GOPT_TRACE_INSTR(instr, ...) \
  46. if (PHASE_TRACE(Js::GlobOptPhase, this->func) && !this->IsLoopPrePass()) \
  47. { \
  48. Output::Print(_u("TRACE: ")); \
  49. Output::Print(__VA_ARGS__); \
  50. instr->Dump(); \
  51. Output::Flush(); \
  52. }
  53. #define GOPT_TRACE_BLOCK(block, before) \
  54. this->Trace(block, before); \
  55. Output::Flush();
  56. #define TRACE_PHASE_INSTR(phase, instr, ...) \
  57. if(PHASE_TRACE(phase, this->func)) \
  58. { \
  59. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE]; \
  60. Output::Print( \
  61. _u("Function %s (%s, line %u)"), \
  62. this->func->GetJnFunction()->GetDisplayName(), \
  63. this->func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer), \
  64. this->func->GetJnFunction()->GetLineNumber()); \
  65. if(this->func->IsLoopBody()) \
  66. { \
  67. Output::Print(_u(", loop %u"), static_cast<JsLoopBodyCodeGen *>(this->func->m_workItem)->GetLoopNumber()); \
  68. } \
  69. if(instr->m_func != this->func) \
  70. { \
  71. Output::Print( \
  72. _u(", Inlinee %s (%s, line %u)"), \
  73. instr->m_func->GetJnFunction()->GetDisplayName(), \
  74. instr->m_func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer), \
  75. instr->m_func->GetJnFunction()->GetLineNumber()); \
  76. } \
  77. Output::Print(_u(" - %s\n "), Js::PhaseNames[phase]); \
  78. instr->Dump(); \
  79. Output::Print(_u(" ")); \
  80. Output::Print(__VA_ARGS__); \
  81. Output::Flush(); \
  82. }
  83. #define TRACE_PHASE_INSTR_VERBOSE(phase, instr, ...) \
  84. if(CONFIG_FLAG(Verbose)) \
  85. { \
  86. TRACE_PHASE_INSTR(phase, instr, __VA_ARGS__); \
  87. }
  88. #define TRACE_TESTTRACE_PHASE_INSTR(phase, instr, ...) \
  89. TRACE_PHASE_INSTR(phase, instr, __VA_ARGS__); \
  90. TESTTRACE_PHASE_INSTR(phase, instr, __VA_ARGS__);
  91. #else // ENABLE_DEBUG_CONFIG_OPTIONS && DBG_DUMP
  92. #define GOPT_TRACE(...)
  93. #define GOPT_TRACE_OPND(opnd, ...)
  94. #define GOPT_TRACE_INSTRTRACE(instr)
  95. #define GOPT_TRACE_INSTR(instr, ...)
  96. #define GOPT_TRACE_BLOCK(block, before)
  97. #define TRACE_PHASE_INSTR(phase, instr, ...)
  98. #define TRACE_PHASE_INSTR_VERBOSE(phase, instr, ...)
  99. #define TRACE_TESTTRACE_PHASE_INSTR(phase, instr, ...) TESTTRACE_PHASE_INSTR(phase, instr, __VA_ARGS__);
  100. #endif // ENABLE_DEBUG_CONFIG_OPTIONS && DBG_DUMP
  101. #if DBG_DUMP
  102. #define DO_MEMOP_TRACE() (PHASE_TRACE(Js::MemOpPhase, this->func->GetJnFunction()) ||\
  103. PHASE_TRACE(Js::MemSetPhase, this->func->GetJnFunction()) ||\
  104. PHASE_TRACE(Js::MemCopyPhase, this->func->GetJnFunction()))
  105. #define DO_MEMOP_TRACE_PHASE(phase) (PHASE_TRACE(Js::MemOpPhase, this->func->GetJnFunction()) || PHASE_TRACE(Js::phase ## Phase, this->func->GetJnFunction()))
  106. #define OUTPUT_MEMOP_TRACE(loop, instr, ...) {\
  107. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];\
  108. Output::Print(15, _u("Function: %s%s, Loop: %u: "), this->func->GetJnFunction()->GetDisplayName(), this->func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer), loop->GetLoopNumber());\
  109. Output::Print(__VA_ARGS__);\
  110. IR::Instr* __instr__ = instr;\
  111. if(__instr__) __instr__->DumpByteCodeOffset();\
  112. Output::Print(_u("\n"));\
  113. Output::Flush(); \
  114. }
  115. #define TRACE_MEMOP(loop, instr, ...) \
  116. if (DO_MEMOP_TRACE()) {\
  117. Output::Print(_u("TRACE MemOp:"));\
  118. OUTPUT_MEMOP_TRACE(loop, instr, __VA_ARGS__)\
  119. }
  120. #define TRACE_MEMOP_VERBOSE(loop, instr, ...) if(CONFIG_FLAG(Verbose)) {TRACE_MEMOP(loop, instr, __VA_ARGS__)}
  121. #define TRACE_MEMOP_PHASE(phase, loop, instr, ...) \
  122. if (DO_MEMOP_TRACE_PHASE(phase))\
  123. {\
  124. Output::Print(_u("TRACE ") _u(#phase) _u(":"));\
  125. OUTPUT_MEMOP_TRACE(loop, instr, __VA_ARGS__)\
  126. }
  127. #define TRACE_MEMOP_PHASE_VERBOSE(phase, loop, instr, ...) if(CONFIG_FLAG(Verbose)) {TRACE_MEMOP_PHASE(phase, loop, instr, __VA_ARGS__)}
  128. #else
  129. #define DO_MEMOP_TRACE()
  130. #define DO_MEMOP_TRACE_PHASE(phase)
  131. #define OUTPUT_MEMOP_TRACE(loop, instr, ...)
  132. #define TRACE_MEMOP(loop, instr, ...)
  133. #define TRACE_MEMOP_VERBOSE(loop, instr, ...)
  134. #define TRACE_MEMOP_PHASE(phase, loop, instr, ...)
  135. #define TRACE_MEMOP_PHASE_VERBOSE(phase, loop, instr, ...)
  136. #endif
  137. class AutoRestoreVal
  138. {
  139. private:
  140. Value *const originalValue;
  141. Value *const tempValue;
  142. Value * *const valueRef;
  143. public:
  144. AutoRestoreVal(Value *const originalValue, Value * *const tempValueRef)
  145. : originalValue(originalValue), tempValue(*tempValueRef), valueRef(tempValueRef)
  146. {
  147. }
  148. ~AutoRestoreVal()
  149. {
  150. if(*valueRef == tempValue)
  151. {
  152. *valueRef = originalValue;
  153. }
  154. }
  155. PREVENT_COPY(AutoRestoreVal);
  156. };
  157. GlobOpt::GlobOpt(Func * func)
  158. : func(func),
  159. intConstantToStackSymMap(nullptr),
  160. intConstantToValueMap(nullptr),
  161. currentValue(FirstNewValueNumber),
  162. prePassLoop(nullptr),
  163. alloc(nullptr),
  164. isCallHelper(false),
  165. inInlinedBuiltIn(false),
  166. rootLoopPrePass(nullptr),
  167. noImplicitCallUsesToInsert(nullptr),
  168. valuesCreatedForClone(nullptr),
  169. valuesCreatedForMerge(nullptr),
  170. blockData(func),
  171. instrCountSinceLastCleanUp(0),
  172. isRecursiveCallOnLandingPad(false),
  173. updateInductionVariableValueNumber(false),
  174. isPerformingLoopBackEdgeCompensation(false),
  175. currentRegion(nullptr),
  176. doTypeSpec(
  177. !IsTypeSpecPhaseOff(func)),
  178. doAggressiveIntTypeSpec(
  179. doTypeSpec &&
  180. DoAggressiveIntTypeSpec(func)),
  181. doAggressiveMulIntTypeSpec(
  182. doTypeSpec &&
  183. !PHASE_OFF(Js::AggressiveMulIntTypeSpecPhase, func) &&
  184. !func->GetProfileInfo()->IsAggressiveMulIntTypeSpecDisabled(func->IsLoopBody())),
  185. doDivIntTypeSpec(
  186. doAggressiveIntTypeSpec &&
  187. !func->GetProfileInfo()->IsDivIntTypeSpecDisabled(func->IsLoopBody())),
  188. doLossyIntTypeSpec(
  189. doTypeSpec &&
  190. DoLossyIntTypeSpec(func)),
  191. doFloatTypeSpec(
  192. doTypeSpec &&
  193. DoFloatTypeSpec(func)),
  194. doArrayCheckHoist(
  195. DoArrayCheckHoist(func)),
  196. doArrayMissingValueCheckHoist(
  197. doArrayCheckHoist &&
  198. DoArrayMissingValueCheckHoist(func)),
  199. doArraySegmentHoist(
  200. doArrayCheckHoist &&
  201. DoArraySegmentHoist(ValueType::GetObject(ObjectType::Int32Array), func)),
  202. doJsArraySegmentHoist(
  203. doArraySegmentHoist &&
  204. DoArraySegmentHoist(ValueType::GetObject(ObjectType::Array), func)),
  205. doArrayLengthHoist(
  206. doArrayCheckHoist &&
  207. DoArrayLengthHoist(func)),
  208. doEliminateArrayAccessHelperCall(
  209. doArrayCheckHoist &&
  210. !PHASE_OFF(Js::EliminateArrayAccessHelperCallPhase, func)),
  211. doTrackRelativeIntBounds(
  212. doAggressiveIntTypeSpec &&
  213. DoPathDependentValues() &&
  214. !PHASE_OFF(Js::Phase::TrackRelativeIntBoundsPhase, func)),
  215. doBoundCheckElimination(
  216. doTrackRelativeIntBounds &&
  217. !PHASE_OFF(Js::Phase::BoundCheckEliminationPhase, func)),
  218. doBoundCheckHoist(
  219. doEliminateArrayAccessHelperCall &&
  220. doBoundCheckElimination &&
  221. DoConstFold() &&
  222. !PHASE_OFF(Js::Phase::BoundCheckHoistPhase, func) &&
  223. !func->GetProfileInfo()->IsBoundCheckHoistDisabled(func->IsLoopBody())),
  224. doLoopCountBasedBoundCheckHoist(
  225. doBoundCheckHoist &&
  226. !PHASE_OFF(Js::Phase::LoopCountBasedBoundCheckHoistPhase, func) &&
  227. !func->GetProfileInfo()->IsLoopCountBasedBoundCheckHoistDisabled(func->IsLoopBody())),
  228. isAsmJSFunc(func->m_workItem->GetFunctionBody()->GetIsAsmjsMode())
  229. {
  230. }
  231. void
  232. GlobOpt::BackwardPass(Js::Phase tag)
  233. {
  234. BEGIN_CODEGEN_PHASE(this->func, tag);
  235. ::BackwardPass backwardPass(this->func, this, tag);
  236. backwardPass.Optimize();
  237. END_CODEGEN_PHASE(this->func, tag);
  238. }
  239. void
  240. GlobOpt::Optimize()
  241. {
  242. this->objectTypeSyms = nullptr;
  243. if (!func->DoGlobOpt())
  244. {
  245. this->lengthEquivBv = nullptr;
  246. argumentsEquivBv = nullptr;
  247. // Still need to run the dead store phase to calculate the live reg on back edge
  248. this->BackwardPass(Js::DeadStorePhase);
  249. CannotAllocateArgumentsObjectOnStack();
  250. return;
  251. }
  252. {
  253. this->lengthEquivBv = this->func->m_symTable->m_propertyEquivBvMap->Lookup(Js::PropertyIds::length, nullptr); // Used to kill live "length" properties
  254. argumentsEquivBv = func->m_symTable->m_propertyEquivBvMap->Lookup(Js::PropertyIds::arguments, nullptr); // Used to kill live "arguments" properties
  255. // The backward phase needs the glob opt's allocator to allocate the propertyTypeValueMap
  256. // in GlobOpt::EnsurePropertyTypeValue and ranges of instructions where int overflow may be ignored.
  257. // (see BackwardPass::TrackIntUsage)
  258. PageAllocator * pageAllocator = this->func->m_alloc->GetPageAllocator();
  259. NoRecoverMemoryJitArenaAllocator localAlloc(_u("BE-GlobOpt"), pageAllocator, Js::Throw::OutOfMemory);
  260. this->alloc = &localAlloc;
  261. NoRecoverMemoryJitArenaAllocator localTempAlloc(_u("BE-GlobOpt temp"), pageAllocator, Js::Throw::OutOfMemory);
  262. this->tempAlloc = &localTempAlloc;
  263. // The forward passes use info (upwardExposedUses) from the backward pass. This info
  264. // isn't available for some of the symbols created during the backward pass, or the forward pass.
  265. // Keep track of the last symbol for which we're guaranteed to have data.
  266. this->maxInitialSymID = this->func->m_symTable->GetMaxSymID();
  267. this->BackwardPass(Js::BackwardPhase);
  268. this->ForwardPass();
  269. }
  270. this->BackwardPass(Js::DeadStorePhase);
  271. this->TailDupPass();
  272. }
  273. bool GlobOpt::ShouldExpectConventionalArrayIndexValue(IR::IndirOpnd *const indirOpnd)
  274. {
  275. Assert(indirOpnd);
  276. if(!indirOpnd->GetIndexOpnd())
  277. {
  278. return indirOpnd->GetOffset() >= 0;
  279. }
  280. IR::RegOpnd *const indexOpnd = indirOpnd->GetIndexOpnd();
  281. if(indexOpnd->m_sym->m_isNotInt)
  282. {
  283. // Typically, single-def or any sym-specific information for type-specialized syms should not be used because all of
  284. // their defs will not have been accounted for until after the forward pass. But m_isNotInt is only ever changed from
  285. // false to true, so it's okay in this case.
  286. return false;
  287. }
  288. StackSym *indexVarSym = indexOpnd->m_sym;
  289. if(indexVarSym->IsTypeSpec())
  290. {
  291. indexVarSym = indexVarSym->GetVarEquivSym(nullptr);
  292. Assert(indexVarSym);
  293. }
  294. else if(!IsLoopPrePass())
  295. {
  296. // Don't use single-def info or const flags for type-specialized syms, as all of their defs will not have been accounted
  297. // for until after the forward pass. Also, don't use the const flags in a loop prepass because the const flags may not
  298. // be up-to-date.
  299. StackSym *const indexSym = indexOpnd->m_sym;
  300. if(indexSym->IsIntConst())
  301. {
  302. return indexSym->GetIntConstValue() >= 0;
  303. }
  304. }
  305. Value *const indexValue = FindValue(indexVarSym);
  306. if(!indexValue)
  307. {
  308. // Treat it as Uninitialized, assume it's going to be valid
  309. return true;
  310. }
  311. ValueInfo *const indexValueInfo = indexValue->GetValueInfo();
  312. int32 indexConstantValue;
  313. if(indexValueInfo->TryGetIntConstantValue(&indexConstantValue))
  314. {
  315. return indexConstantValue >= 0;
  316. }
  317. if(indexValueInfo->IsUninitialized())
  318. {
  319. // Assume it's going to be valid
  320. return true;
  321. }
  322. return indexValueInfo->HasBeenNumber() && !indexValueInfo->HasBeenFloat();
  323. }
  324. //
  325. // Either result is float or 1/x or cst1/cst2 where cst1%cst2 != 0
  326. //
  327. ValueType GlobOpt::GetDivValueType(IR::Instr* instr, Value* src1Val, Value* src2Val, bool specialize)
  328. {
  329. ValueInfo *src1ValueInfo = (src1Val ? src1Val->GetValueInfo() : nullptr);
  330. ValueInfo *src2ValueInfo = (src2Val ? src2Val->GetValueInfo() : nullptr);
  331. if (instr->IsProfiledInstr() && instr->m_func->HasProfileInfo())
  332. {
  333. ValueType resultType = instr->m_func->GetProfileInfo()->GetDivProfileInfo(instr->m_func->GetJnFunction(),
  334. static_cast<Js::ProfileId>(instr->AsProfiledInstr()->u.profileId));
  335. if (resultType.IsLikelyInt())
  336. {
  337. if (specialize && src1ValueInfo && src2ValueInfo
  338. && ((src1ValueInfo->IsInt() && src2ValueInfo->IsInt()) ||
  339. (this->DoDivIntTypeSpec() && src1ValueInfo->IsLikelyInt() && src2ValueInfo->IsLikelyInt())))
  340. {
  341. return ValueType::GetInt(true);
  342. }
  343. return resultType;
  344. }
  345. // Consider: Checking that the sources are numbers.
  346. if (resultType.IsLikelyFloat())
  347. {
  348. return ValueType::Float;
  349. }
  350. return resultType;
  351. }
  352. int32 src1IntConstantValue;
  353. if(!src1ValueInfo || !src1ValueInfo->TryGetIntConstantValue(&src1IntConstantValue))
  354. {
  355. return ValueType::Number;
  356. }
  357. if (src1IntConstantValue == 1)
  358. {
  359. return ValueType::Float;
  360. }
  361. int32 src2IntConstantValue;
  362. if(!src2Val || !src2ValueInfo->TryGetIntConstantValue(&src2IntConstantValue))
  363. {
  364. return ValueType::Number;
  365. }
  366. if (src2IntConstantValue // Avoid divide by zero
  367. && !(src1IntConstantValue == 0x80000000 && src2IntConstantValue == -1) // Avoid integer overflow
  368. && (src1IntConstantValue % src2IntConstantValue) != 0)
  369. {
  370. return ValueType::Float;
  371. }
  372. return ValueType::Number;
  373. }
  374. void
  375. GlobOpt::ForwardPass()
  376. {
  377. BEGIN_CODEGEN_PHASE(this->func, Js::ForwardPhase);
  378. #if DBG_DUMP
  379. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::GlobOptPhase, this->func->GetSourceContextId(), this->func->GetLocalFunctionId()))
  380. {
  381. this->func->DumpHeader();
  382. }
  383. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::GlobOptPhase))
  384. {
  385. this->TraceSettings();
  386. }
  387. #endif
  388. // GetConstantCount() gives us the right size to pick for the SparseArray, but we may need more if we've inlined
  389. // functions with constants. There will be a gap in the symbol numbering between the main constants and
  390. // the inlined ones, so we'll most likely need a new array chunk. Make the min size of the array chunks be 64
  391. // in case we have a main function with very few constants and a bunch of constants from inlined functions.
  392. this->byteCodeConstantValueArray = SparseArray<Value>::New(this->alloc, max(this->func->GetJnFunction()->GetConstantCount(), 64U));
  393. this->byteCodeConstantValueNumbersBv = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
  394. this->tempBv = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
  395. this->prePassCopyPropSym = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
  396. this->byteCodeUses = nullptr;
  397. this->propertySymUse = nullptr;
  398. #if DBG
  399. this->byteCodeUsesBeforeOpt = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
  400. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::FieldCopyPropPhase) && this->DoFunctionFieldCopyProp())
  401. {
  402. Output::Print(_u("TRACE: CanDoFieldCopyProp Func: "));
  403. this->func->GetJnFunction()->DumpFullFunctionName();
  404. Output::Print(_u("\n"));
  405. }
  406. #endif
  407. OpndList localNoImplicitCallUsesToInsert(alloc);
  408. this->noImplicitCallUsesToInsert = &localNoImplicitCallUsesToInsert;
  409. IntConstantToStackSymMap localIntConstantToStackSymMap(alloc);
  410. this->intConstantToStackSymMap = &localIntConstantToStackSymMap;
  411. IntConstantToValueMap localIntConstantToValueMap(alloc);
  412. this->intConstantToValueMap = &localIntConstantToValueMap;
  413. AddrConstantToValueMap localAddrConstantToValueMap(alloc);
  414. this->addrConstantToValueMap = &localAddrConstantToValueMap;
  415. StringConstantToValueMap localStringConstantToValueMap(alloc);
  416. this->stringConstantToValueMap = &localStringConstantToValueMap;
  417. SymIdToInstrMap localPrePassInstrMap(alloc);
  418. this->prePassInstrMap = &localPrePassInstrMap;
  419. ValueSetByValueNumber localValuesCreatedForClone(alloc, 64);
  420. this->valuesCreatedForClone = &localValuesCreatedForClone;
  421. ValueNumberPairToValueMap localValuesCreatedForMerge(alloc, 64);
  422. this->valuesCreatedForMerge = &localValuesCreatedForMerge;
  423. #if DBG
  424. BVSparse<JitArenaAllocator> localFinishedStackLiteralInitFld(alloc);
  425. this->finishedStackLiteralInitFld = &localFinishedStackLiteralInitFld;
  426. #endif
  427. FOREACH_BLOCK_IN_FUNC_EDITING(block, this->func)
  428. {
  429. this->OptBlock(block);
  430. } NEXT_BLOCK_IN_FUNC_EDITING;
  431. if (!PHASE_OFF(Js::MemOpPhase, this->func))
  432. {
  433. ProcessMemOp();
  434. }
  435. this->noImplicitCallUsesToInsert = nullptr;
  436. this->intConstantToStackSymMap = nullptr;
  437. this->intConstantToValueMap = nullptr;
  438. this->addrConstantToValueMap = nullptr;
  439. this->stringConstantToValueMap = nullptr;
  440. #if DBG
  441. this->finishedStackLiteralInitFld = nullptr;
  442. uint freedCount = 0;
  443. uint spilledCount = 0;
  444. #endif
  445. FOREACH_BLOCK_IN_FUNC(block, this->func)
  446. {
  447. #if DBG
  448. if (block->GetDataUseCount() == 0)
  449. {
  450. freedCount++;
  451. }
  452. else
  453. {
  454. spilledCount++;
  455. }
  456. #endif
  457. block->SetDataUseCount(0);
  458. if (block->cloneStrCandidates)
  459. {
  460. JitAdelete(this->alloc, block->cloneStrCandidates);
  461. block->cloneStrCandidates = nullptr;
  462. }
  463. } NEXT_BLOCK_IN_FUNC;
  464. // Make sure we free most of them.
  465. Assert(freedCount >= spilledCount);
  466. END_CODEGEN_PHASE(this->func, Js::ForwardPhase);
  467. }
  468. void
  469. GlobOpt::OptBlock(BasicBlock *block)
  470. {
  471. this->func->ThrowIfScriptClosed();
  472. if (this->func->m_fg->RemoveUnreachableBlock(block, this))
  473. {
  474. GOPT_TRACE(_u("Removing unreachable block #%d\n"), block->GetBlockNum());
  475. return;
  476. }
  477. Loop * loop = block->loop;
  478. if (loop && block->isLoopHeader)
  479. {
  480. if (loop != this->prePassLoop)
  481. {
  482. OptLoops(loop);
  483. if (!this->IsLoopPrePass() && DoFieldPRE(loop))
  484. {
  485. // Note: !IsLoopPrePass means this was a root loop pre-pass. FieldPre() is called once per loop.
  486. this->FieldPRE(loop);
  487. // Re-optimize the landing pad
  488. BasicBlock *landingPad = loop->landingPad;
  489. this->isRecursiveCallOnLandingPad = true;
  490. this->OptBlock(landingPad);
  491. this->isRecursiveCallOnLandingPad = false;
  492. this->currentBlock = block;
  493. }
  494. }
  495. }
  496. this->currentBlock = block;
  497. PrepareLoopArrayCheckHoist();
  498. this->MergePredBlocksValueMaps(block);
  499. this->intOverflowCurrentlyMattersInRange = true;
  500. this->intOverflowDoesNotMatterRange = this->currentBlock->intOverflowDoesNotMatterRange;
  501. if (loop && DoFieldHoisting(loop))
  502. {
  503. if (block->isLoopHeader)
  504. {
  505. if (!this->IsLoopPrePass())
  506. {
  507. this->PrepareFieldHoisting(loop);
  508. }
  509. else if (loop == this->rootLoopPrePass)
  510. {
  511. this->PreparePrepassFieldHoisting(loop);
  512. }
  513. }
  514. }
  515. else
  516. {
  517. Assert(!TrackHoistableFields() || !HasHoistableFields(&this->blockData));
  518. if (!DoFieldCopyProp() && !DoFieldRefOpts())
  519. {
  520. this->blockData.liveFields->ClearAll();
  521. }
  522. }
  523. this->tempAlloc->Reset();
  524. if(loop && block->isLoopHeader)
  525. {
  526. loop->firstValueNumberInLoop = this->currentValue;
  527. }
  528. GOPT_TRACE_BLOCK(block, true);
  529. FOREACH_INSTR_IN_BLOCK_EDITING(instr, instrNext, block)
  530. {
  531. GOPT_TRACE_INSTRTRACE(instr);
  532. BailOutInfo* oldBailOutInfo = nullptr;
  533. bool isCheckAuxBailoutNeeded = this->func->IsJitInDebugMode() && !this->IsLoopPrePass();
  534. if (isCheckAuxBailoutNeeded && instr->HasAuxBailOut() && !instr->HasBailOutInfo())
  535. {
  536. oldBailOutInfo = instr->GetBailOutInfo();
  537. Assert(oldBailOutInfo);
  538. }
  539. bool isInstrRemoved = false;
  540. instrNext = this->OptInstr(instr, &isInstrRemoved);
  541. // If we still have instrs with only aux bail out, convert aux bail out back to regular bail out and fill it.
  542. // During OptInstr some instr can be moved out to a different block, in this case bailout info is going to be replaced
  543. // with e.g. loop bailout info which is filled as part of processing that block, thus we don't need to fill it here.
  544. if (isCheckAuxBailoutNeeded && !isInstrRemoved && instr->HasAuxBailOut() && !instr->HasBailOutInfo())
  545. {
  546. if (instr->GetBailOutInfo() == oldBailOutInfo)
  547. {
  548. instr->PromoteAuxBailOut();
  549. FillBailOutInfo(block, instr->GetBailOutInfo());
  550. }
  551. else
  552. {
  553. AssertMsg(instr->GetBailOutInfo(), "With aux bailout, the bailout info should not be removed by OptInstr.");
  554. }
  555. }
  556. } NEXT_INSTR_IN_BLOCK_EDITING;
  557. GOPT_TRACE_BLOCK(block, false);
  558. if (block->loop)
  559. {
  560. if (IsLoopPrePass())
  561. {
  562. if (DoBoundCheckHoist())
  563. {
  564. DetectUnknownChangesToInductionVariables(&block->globOptData);
  565. }
  566. }
  567. else
  568. {
  569. isPerformingLoopBackEdgeCompensation = true;
  570. Assert(this->tempBv->IsEmpty());
  571. BVSparse<JitArenaAllocator> tempBv2(this->tempAlloc);
  572. // On loop back-edges, we need to restore the state of the type specialized
  573. // symbols to that of the loop header.
  574. FOREACH_SUCCESSOR_BLOCK(succ, block)
  575. {
  576. if (succ->isLoopHeader && succ->loop->IsDescendentOrSelf(block->loop))
  577. {
  578. BVSparse<JitArenaAllocator> *liveOnBackEdge = block->loop->regAlloc.liveOnBackEdgeSyms;
  579. this->tempBv->Minus(block->loop->varSymsOnEntry, block->globOptData.liveVarSyms);
  580. this->tempBv->And(liveOnBackEdge);
  581. this->ToVar(this->tempBv, block);
  582. // Lossy int in the loop header, and no int on the back-edge - need a lossy conversion to int
  583. this->tempBv->Minus(block->loop->lossyInt32SymsOnEntry, block->globOptData.liveInt32Syms);
  584. this->tempBv->And(liveOnBackEdge);
  585. this->ToInt32(this->tempBv, block, true /* lossy */);
  586. // Lossless int in the loop header, and no lossless int on the back-edge - need a lossless conversion to int
  587. this->tempBv->Minus(block->loop->int32SymsOnEntry, block->loop->lossyInt32SymsOnEntry);
  588. tempBv2.Minus(block->globOptData.liveInt32Syms, block->globOptData.liveLossyInt32Syms);
  589. this->tempBv->Minus(&tempBv2);
  590. this->tempBv->And(liveOnBackEdge);
  591. this->ToInt32(this->tempBv, block, false /* lossy */);
  592. this->tempBv->Minus(block->loop->float64SymsOnEntry, block->globOptData.liveFloat64Syms);
  593. this->tempBv->And(liveOnBackEdge);
  594. this->ToFloat64(this->tempBv, block);
  595. // SIMD_JS
  596. // Compensate on backedge if sym is live on loop entry but not on backedge
  597. this->tempBv->Minus(block->loop->simd128F4SymsOnEntry, block->globOptData.liveSimd128F4Syms);
  598. this->tempBv->And(liveOnBackEdge);
  599. this->ToTypeSpec(this->tempBv, block, TySimd128F4, IR::BailOutSimd128F4Only);
  600. this->tempBv->Minus(block->loop->simd128I4SymsOnEntry, block->globOptData.liveSimd128I4Syms);
  601. this->tempBv->And(liveOnBackEdge);
  602. this->ToTypeSpec(this->tempBv, block, TySimd128I4, IR::BailOutSimd128I4Only);
  603. // For ints and floats, go aggressive and type specialize in the landing pad any symbol which was specialized on
  604. // entry to the loop body (in the loop header), and is still specialized on this tail, but wasn't specialized in
  605. // the landing pad.
  606. // Lossy int in the loop header and no int in the landing pad - need a lossy conversion to int
  607. // (entry.lossyInt32 - landingPad.int32)
  608. this->tempBv->Minus(block->loop->lossyInt32SymsOnEntry, block->loop->landingPad->globOptData.liveInt32Syms);
  609. this->tempBv->And(liveOnBackEdge);
  610. this->ToInt32(this->tempBv, block->loop->landingPad, true /* lossy */);
  611. // Lossless int in the loop header, and no lossless int in the landing pad - need a lossless conversion to int
  612. // ((entry.int32 - entry.lossyInt32) - (landingPad.int32 - landingPad.lossyInt32))
  613. this->tempBv->Minus(block->loop->int32SymsOnEntry, block->loop->lossyInt32SymsOnEntry);
  614. tempBv2.Minus(
  615. block->loop->landingPad->globOptData.liveInt32Syms,
  616. block->loop->landingPad->globOptData.liveLossyInt32Syms);
  617. this->tempBv->Minus(&tempBv2);
  618. this->tempBv->And(liveOnBackEdge);
  619. this->ToInt32(this->tempBv, block->loop->landingPad, false /* lossy */);
  620. // ((entry.float64 - landingPad.float64) & block.float64)
  621. this->tempBv->Minus(block->loop->float64SymsOnEntry, block->loop->landingPad->globOptData.liveFloat64Syms);
  622. this->tempBv->And(block->globOptData.liveFloat64Syms);
  623. this->tempBv->And(liveOnBackEdge);
  624. this->ToFloat64(this->tempBv, block->loop->landingPad);
  625. // SIMD_JS
  626. // compensate on landingpad if live on loopEntry and Backedge.
  627. this->tempBv->Minus(block->loop->simd128F4SymsOnEntry, block->loop->landingPad->globOptData.liveSimd128F4Syms);
  628. this->tempBv->And(block->globOptData.liveSimd128F4Syms);
  629. this->tempBv->And(liveOnBackEdge);
  630. this->ToTypeSpec(this->tempBv, block->loop->landingPad, TySimd128F4, IR::BailOutSimd128F4Only);
  631. this->tempBv->Minus(block->loop->simd128I4SymsOnEntry, block->loop->landingPad->globOptData.liveSimd128I4Syms);
  632. this->tempBv->And(block->globOptData.liveSimd128I4Syms);
  633. this->tempBv->And(liveOnBackEdge);
  634. this->ToTypeSpec(this->tempBv, block->loop->landingPad, TySimd128I4, IR::BailOutSimd128I4Only);
  635. // Now that we're done with the liveFields within this loop, trim the set to those syms
  636. // that the backward pass told us were live out of the loop.
  637. // This assumes we have no further need of the liveFields within the loop.
  638. if (block->loop->liveOutFields)
  639. {
  640. block->globOptData.liveFields->And(block->loop->liveOutFields);
  641. }
  642. }
  643. } NEXT_SUCCESSOR_BLOCK;
  644. this->tempBv->ClearAll();
  645. isPerformingLoopBackEdgeCompensation = false;
  646. }
  647. }
  648. block->globOptData.hasCSECandidates = this->blockData.hasCSECandidates;
  649. #if DBG
  650. // The set of live lossy int32 syms should be a subset of all live int32 syms
  651. this->tempBv->And(block->globOptData.liveInt32Syms, block->globOptData.liveLossyInt32Syms);
  652. Assert(this->tempBv->Count() == block->globOptData.liveLossyInt32Syms->Count());
  653. // The set of live lossy int32 syms should be a subset of live var or float syms (var or float sym containing the lossless
  654. // value of the sym should be live)
  655. this->tempBv->Or(block->globOptData.liveVarSyms, block->globOptData.liveFloat64Syms);
  656. this->tempBv->And(block->globOptData.liveLossyInt32Syms);
  657. Assert(this->tempBv->Count() == block->globOptData.liveLossyInt32Syms->Count());
  658. this->tempBv->ClearAll();
  659. #endif
  660. }
  661. void
  662. GlobOpt::OptLoops(Loop *loop)
  663. {
  664. Assert(loop != nullptr);
  665. #if DBG
  666. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::FieldCopyPropPhase) &&
  667. !DoFunctionFieldCopyProp() && DoFieldCopyProp(loop))
  668. {
  669. Output::Print(_u("TRACE: CanDoFieldCopyProp Loop: "));
  670. this->func->GetJnFunction()->DumpFullFunctionName();
  671. uint loopNumber = loop->GetLoopNumber();
  672. Assert(loopNumber != Js::LoopHeader::NoLoop);
  673. Output::Print(_u(" Loop: %d\n"), loopNumber);
  674. }
  675. #endif
  676. Loop *previousLoop = this->prePassLoop;
  677. this->prePassLoop = loop;
  678. if (previousLoop == nullptr)
  679. {
  680. Assert(this->rootLoopPrePass == nullptr);
  681. this->rootLoopPrePass = loop;
  682. this->prePassInstrMap->Clear();
  683. if (loop->parent == nullptr)
  684. {
  685. // Outer most loop...
  686. this->prePassCopyPropSym->ClearAll();
  687. }
  688. }
  689. if (loop->symsUsedBeforeDefined == nullptr)
  690. {
  691. loop->symsUsedBeforeDefined = JitAnew(alloc, BVSparse<JitArenaAllocator>, this->alloc);
  692. loop->likelyIntSymsUsedBeforeDefined = JitAnew(alloc, BVSparse<JitArenaAllocator>, this->alloc);
  693. loop->likelyNumberSymsUsedBeforeDefined = JitAnew(alloc, BVSparse<JitArenaAllocator>, this->alloc);
  694. loop->likelySimd128F4SymsUsedBeforeDefined = JitAnew(alloc, BVSparse<JitArenaAllocator>, this->alloc);
  695. loop->likelySimd128I4SymsUsedBeforeDefined = JitAnew(alloc, BVSparse<JitArenaAllocator>, this->alloc);
  696. loop->forceFloat64SymsOnEntry = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
  697. loop->forceSimd128F4SymsOnEntry = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
  698. loop->forceSimd128I4SymsOnEntry = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
  699. loop->symsDefInLoop = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
  700. loop->fieldKilled = JitAnew(alloc, BVSparse<JitArenaAllocator>, this->alloc);
  701. loop->fieldPRESymStore = JitAnew(alloc, BVSparse<JitArenaAllocator>, this->alloc);
  702. loop->allFieldsKilled = false;
  703. }
  704. else
  705. {
  706. loop->symsUsedBeforeDefined->ClearAll();
  707. loop->likelyIntSymsUsedBeforeDefined->ClearAll();
  708. loop->likelyNumberSymsUsedBeforeDefined->ClearAll();
  709. loop->likelySimd128F4SymsUsedBeforeDefined->ClearAll();
  710. loop->likelySimd128I4SymsUsedBeforeDefined->ClearAll();
  711. loop->forceFloat64SymsOnEntry->ClearAll();
  712. loop->forceSimd128F4SymsOnEntry->ClearAll();
  713. loop->forceSimd128I4SymsOnEntry->ClearAll();
  714. loop->symsDefInLoop->ClearAll();
  715. loop->fieldKilled->ClearAll();
  716. loop->allFieldsKilled = false;
  717. loop->initialValueFieldMap.Reset();
  718. }
  719. FOREACH_BLOCK_IN_LOOP(block, loop)
  720. {
  721. block->SetDataUseCount(block->GetSuccList()->Count());
  722. OptBlock(block);
  723. } NEXT_BLOCK_IN_LOOP;
  724. if (previousLoop == nullptr)
  725. {
  726. Assert(this->rootLoopPrePass == loop);
  727. this->rootLoopPrePass = nullptr;
  728. }
  729. this->prePassLoop = previousLoop;
  730. }
  731. void
  732. GlobOpt::TailDupPass()
  733. {
  734. FOREACH_LOOP_IN_FUNC_EDITING(loop, this->func)
  735. {
  736. BasicBlock* header = loop->GetHeadBlock();
  737. BasicBlock* loopTail = nullptr;
  738. FOREACH_PREDECESSOR_BLOCK(pred, header)
  739. {
  740. if (loop->IsDescendentOrSelf(pred->loop))
  741. {
  742. loopTail = pred;
  743. break;
  744. }
  745. } NEXT_PREDECESSOR_BLOCK;
  746. if (loopTail)
  747. {
  748. AssertMsg(loopTail->GetLastInstr()->IsBranchInstr(), "LastInstr of loop should always be a branch no?");
  749. if (!loopTail->GetPredList()->HasOne())
  750. {
  751. TryTailDup(loopTail->GetLastInstr()->AsBranchInstr());
  752. }
  753. }
  754. } NEXT_LOOP_IN_FUNC_EDITING;
  755. }
  756. bool
  757. GlobOpt::TryTailDup(IR::BranchInstr *tailBranch)
  758. {
  759. if (PHASE_OFF(Js::TailDupPhase, tailBranch->m_func->GetTopFunc()))
  760. {
  761. return false;
  762. }
  763. if (tailBranch->IsConditional())
  764. {
  765. return false;
  766. }
  767. IR::Instr *instr;
  768. uint instrCount = 0;
  769. for (instr = tailBranch->GetPrevRealInstrOrLabel(); !instr->IsLabelInstr(); instr = instr->GetPrevRealInstrOrLabel())
  770. {
  771. if (instr->HasBailOutInfo())
  772. {
  773. break;
  774. }
  775. if (!OpCodeAttr::CanCSE(instr->m_opcode))
  776. {
  777. // Consider: We could be more aggressive here
  778. break;
  779. }
  780. instrCount++;
  781. if (instrCount > 1)
  782. {
  783. // Consider: If copy handled single-def tmps renaming, we could do more instrs
  784. break;
  785. }
  786. }
  787. if (!instr->IsLabelInstr())
  788. {
  789. return false;
  790. }
  791. IR::LabelInstr *mergeLabel = instr->AsLabelInstr();
  792. IR::Instr *mergeLabelPrev = mergeLabel->m_prev;
  793. // Skip unreferenced labels
  794. while (mergeLabelPrev->IsLabelInstr() && mergeLabelPrev->AsLabelInstr()->labelRefs.Empty())
  795. {
  796. mergeLabelPrev = mergeLabelPrev->m_prev;
  797. }
  798. BasicBlock* labelBlock = mergeLabel->GetBasicBlock();
  799. uint origPredCount = labelBlock->GetPredList()->Count();
  800. uint dupCount = 0;
  801. // We are good to go. Let's do the tail duplication.
  802. FOREACH_SLISTCOUNTED_ENTRY_EDITING(IR::BranchInstr*, branchEntry, &mergeLabel->labelRefs, iter)
  803. {
  804. if (branchEntry->IsUnconditional() && !branchEntry->IsMultiBranch() && branchEntry != mergeLabelPrev && branchEntry != tailBranch)
  805. {
  806. for (instr = mergeLabel->m_next; instr != tailBranch; instr = instr->m_next)
  807. {
  808. branchEntry->InsertBefore(instr->Copy());
  809. }
  810. branchEntry->ReplaceTarget(mergeLabel, tailBranch->GetTarget());
  811. instr = branchEntry;
  812. while(!instr->IsLabelInstr())
  813. {
  814. instr = instr->m_prev;
  815. }
  816. BasicBlock* branchBlock = instr->AsLabelInstr()->GetBasicBlock();
  817. labelBlock->RemovePred(branchBlock, func->m_fg);
  818. func->m_fg->AddEdge(branchBlock, tailBranch->GetTarget()->GetBasicBlock());
  819. dupCount++;
  820. }
  821. } NEXT_SLISTCOUNTED_ENTRY_EDITING;
  822. // If we've duplicated everywhere, tail block is dead and should be removed.
  823. if (dupCount == origPredCount)
  824. {
  825. AssertMsg(mergeLabel->IsUnreferenced(), "Should not remove block with referenced label.");
  826. func->m_fg->RemoveBlock(labelBlock, nullptr, true);
  827. }
  828. return true;
  829. }
  830. void
  831. GlobOpt::MergePredBlocksValueMaps(BasicBlock *block)
  832. {
  833. Assert(!this->isCallHelper);
  834. if (!this->isRecursiveCallOnLandingPad)
  835. {
  836. this->NulloutBlockData(&this->blockData);
  837. }
  838. else
  839. {
  840. // If we are going over the landing pad again after field PRE, just start again
  841. // with the value table where we left off.
  842. this->CopyBlockData(&this->blockData, &block->globOptData);
  843. return;
  844. }
  845. BVSparse<JitArenaAllocator> symsRequiringCompensation(tempAlloc);
  846. {
  847. BVSparse<JitArenaAllocator> symsCreatedForMerge(tempAlloc);
  848. bool forceTypeSpecOnLoopHeader = true;
  849. FOREACH_PREDECESSOR_BLOCK(pred, block)
  850. {
  851. if (pred->globOptData.callSequence && pred->globOptData.callSequence->Empty())
  852. {
  853. JitAdelete(this->alloc, pred->globOptData.callSequence);
  854. pred->globOptData.callSequence = nullptr;
  855. }
  856. if (block->isLoopHeader && this->IsLoopPrePass() && this->prePassLoop == block->loop && block->loop->IsDescendentOrSelf(pred->loop))
  857. {
  858. // Loop back-edge.
  859. // First pass on loop runs optimistically, without doing transforms.
  860. // Skip this edge for now.
  861. continue;
  862. }
  863. PathDependentInfo *const pathDependentInfo = __edge->GetPathDependentInfo();
  864. PathDependentInfoToRestore pathDependentInfoToRestore;
  865. if (pathDependentInfo)
  866. {
  867. pathDependentInfoToRestore = UpdatePathDependentInfo(pathDependentInfo);
  868. }
  869. Assert(pred->GetDataUseCount());
  870. // First pred?
  871. if (this->blockData.symToValueMap == nullptr)
  872. {
  873. // Only one edge?
  874. if (pred->GetSuccList()->HasOne() && block->GetPredList()->HasOne() && block->loop == nullptr)
  875. {
  876. this->ReuseBlockData(&this->blockData, &pred->globOptData);
  877. // Don't need to restore the old value info
  878. pathDependentInfoToRestore.Clear();
  879. }
  880. else
  881. {
  882. this->CloneBlockData(currentBlock, &this->blockData, pred);
  883. }
  884. }
  885. else
  886. {
  887. const bool isLoopPrePass = IsLoopPrePass();
  888. this->MergeBlockData(
  889. &this->blockData,
  890. block,
  891. pred,
  892. isLoopPrePass ? nullptr : &symsRequiringCompensation,
  893. isLoopPrePass ? nullptr : &symsCreatedForMerge,
  894. forceTypeSpecOnLoopHeader);
  895. forceTypeSpecOnLoopHeader = false; // can force type-spec on the loop header only for the first back edge.
  896. }
  897. // Restore the value for the next edge
  898. if (pathDependentInfo)
  899. {
  900. RestorePathDependentInfo(pathDependentInfo, pathDependentInfoToRestore);
  901. __edge->ClearPathDependentInfo(this->alloc);
  902. }
  903. } NEXT_PREDECESSOR_BLOCK;
  904. }
  905. // Consider: We can recreate values for hoisted field so it can copy prop out of the loop
  906. if (this->blockData.symToValueMap == nullptr)
  907. {
  908. Assert(this->blockData.hoistableFields == nullptr);
  909. this->InitBlockData();
  910. }
  911. else if (this->blockData.hoistableFields)
  912. {
  913. Assert(TrackHoistableFields());
  914. this->blockData.hoistableFields->And(this->blockData.liveFields);
  915. }
  916. if (!this->DoObjTypeSpec())
  917. {
  918. // Object type specialization is off, but if copy prop is on (e.g., /force:fieldhoist) we're not clearing liveFields,
  919. // so we may be letting type syms slip through this block.
  920. this->KillAllObjectTypes();
  921. }
  922. this->CopyBlockData(&block->globOptData, &this->blockData);
  923. if (this->IsLoopPrePass())
  924. {
  925. Assert(block->loop);
  926. if(DoBoundCheckHoist())
  927. {
  928. SetInductionVariableValueNumbers(&blockData);
  929. }
  930. if (block->isLoopHeader && this->rootLoopPrePass == block->loop)
  931. {
  932. // Capture bail out info in case we have optimization that needs it
  933. Assert(block->loop->bailOutInfo == nullptr);
  934. IR::Instr * firstInstr = block->GetFirstInstr();
  935. block->loop->bailOutInfo = JitAnew(this->func->m_alloc, BailOutInfo,
  936. firstInstr->GetByteCodeOffset(), firstInstr->m_func);
  937. this->FillBailOutInfo(block, block->loop->bailOutInfo);
  938. #if ENABLE_DEBUG_CONFIG_OPTIONS
  939. block->loop->bailOutInfo->bailOutOpcode = Js::OpCode::LoopBodyStart;
  940. #endif
  941. }
  942. // If loop pre-pass, don't insert convert from type-spec to var
  943. return;
  944. }
  945. this->CleanUpValueMaps();
  946. Sym *symIV = nullptr;
  947. // Clean up the syms requiring compensation by checking the final value in the merged block to see if the sym still requires
  948. // compensation. All the while, create a mapping from sym to value info in the merged block. This dictionary helps avoid a
  949. // value lookup in the merged block per predecessor.
  950. SymToValueInfoMap symsRequiringCompensationToMergedValueInfoMap(tempAlloc);
  951. if(!symsRequiringCompensation.IsEmpty())
  952. {
  953. const SymTable *const symTable = func->m_symTable;
  954. GlobHashTable *const symToValueMap = blockData.symToValueMap;
  955. FOREACH_BITSET_IN_SPARSEBV(id, &symsRequiringCompensation)
  956. {
  957. Sym *const sym = symTable->Find(id);
  958. Assert(sym);
  959. Value *const value = FindValue(symToValueMap, sym);
  960. if(!value)
  961. {
  962. continue;
  963. }
  964. ValueInfo *const valueInfo = value->GetValueInfo();
  965. if(!valueInfo->IsArrayValueInfo())
  966. {
  967. continue;
  968. }
  969. // At least one new sym was created while merging and associated with the merged value info, so those syms will
  970. // require compensation in predecessors. For now, the dead store phase is relied upon to remove compensation that is
  971. // dead due to no further uses of the new sym.
  972. symsRequiringCompensationToMergedValueInfoMap.Add(sym, valueInfo);
  973. } NEXT_BITSET_IN_SPARSEBV;
  974. symsRequiringCompensation.ClearAll();
  975. }
  976. if (block->isLoopHeader)
  977. {
  978. // Values on the back-edge in the prepass may be conservative for syms defined in the loop, and type specialization in
  979. // the prepass is not reflective of the value, but rather, is used to determine whether the sym should be specialized
  980. // around the loop. Additionally, some syms that are used before defined in the loop may be specialized in the loop
  981. // header despite not being specialized in the landing pad. Now that the type specialization bit-vectors are merged,
  982. // specialize the corresponding value infos in the loop header too.
  983. Assert(tempBv->IsEmpty());
  984. Loop *const loop = block->loop;
  985. SymTable *const symTable = func->m_symTable;
  986. GlobHashTable *const symToValueMap = blockData.symToValueMap;
  987. JitArenaAllocator *const alloc = this->alloc;
  988. // Int-specialized syms
  989. tempBv->Or(loop->likelyIntSymsUsedBeforeDefined, loop->symsDefInLoop);
  990. tempBv->And(blockData.liveInt32Syms);
  991. tempBv->Minus(blockData.liveLossyInt32Syms);
  992. FOREACH_BITSET_IN_SPARSEBV(id, tempBv)
  993. {
  994. StackSym *const varSym = symTable->FindStackSym(id);
  995. Assert(varSym);
  996. Value *const value = FindValue(symToValueMap, varSym);
  997. Assert(value);
  998. ValueInfo *const valueInfo = value->GetValueInfo();
  999. if(!valueInfo->IsInt())
  1000. {
  1001. ChangeValueInfo(nullptr, value, valueInfo->SpecializeToInt32(alloc));
  1002. }
  1003. } NEXT_BITSET_IN_SPARSEBV;
  1004. // Float-specialized syms
  1005. tempBv->Or(loop->likelyNumberSymsUsedBeforeDefined, loop->symsDefInLoop);
  1006. tempBv->Or(loop->forceFloat64SymsOnEntry);
  1007. tempBv->And(blockData.liveFloat64Syms);
  1008. GlobOptBlockData &landingPadBlockData = loop->landingPad->globOptData;
  1009. FOREACH_BITSET_IN_SPARSEBV(id, tempBv)
  1010. {
  1011. StackSym *const varSym = symTable->FindStackSym(id);
  1012. Assert(varSym);
  1013. // If the type-spec sym is null or if the sym is not float-specialized in the loop landing pad, the sym may have
  1014. // been merged to float on a loop back-edge when it was live as float on the back-edge, and live as int in the loop
  1015. // header. In this case, compensation inserted in the loop landing pad will use BailOutNumberOnly, and so it is
  1016. // guaranteed that the value will be float. Otherwise, if the type-spec sym exists, its field can be checked to see
  1017. // if it's prevented from being anything but a number.
  1018. StackSym *const typeSpecSym = varSym->GetFloat64EquivSym(nullptr);
  1019. if(!typeSpecSym ||
  1020. typeSpecSym->m_requiresBailOnNotNumber ||
  1021. !IsFloat64TypeSpecialized(varSym, &landingPadBlockData))
  1022. {
  1023. Value *const value = FindValue(symToValueMap, varSym);
  1024. if(value)
  1025. {
  1026. ValueInfo *const valueInfo = value->GetValueInfo();
  1027. if(!valueInfo->IsNumber())
  1028. {
  1029. ChangeValueInfo(block, value, valueInfo->SpecializeToFloat64(alloc));
  1030. }
  1031. }
  1032. else
  1033. {
  1034. SetValue(&block->globOptData, NewGenericValue(ValueType::Float), varSym);
  1035. }
  1036. }
  1037. } NEXT_BITSET_IN_SPARSEBV;
  1038. // SIMD_JS
  1039. // Simd128 type-spec syms
  1040. BVSparse<JitArenaAllocator> tempBv2(this->tempAlloc);
  1041. // For syms we made alive in loop header because of hoisting, use-before-def, or def in Loop body, set their valueInfo to definite.
  1042. // Make live on header AND in one of forceSimd128* or likelySimd128* vectors.
  1043. tempBv->Or(loop->likelySimd128F4SymsUsedBeforeDefined, loop->symsDefInLoop);
  1044. tempBv->Or(loop->likelySimd128I4SymsUsedBeforeDefined);
  1045. tempBv->Or(loop->forceSimd128F4SymsOnEntry);
  1046. tempBv->Or(loop->forceSimd128I4SymsOnEntry);
  1047. tempBv2.Or(blockData.liveSimd128F4Syms, blockData.liveSimd128I4Syms);
  1048. tempBv->And(&tempBv2);
  1049. FOREACH_BITSET_IN_SPARSEBV(id, tempBv)
  1050. {
  1051. StackSym * typeSpecSym = nullptr;
  1052. StackSym *const varSym = symTable->FindStackSym(id);
  1053. Assert(varSym);
  1054. if (blockData.liveSimd128F4Syms->Test(id))
  1055. {
  1056. typeSpecSym = varSym->GetSimd128F4EquivSym(nullptr);
  1057. if (!typeSpecSym || !IsSimd128F4TypeSpecialized(varSym, &landingPadBlockData))
  1058. {
  1059. Value *const value = FindValue(symToValueMap, varSym);
  1060. if (value)
  1061. {
  1062. ValueInfo *const valueInfo = value->GetValueInfo();
  1063. if (!valueInfo->IsSimd128Float32x4())
  1064. {
  1065. ChangeValueInfo(block, value, valueInfo->SpecializeToSimd128F4(alloc));
  1066. }
  1067. }
  1068. else
  1069. {
  1070. SetValue(&block->globOptData, NewGenericValue(ValueType::GetSimd128(ObjectType::Simd128Float32x4), varSym), varSym);
  1071. }
  1072. }
  1073. }
  1074. else if (blockData.liveSimd128I4Syms->Test(id))
  1075. {
  1076. typeSpecSym = varSym->GetSimd128I4EquivSym(nullptr);
  1077. if (!typeSpecSym || !IsSimd128I4TypeSpecialized(varSym, &landingPadBlockData))
  1078. {
  1079. Value *const value = FindValue(symToValueMap, varSym);
  1080. if (value)
  1081. {
  1082. ValueInfo *const valueInfo = value->GetValueInfo();
  1083. if (!valueInfo->IsSimd128Int32x4())
  1084. {
  1085. ChangeValueInfo(block, value, valueInfo->SpecializeToSimd128I4(alloc));
  1086. }
  1087. }
  1088. else
  1089. {
  1090. SetValue(&block->globOptData, NewGenericValue(ValueType::GetSimd128(ObjectType::Simd128Int32x4), varSym), varSym);
  1091. }
  1092. }
  1093. }
  1094. else
  1095. {
  1096. Assert(UNREACHED);
  1097. }
  1098. } NEXT_BITSET_IN_SPARSEBV;
  1099. tempBv->ClearAll();
  1100. }
  1101. // We need to handle the case where a symbol is type-spec'd coming from some predecessors,
  1102. // but not from others.
  1103. //
  1104. // We can do this by inserting the right conversion in the predecessor block, but we
  1105. // can only do this if we are the first successor of that block, since the previous successors
  1106. // would have already been processed. Instead, we'll need to break the edge and insert a block
  1107. // (airlock block) to put in the conversion code.
  1108. Assert(this->tempBv->IsEmpty());
  1109. BVSparse<JitArenaAllocator> tempBv2(this->tempAlloc);
  1110. BVSparse<JitArenaAllocator> tempBv3(this->tempAlloc);
  1111. BVSparse<JitArenaAllocator> tempBv4(this->tempAlloc);
  1112. // SIMD_JS
  1113. BVSparse<JitArenaAllocator> simd128F4SymsToUnbox(this->tempAlloc);
  1114. BVSparse<JitArenaAllocator> simd128I4SymsToUnbox(this->tempAlloc);
  1115. FOREACH_PREDECESSOR_EDGE_EDITING(edge, block, iter)
  1116. {
  1117. BasicBlock *pred = edge->GetPred();
  1118. if (pred->loop && pred->loop->GetHeadBlock() == block)
  1119. {
  1120. pred->DecrementDataUseCount();
  1121. // Skip loop back-edges. We will handle these when we get to the exit blocks.
  1122. continue;
  1123. }
  1124. BasicBlock *orgPred = nullptr;
  1125. if (pred->isAirLockCompensationBlock)
  1126. {
  1127. Assert(pred->GetPredList()->HasOne());
  1128. orgPred = pred;
  1129. pred = (pred->GetPredList()->Head())->GetPred();
  1130. }
  1131. // Lossy int in the merged block, and no int in the predecessor - need a lossy conversion to int
  1132. tempBv2.Minus(this->blockData.liveLossyInt32Syms, pred->globOptData.liveInt32Syms);
  1133. // Lossless int in the merged block, and no lossless int in the predecessor - need a lossless conversion to int
  1134. tempBv3.Minus(this->blockData.liveInt32Syms, this->blockData.liveLossyInt32Syms);
  1135. this->tempBv->Minus(pred->globOptData.liveInt32Syms, pred->globOptData.liveLossyInt32Syms);
  1136. tempBv3.Minus(this->tempBv);
  1137. this->tempBv->Minus(this->blockData.liveVarSyms, pred->globOptData.liveVarSyms);
  1138. tempBv4.Minus(this->blockData.liveFloat64Syms, pred->globOptData.liveFloat64Syms);
  1139. bool symIVNeedsSpecializing = (symIV && !pred->globOptData.liveInt32Syms->Test(symIV->m_id) && !tempBv3.Test(symIV->m_id));
  1140. // SIMD_JS
  1141. simd128F4SymsToUnbox.Minus(this->blockData.liveSimd128F4Syms, pred->globOptData.liveSimd128F4Syms);
  1142. simd128I4SymsToUnbox.Minus(this->blockData.liveSimd128I4Syms, pred->globOptData.liveSimd128I4Syms);
  1143. if (!this->tempBv->IsEmpty() ||
  1144. !tempBv2.IsEmpty() ||
  1145. !tempBv3.IsEmpty() ||
  1146. !tempBv4.IsEmpty() ||
  1147. !simd128F4SymsToUnbox.IsEmpty() ||
  1148. !simd128I4SymsToUnbox.IsEmpty() ||
  1149. symIVNeedsSpecializing ||
  1150. symsRequiringCompensationToMergedValueInfoMap.Count() != 0)
  1151. {
  1152. // We can't un-specialize a symbol in a predecessor if we've already processed
  1153. // a successor of that block. Instead, insert a new block on the flow edge
  1154. // (an airlock block) and do the un-specialization there.
  1155. //
  1156. // Alternatively, the current block could be an exit block out of this loop, and so the predecessor may exit the
  1157. // loop. In that case, if the predecessor may continue into the loop without exiting, then we need an airlock block
  1158. // to do the appropriate conversions only on the exit path (preferring not to do the conversions inside the loop).
  1159. // If, on the other hand, the predecessor always flows into the current block, then it always exits, so we don't need
  1160. // an airlock block and can just do the conversions in the predecessor.
  1161. if (pred->GetSuccList()->Head()->GetSucc() != block ||
  1162. (pred->loop && pred->loop->parent == block->loop && pred->GetSuccList()->Count() > 1))
  1163. {
  1164. BasicBlock *airlockBlock = nullptr;
  1165. if (!orgPred)
  1166. {
  1167. GOPT_TRACE(_u("Inserting airlock block to convert syms to var between block %d and %d\n"),
  1168. pred->GetBlockNum(), block->GetBlockNum());
  1169. airlockBlock = this->func->m_fg->InsertAirlockBlock(edge);
  1170. }
  1171. else
  1172. {
  1173. Assert(orgPred->isAirLockCompensationBlock);
  1174. airlockBlock = orgPred;
  1175. pred->DecrementDataUseCount();
  1176. airlockBlock->isAirLockCompensationBlock = false; // This is airlock block now. So remove the attribute.
  1177. }
  1178. this->CloneBlockData(airlockBlock, pred);
  1179. pred = airlockBlock;
  1180. }
  1181. if (!this->tempBv->IsEmpty())
  1182. {
  1183. this->ToVar(this->tempBv, pred);
  1184. }
  1185. if (!tempBv2.IsEmpty())
  1186. {
  1187. this->ToInt32(&tempBv2, pred, true /* lossy */);
  1188. }
  1189. if (!tempBv3.IsEmpty())
  1190. {
  1191. this->ToInt32(&tempBv3, pred, false /* lossy */);
  1192. }
  1193. if (!tempBv4.IsEmpty())
  1194. {
  1195. this->ToFloat64(&tempBv4, pred);
  1196. }
  1197. if (symIVNeedsSpecializing)
  1198. {
  1199. this->tempBv->ClearAll();
  1200. this->tempBv->Set(symIV->m_id);
  1201. this->ToInt32(this->tempBv, pred, false /* lossy */);
  1202. }
  1203. if(symsRequiringCompensationToMergedValueInfoMap.Count() != 0)
  1204. {
  1205. InsertValueCompensation(pred, symsRequiringCompensationToMergedValueInfoMap);
  1206. }
  1207. // SIMD_JS
  1208. if (!simd128F4SymsToUnbox.IsEmpty())
  1209. {
  1210. this->ToTypeSpec(&simd128F4SymsToUnbox, pred, TySimd128F4, IR::BailOutSimd128F4Only);
  1211. }
  1212. if (!simd128I4SymsToUnbox.IsEmpty())
  1213. {
  1214. this->ToTypeSpec(&simd128I4SymsToUnbox, pred, TySimd128I4, IR::BailOutSimd128I4Only);
  1215. }
  1216. }
  1217. } NEXT_PREDECESSOR_EDGE_EDITING;
  1218. FOREACH_PREDECESSOR_EDGE(edge, block)
  1219. {
  1220. // Peak Memory optimization:
  1221. // These are in an arena, but putting them on the free list greatly reduces
  1222. // the peak memory used by the global optimizer for complex flow graphs.
  1223. BasicBlock *pred = edge->GetPred();
  1224. if (!block->isLoopHeader || block->loop != pred->loop)
  1225. {
  1226. // Skip airlock compensation block as we are not going to walk this block.
  1227. if (pred->isAirLockCompensationBlock)
  1228. {
  1229. pred->DecrementDataUseCount();
  1230. Assert(pred->GetPredList()->HasOne());
  1231. pred = (pred->GetPredList()->Head())->GetPred();
  1232. }
  1233. if (pred->DecrementDataUseCount() == 0 && (!block->loop || block->loop->landingPad != pred))
  1234. {
  1235. if (!(pred->GetSuccList()->HasOne() && block->GetPredList()->HasOne() && block->loop == nullptr))
  1236. {
  1237. this->DeleteBlockData(&pred->globOptData);
  1238. }
  1239. else
  1240. {
  1241. this->NulloutBlockData(&pred->globOptData);
  1242. }
  1243. }
  1244. }
  1245. } NEXT_PREDECESSOR_EDGE;
  1246. this->tempBv->ClearAll();
  1247. Assert(!this->IsLoopPrePass()); // We already early return if we are in prepass
  1248. if (block->isLoopHeader)
  1249. {
  1250. Loop *const loop = block->loop;
  1251. // Save values live on loop entry, such that we can adjust the state of the
  1252. // values on the back-edge to match.
  1253. loop->varSymsOnEntry = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
  1254. loop->varSymsOnEntry->Copy(block->globOptData.liveVarSyms);
  1255. loop->int32SymsOnEntry = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
  1256. loop->int32SymsOnEntry->Copy(block->globOptData.liveInt32Syms);
  1257. loop->lossyInt32SymsOnEntry = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
  1258. loop->lossyInt32SymsOnEntry->Copy(block->globOptData.liveLossyInt32Syms);
  1259. loop->float64SymsOnEntry = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
  1260. loop->float64SymsOnEntry->Copy(block->globOptData.liveFloat64Syms);
  1261. // SIMD_JS
  1262. loop->simd128F4SymsOnEntry = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
  1263. loop->simd128F4SymsOnEntry->Copy(block->globOptData.liveSimd128F4Syms);
  1264. loop->simd128I4SymsOnEntry = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
  1265. loop->simd128I4SymsOnEntry->Copy(block->globOptData.liveSimd128I4Syms);
  1266. loop->liveFieldsOnEntry = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
  1267. loop->liveFieldsOnEntry->Copy(block->globOptData.liveFields);
  1268. if(DoBoundCheckHoist() && loop->inductionVariables)
  1269. {
  1270. FinalizeInductionVariables(loop, &blockData);
  1271. if(DoLoopCountBasedBoundCheckHoist())
  1272. {
  1273. DetermineDominatingLoopCountableBlock(loop, block);
  1274. }
  1275. }
  1276. }
  1277. else if (!block->loop)
  1278. {
  1279. block->SetDataUseCount(block->GetSuccList()->Count());
  1280. }
  1281. else if(block == block->loop->dominatingLoopCountableBlock)
  1282. {
  1283. DetermineLoopCount(block->loop);
  1284. }
  1285. }
  1286. void
  1287. GlobOpt::NulloutBlockData(GlobOptBlockData *data)
  1288. {
  1289. data->symToValueMap = nullptr;
  1290. data->exprToValueMap = nullptr;
  1291. data->liveFields = nullptr;
  1292. data->maybeWrittenTypeSyms = nullptr;
  1293. data->isTempSrc = nullptr;
  1294. data->liveVarSyms = nullptr;
  1295. data->liveInt32Syms = nullptr;
  1296. data->liveLossyInt32Syms = nullptr;
  1297. data->liveFloat64Syms = nullptr;
  1298. // SIMD_JS
  1299. data->liveSimd128F4Syms = nullptr;
  1300. data->liveSimd128I4Syms = nullptr;
  1301. data->hoistableFields = nullptr;
  1302. data->argObjSyms = nullptr;
  1303. data->maybeTempObjectSyms = nullptr;
  1304. data->canStoreTempObjectSyms = nullptr;
  1305. data->valuesToKillOnCalls = nullptr;
  1306. data->inductionVariables = nullptr;
  1307. data->availableIntBoundChecks = nullptr;
  1308. data->callSequence = nullptr;
  1309. data->startCallCount = 0;
  1310. data->argOutCount = 0;
  1311. data->totalOutParamCount = 0;
  1312. data->inlinedArgOutCount = 0;
  1313. data->hasCSECandidates = false;
  1314. data->curFunc = this->func;
  1315. data->stackLiteralInitFldDataMap = nullptr;
  1316. data->OnDataUnreferenced();
  1317. }
  1318. void
  1319. GlobOpt::InitBlockData()
  1320. {
  1321. GlobOptBlockData *const data = &this->blockData;
  1322. JitArenaAllocator *const alloc = this->alloc;
  1323. data->symToValueMap = GlobHashTable::New(alloc, 64);
  1324. data->exprToValueMap = ExprHashTable::New(alloc, 64);
  1325. data->liveFields = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1326. data->liveArrayValues = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1327. data->isTempSrc = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1328. data->liveVarSyms = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1329. data->liveInt32Syms = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1330. data->liveLossyInt32Syms = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1331. data->liveFloat64Syms = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1332. // SIMD_JS
  1333. data->liveSimd128F4Syms = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1334. data->liveSimd128I4Syms = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1335. data->hoistableFields = nullptr;
  1336. data->argObjSyms = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1337. data->maybeTempObjectSyms = nullptr;
  1338. data->canStoreTempObjectSyms = nullptr;
  1339. data->valuesToKillOnCalls = JitAnew(alloc, ValueSet, alloc);
  1340. if(DoBoundCheckHoist())
  1341. {
  1342. data->inductionVariables = IsLoopPrePass() ? JitAnew(alloc, InductionVariableSet, alloc) : nullptr;
  1343. data->availableIntBoundChecks = JitAnew(alloc, IntBoundCheckSet, alloc);
  1344. }
  1345. data->maybeWrittenTypeSyms = nullptr;
  1346. data->callSequence = nullptr;
  1347. data->startCallCount = 0;
  1348. data->argOutCount = 0;
  1349. data->totalOutParamCount = 0;
  1350. data->inlinedArgOutCount = 0;
  1351. data->hasCSECandidates = false;
  1352. data->curFunc = this->func;
  1353. data->stackLiteralInitFldDataMap = nullptr;
  1354. data->OnDataInitialized(alloc);
  1355. }
  1356. void
  1357. GlobOpt::ReuseBlockData(GlobOptBlockData *toData, GlobOptBlockData *fromData)
  1358. {
  1359. // Reuse dead map
  1360. toData->symToValueMap = fromData->symToValueMap;
  1361. toData->exprToValueMap = fromData->exprToValueMap;
  1362. toData->liveFields = fromData->liveFields;
  1363. toData->liveArrayValues = fromData->liveArrayValues;
  1364. toData->maybeWrittenTypeSyms = fromData->maybeWrittenTypeSyms;
  1365. toData->isTempSrc = fromData->isTempSrc;
  1366. toData->liveVarSyms = fromData->liveVarSyms;
  1367. toData->liveInt32Syms = fromData->liveInt32Syms;
  1368. toData->liveLossyInt32Syms = fromData->liveLossyInt32Syms;
  1369. toData->liveFloat64Syms = fromData->liveFloat64Syms;
  1370. // SIMD_JS
  1371. toData->liveSimd128F4Syms = fromData->liveSimd128F4Syms;
  1372. toData->liveSimd128I4Syms = fromData->liveSimd128I4Syms;
  1373. if (TrackHoistableFields())
  1374. {
  1375. toData->hoistableFields = fromData->hoistableFields;
  1376. }
  1377. if (TrackArgumentsObject())
  1378. {
  1379. toData->argObjSyms = fromData->argObjSyms;
  1380. }
  1381. toData->maybeTempObjectSyms = fromData->maybeTempObjectSyms;
  1382. toData->canStoreTempObjectSyms = fromData->canStoreTempObjectSyms;
  1383. toData->curFunc = fromData->curFunc;
  1384. toData->valuesToKillOnCalls = fromData->valuesToKillOnCalls;
  1385. toData->inductionVariables = fromData->inductionVariables;
  1386. toData->availableIntBoundChecks = fromData->availableIntBoundChecks;
  1387. toData->callSequence = fromData->callSequence;
  1388. toData->startCallCount = fromData->startCallCount;
  1389. toData->argOutCount = fromData->argOutCount;
  1390. toData->totalOutParamCount = fromData->totalOutParamCount;
  1391. toData->inlinedArgOutCount = fromData->inlinedArgOutCount;
  1392. toData->hasCSECandidates = fromData->hasCSECandidates;
  1393. toData->stackLiteralInitFldDataMap = fromData->stackLiteralInitFldDataMap;
  1394. toData->OnDataReused(fromData);
  1395. }
  1396. void
  1397. GlobOpt::CopyBlockData(GlobOptBlockData *toData, GlobOptBlockData *fromData)
  1398. {
  1399. toData->symToValueMap = fromData->symToValueMap;
  1400. toData->exprToValueMap = fromData->exprToValueMap;
  1401. toData->liveFields = fromData->liveFields;
  1402. toData->liveArrayValues = fromData->liveArrayValues;
  1403. toData->maybeWrittenTypeSyms = fromData->maybeWrittenTypeSyms;
  1404. toData->isTempSrc = fromData->isTempSrc;
  1405. toData->liveVarSyms = fromData->liveVarSyms;
  1406. toData->liveInt32Syms = fromData->liveInt32Syms;
  1407. toData->liveLossyInt32Syms = fromData->liveLossyInt32Syms;
  1408. toData->liveFloat64Syms = fromData->liveFloat64Syms;
  1409. // SIMD_JS
  1410. toData->liveSimd128F4Syms = fromData->liveSimd128F4Syms;
  1411. toData->liveSimd128I4Syms = fromData->liveSimd128I4Syms;
  1412. toData->hoistableFields = fromData->hoistableFields;
  1413. toData->argObjSyms = fromData->argObjSyms;
  1414. toData->maybeTempObjectSyms = fromData->maybeTempObjectSyms;
  1415. toData->canStoreTempObjectSyms = fromData->canStoreTempObjectSyms;
  1416. toData->curFunc = fromData->curFunc;
  1417. toData->valuesToKillOnCalls = fromData->valuesToKillOnCalls;
  1418. toData->inductionVariables = fromData->inductionVariables;
  1419. toData->availableIntBoundChecks = fromData->availableIntBoundChecks;
  1420. toData->callSequence = fromData->callSequence;
  1421. toData->startCallCount = fromData->startCallCount;
  1422. toData->argOutCount = fromData->argOutCount;
  1423. toData->totalOutParamCount = fromData->totalOutParamCount;
  1424. toData->inlinedArgOutCount = fromData->inlinedArgOutCount;
  1425. toData->hasCSECandidates = fromData->hasCSECandidates;
  1426. toData->stackLiteralInitFldDataMap = fromData->stackLiteralInitFldDataMap;
  1427. toData->OnDataReused(fromData);
  1428. }
  1429. void GlobOpt::CloneBlockData(BasicBlock *const toBlock, BasicBlock *const fromBlock)
  1430. {
  1431. CloneBlockData(toBlock, &toBlock->globOptData, fromBlock);
  1432. }
  1433. void GlobOpt::CloneBlockData(BasicBlock *const toBlock, GlobOptBlockData *const toData, BasicBlock *const fromBlock)
  1434. {
  1435. GlobOptBlockData *const fromData = &fromBlock->globOptData;
  1436. JitArenaAllocator *const alloc = this->alloc;
  1437. toData->symToValueMap = fromData->symToValueMap->Copy();
  1438. toData->exprToValueMap = fromData->exprToValueMap->Copy();
  1439. // Clone the values as well to allow for flow-sensitive ValueInfo
  1440. this->CloneValues(toBlock, toData, fromData);
  1441. if(DoBoundCheckHoist())
  1442. {
  1443. CloneBoundCheckHoistBlockData(toBlock, toData, fromBlock, fromData);
  1444. }
  1445. toData->liveFields = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1446. toData->liveFields->Copy(fromData->liveFields);
  1447. toData->liveArrayValues = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1448. toData->liveArrayValues->Copy(fromData->liveArrayValues);
  1449. if (fromData->maybeWrittenTypeSyms)
  1450. {
  1451. toData->maybeWrittenTypeSyms = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1452. toData->maybeWrittenTypeSyms->Copy(fromData->maybeWrittenTypeSyms);
  1453. }
  1454. toData->isTempSrc = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1455. toData->isTempSrc->Copy(fromData->isTempSrc);
  1456. toData->liveVarSyms = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1457. toData->liveVarSyms->Copy(fromData->liveVarSyms);
  1458. toData->liveInt32Syms = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1459. toData->liveInt32Syms->Copy(fromData->liveInt32Syms);
  1460. toData->liveLossyInt32Syms = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1461. toData->liveLossyInt32Syms->Copy(fromData->liveLossyInt32Syms);
  1462. toData->liveFloat64Syms = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1463. toData->liveFloat64Syms->Copy(fromData->liveFloat64Syms);
  1464. // SIMD_JS
  1465. toData->liveSimd128F4Syms = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1466. toData->liveSimd128F4Syms->Copy(fromData->liveSimd128F4Syms);
  1467. toData->liveSimd128I4Syms = JitAnew(alloc, BVSparse<JitArenaAllocator>, alloc);
  1468. toData->liveSimd128I4Syms->Copy(fromData->liveSimd128I4Syms);
  1469. if (TrackHoistableFields())
  1470. {
  1471. if (fromData->hoistableFields)
  1472. {
  1473. toData->hoistableFields = fromData->hoistableFields->CopyNew(alloc);
  1474. }
  1475. }
  1476. if (TrackArgumentsObject() && fromData->argObjSyms)
  1477. {
  1478. toData->argObjSyms = fromData->argObjSyms->CopyNew(alloc);
  1479. }
  1480. if (fromData->maybeTempObjectSyms && !fromData->maybeTempObjectSyms->IsEmpty())
  1481. {
  1482. toData->maybeTempObjectSyms = fromData->maybeTempObjectSyms->CopyNew(alloc);
  1483. if (fromData->canStoreTempObjectSyms && !fromData->canStoreTempObjectSyms->IsEmpty())
  1484. {
  1485. toData->canStoreTempObjectSyms = fromData->canStoreTempObjectSyms->CopyNew(alloc);
  1486. }
  1487. }
  1488. else
  1489. {
  1490. Assert(fromData->canStoreTempObjectSyms == nullptr || fromData->canStoreTempObjectSyms->IsEmpty());
  1491. }
  1492. toData->curFunc = fromData->curFunc;
  1493. if (fromData->callSequence != nullptr)
  1494. {
  1495. toData->callSequence = JitAnew(alloc, SListBase<IR::Opnd *>);
  1496. fromData->callSequence->CopyTo(alloc, *(toData->callSequence));
  1497. }
  1498. else
  1499. {
  1500. toData->callSequence = nullptr;
  1501. }
  1502. toData->startCallCount = fromData->startCallCount;
  1503. toData->argOutCount = fromData->argOutCount;
  1504. toData->totalOutParamCount = fromData->totalOutParamCount;
  1505. toData->inlinedArgOutCount = fromData->inlinedArgOutCount;
  1506. toData->hasCSECandidates = fromData->hasCSECandidates;
  1507. // Although we don't need the data on loop pre pass, we need to do it for the loop header
  1508. // because we capture the loop header bailout on loop prepass
  1509. if (fromData->stackLiteralInitFldDataMap != nullptr &&
  1510. (!this->IsLoopPrePass() || (toBlock->isLoopHeader && toBlock->loop == this->rootLoopPrePass)))
  1511. {
  1512. toData->stackLiteralInitFldDataMap = fromData->stackLiteralInitFldDataMap->Clone();
  1513. }
  1514. else
  1515. {
  1516. toData->stackLiteralInitFldDataMap = nullptr;
  1517. }
  1518. Assert(fromData->HasData());
  1519. toData->OnDataInitialized(alloc);
  1520. }
  1521. void
  1522. GlobOpt::CloneValues(BasicBlock *const toBlock, GlobOptBlockData *toData, GlobOptBlockData *fromData)
  1523. {
  1524. ValueSet *const valuesToKillOnCalls = JitAnew(this->alloc, ValueSet, this->alloc);
  1525. toData->valuesToKillOnCalls = valuesToKillOnCalls;
  1526. // Values are shared between symbols with the same ValueNumber.
  1527. // Use a dictionary to share the clone values.
  1528. ValueSetByValueNumber *const valuesCreatedForClone = this->valuesCreatedForClone;
  1529. Assert(valuesCreatedForClone);
  1530. Assert(valuesCreatedForClone->Count() == 0);
  1531. DebugOnly(ValueSetByValueNumber originalValues(tempAlloc, 64));
  1532. const uint tableSize = toData->symToValueMap->tableSize;
  1533. SListBase<GlobHashBucket> *const table = toData->symToValueMap->table;
  1534. for (uint i = 0; i < tableSize; i++)
  1535. {
  1536. FOREACH_SLISTBASE_ENTRY(GlobHashBucket, bucket, &table[i])
  1537. {
  1538. Value *value = bucket.element;
  1539. ValueNumber valueNum = value->GetValueNumber();
  1540. #if DBG
  1541. // Ensure that the set of values in fromData contains only one value per value number. Byte-code constant values
  1542. // are reused in multiple blocks without cloning, so exclude those value numbers.
  1543. {
  1544. Value *const previouslyClonedOriginalValue = originalValues.Lookup(valueNum);
  1545. if (previouslyClonedOriginalValue)
  1546. {
  1547. if (!byteCodeConstantValueNumbersBv->Test(valueNum))
  1548. {
  1549. Assert(value == previouslyClonedOriginalValue);
  1550. }
  1551. }
  1552. else
  1553. {
  1554. originalValues.Add(value);
  1555. }
  1556. }
  1557. #endif
  1558. Value *newValue = valuesCreatedForClone->Lookup(valueNum);
  1559. if (!newValue)
  1560. {
  1561. newValue = CopyValue(value, valueNum);
  1562. TrackMergedValueForKills(newValue, toData, nullptr);
  1563. valuesCreatedForClone->Add(newValue);
  1564. }
  1565. bucket.element = newValue;
  1566. } NEXT_SLISTBASE_ENTRY;
  1567. }
  1568. valuesCreatedForClone->Clear();
  1569. ProcessValueKills(toBlock, toData);
  1570. }
  1571. void
  1572. GlobOpt::MergeBlockData(
  1573. GlobOptBlockData *toData,
  1574. BasicBlock *toBlock,
  1575. BasicBlock *fromBlock,
  1576. BVSparse<JitArenaAllocator> *const symsRequiringCompensation,
  1577. BVSparse<JitArenaAllocator> *const symsCreatedForMerge,
  1578. bool forceTypeSpecOnLoopHeader)
  1579. {
  1580. GlobOptBlockData *fromData = &(fromBlock->globOptData);
  1581. if(DoBoundCheckHoist())
  1582. {
  1583. // Do this before merging values so that it can see whether a sym's value was changed on one side or the other
  1584. MergeBoundCheckHoistBlockData(toBlock, toData, fromBlock, fromData);
  1585. }
  1586. bool isLoopBackEdge = toBlock->isLoopHeader;
  1587. this->MergeValueMaps(toData, toBlock, fromBlock, symsRequiringCompensation, symsCreatedForMerge);
  1588. this->InsertCloneStrs(toBlock, toData, fromData);
  1589. toData->liveFields->And(fromData->liveFields);
  1590. toData->liveArrayValues->And(fromData->liveArrayValues);
  1591. toData->isTempSrc->And(fromData->isTempSrc);
  1592. toData->hasCSECandidates &= fromData->hasCSECandidates;
  1593. if (fromData->maybeWrittenTypeSyms)
  1594. {
  1595. if (toData->maybeWrittenTypeSyms == nullptr)
  1596. {
  1597. toData->maybeWrittenTypeSyms = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
  1598. toData->maybeWrittenTypeSyms->Copy(fromData->maybeWrittenTypeSyms);
  1599. }
  1600. else
  1601. {
  1602. toData->maybeWrittenTypeSyms->Or(fromData->maybeWrittenTypeSyms);
  1603. }
  1604. }
  1605. {
  1606. // - Keep the var sym live if any of the following is true:
  1607. // - The var sym is live on both sides
  1608. // - The var sym is the only live sym that contains the lossless value of the sym on a side (that is, the lossless
  1609. // int32 sym is not live, and the float64 sym is not live on that side), and the sym of any type is live on the
  1610. // other side
  1611. // - On a side, the var and float64 syms are live, the lossless int32 sym is not live, the sym's merged value is
  1612. // likely int, and the sym of any type is live on the other side. Since the value is likely int, it may be
  1613. // int-specialized (with lossless conversion) later. Keeping only the float64 sym live requires doing a lossless
  1614. // conversion from float64 to int32, with bailout if the value of the float is not a true 32-bit integer. Checking
  1615. // that is costly, and if the float64 sym is converted back to var, it does not become a tagged int, causing a
  1616. // guaranteed bailout if a lossless conversion to int happens later. Keep the var sym live to preserve its
  1617. // tagged-ness so that it can be int-specialized while avoiding unnecessary bailouts.
  1618. // - Keep the int32 sym live if it's live on both sides
  1619. // - Mark the sym as lossy if it's lossy on any side
  1620. // - Keep the float64 sym live if it's live on a side and the sym of a specialized lossless type is live on the other
  1621. // side
  1622. //
  1623. // fromData.temp =
  1624. // (fromData.var - (fromData.int32 - fromData.lossyInt32)) &
  1625. // (toData.var | toData.int32 | toData.float64)
  1626. // toData.temp =
  1627. // (toData.var - (toData.int32 - toData.lossyInt32)) &
  1628. // (fromData.var | fromData.int32 | fromData.float64)
  1629. // toData.var =
  1630. // (fromData.var & toData.var) |
  1631. // (fromData.temp - fromData.float64) |
  1632. // (toData.temp - toData.float64) |
  1633. // (fromData.temp & fromData.float64 | toData.temp & toData.float64) & (value ~ int)
  1634. //
  1635. // toData.float64 =
  1636. // fromData.float64 & ((toData.int32 - toData.lossyInt32) | toData.float64) |
  1637. // toData.float64 & ((fromData.int32 - fromData.lossyInt32) | fromData.float64)
  1638. // toData.int32 &= fromData.int32
  1639. // toData.lossyInt32 = (fromData.lossyInt32 | toData.lossyInt32) & toData.int32
  1640. BVSparse<JitArenaAllocator> tempBv1(this->tempAlloc);
  1641. BVSparse<JitArenaAllocator> tempBv2(this->tempAlloc);
  1642. if (isLoopBackEdge && forceTypeSpecOnLoopHeader)
  1643. {
  1644. Loop *const loop = toBlock->loop;
  1645. // Force to lossless int32:
  1646. // forceLosslessInt32 =
  1647. // ((fromData.int32 - fromData.lossyInt32) - (toData.int32 - toData.lossyInt32)) &
  1648. // loop.likelyIntSymsUsedBeforeDefined &
  1649. // toData.var
  1650. tempBv1.Minus(fromData->liveInt32Syms, fromData->liveLossyInt32Syms);
  1651. tempBv2.Minus(toData->liveInt32Syms, toData->liveLossyInt32Syms);
  1652. tempBv1.Minus(&tempBv2);
  1653. tempBv1.And(loop->likelyIntSymsUsedBeforeDefined);
  1654. tempBv1.And(toData->liveVarSyms);
  1655. toData->liveInt32Syms->Or(&tempBv1);
  1656. toData->liveLossyInt32Syms->Minus(&tempBv1);
  1657. if(DoLossyIntTypeSpec())
  1658. {
  1659. // Force to lossy int32:
  1660. // forceLossyInt32 = (fromData.int32 - toData.int32) & loop.symsUsedBeforeDefined & toData.var
  1661. tempBv1.Minus(fromData->liveInt32Syms, toData->liveInt32Syms);
  1662. tempBv1.And(loop->symsUsedBeforeDefined);
  1663. tempBv1.And(toData->liveVarSyms);
  1664. toData->liveInt32Syms->Or(&tempBv1);
  1665. toData->liveLossyInt32Syms->Or(&tempBv1);
  1666. }
  1667. // Force to float64:
  1668. // forceFloat64 =
  1669. // fromData.float64 & loop.forceFloat64 |
  1670. // (fromData.float64 - toData.float64) & loop.likelyNumberSymsUsedBeforeDefined
  1671. tempBv1.And(fromData->liveFloat64Syms, loop->forceFloat64SymsOnEntry);
  1672. toData->liveFloat64Syms->Or(&tempBv1);
  1673. tempBv1.Minus(fromData->liveFloat64Syms, toData->liveFloat64Syms);
  1674. tempBv1.And(loop->likelyNumberSymsUsedBeforeDefined);
  1675. toData->liveFloat64Syms->Or(&tempBv1);
  1676. // Force to Simd128 type:
  1677. // if live on the backedge and we are hoisting the operand.
  1678. // or if live on the backedge only and used before def in the loop.
  1679. tempBv1.And(fromData->liveSimd128F4Syms, loop->forceSimd128F4SymsOnEntry);
  1680. toData->liveSimd128F4Syms->Or(&tempBv1);
  1681. tempBv1.Minus(fromData->liveSimd128F4Syms, toData->liveSimd128F4Syms);
  1682. tempBv1.And(loop->likelySimd128F4SymsUsedBeforeDefined);
  1683. toData->liveSimd128F4Syms->Or(&tempBv1);
  1684. tempBv1.And(fromData->liveSimd128I4Syms, loop->forceSimd128I4SymsOnEntry);
  1685. toData->liveSimd128I4Syms->Or(&tempBv1);
  1686. tempBv1.Minus(fromData->liveSimd128I4Syms, toData->liveSimd128I4Syms);
  1687. tempBv1.And(loop->likelySimd128I4SymsUsedBeforeDefined);
  1688. toData->liveSimd128I4Syms->Or(&tempBv1);
  1689. }
  1690. BVSparse<JitArenaAllocator> simdSymsToVar(this->tempAlloc);
  1691. {
  1692. // SIMD_JS
  1693. // If we have simd128 type-spec sym live as one type on one side, but not of same type on the other, we look at the merged ValueType.
  1694. // If it's Likely the simd128 type, we choose to keep the type-spec sym (compensate with a FromVar), if the following is true:
  1695. // - We are not in jitLoopBody. Introducing a FromVar for compensation extends bytecode syms lifetime. If the value
  1696. // is actually dead, and we enter the loop-body after bailing out from SimpleJit, the value will not be restored in
  1697. // the bailout code.
  1698. // - Value was never Undefined/Null. Avoid unboxing of possibly uninitialized values.
  1699. // - Not loop back-edge. To keep unboxed value, the value has to be used-before def in the loop-body. This is done
  1700. // separately in forceSimd128*SymsOnEntry and included in loop-header.
  1701. // Live syms as F4 on one edge only
  1702. tempBv1.Xor(fromData->liveSimd128F4Syms, toData->liveSimd128F4Syms);
  1703. FOREACH_BITSET_IN_SPARSEBV(id, &tempBv1)
  1704. {
  1705. StackSym *const stackSym = this->func->m_symTable->FindStackSym(id);
  1706. Assert(stackSym);
  1707. Value *const value = this->FindValue(toData->symToValueMap, stackSym);
  1708. ValueInfo * valueInfo = value ? value->GetValueInfo() : nullptr;
  1709. // There are two possible representations for Simd128F4 Value: F4 or Var.
  1710. // If the merged ValueType is LikelySimd128F4, then on the edge where F4 is dead, Var must be alive.
  1711. // Unbox to F4 type-spec sym.
  1712. if (
  1713. valueInfo && valueInfo->IsLikelySimd128Float32x4() &&
  1714. !valueInfo->HasBeenUndefined() && !valueInfo->HasBeenNull() &&
  1715. !isLoopBackEdge && !func->IsLoopBody()
  1716. )
  1717. {
  1718. toData->liveSimd128F4Syms->Set(id);
  1719. }
  1720. else
  1721. {
  1722. // If live on both edges, box it.
  1723. if (IsLive(stackSym, fromData) && IsLive(stackSym, toData))
  1724. {
  1725. simdSymsToVar.Set(id);
  1726. }
  1727. // kill F4 sym
  1728. toData->liveSimd128F4Syms->Clear(id);
  1729. }
  1730. } NEXT_BITSET_IN_SPARSEBV;
  1731. // Same for I4
  1732. tempBv1.Xor(fromData->liveSimd128I4Syms, toData->liveSimd128I4Syms);
  1733. FOREACH_BITSET_IN_SPARSEBV(id, &tempBv1)
  1734. {
  1735. StackSym *const stackSym = this->func->m_symTable->FindStackSym(id);
  1736. Assert(stackSym);
  1737. Value *const value = this->FindValue(toData->symToValueMap, stackSym);
  1738. ValueInfo * valueInfo = value ? value->GetValueInfo() : nullptr;
  1739. if (
  1740. valueInfo && valueInfo->IsLikelySimd128Int32x4() &&
  1741. !valueInfo->HasBeenUndefined() && !valueInfo->HasBeenNull() &&
  1742. !isLoopBackEdge && !func->IsLoopBody()
  1743. )
  1744. {
  1745. toData->liveSimd128I4Syms->Set(id);
  1746. }
  1747. else
  1748. {
  1749. if (IsLive(stackSym, fromData) && IsLive(stackSym, toData))
  1750. {
  1751. simdSymsToVar.Set(id);
  1752. }
  1753. toData->liveSimd128I4Syms->Clear(id);
  1754. }
  1755. } NEXT_BITSET_IN_SPARSEBV;
  1756. }
  1757. {
  1758. BVSparse<JitArenaAllocator> tempBv3(this->tempAlloc);
  1759. // fromData.temp =
  1760. // (fromData.var - (fromData.int32 - fromData.lossyInt32)) &
  1761. // (toData.var | toData.int32 | toData.float64)
  1762. tempBv2.Minus(fromData->liveInt32Syms, fromData->liveLossyInt32Syms);
  1763. tempBv1.Minus(fromData->liveVarSyms, &tempBv2);
  1764. tempBv2.Or(toData->liveVarSyms, toData->liveInt32Syms);
  1765. tempBv2.Or(toData->liveFloat64Syms);
  1766. tempBv1.And(&tempBv2);
  1767. // toData.temp =
  1768. // (toData.var - (toData.int32 - toData.lossyInt32)) &
  1769. // (fromData.var | fromData.int32 | fromData.float64)
  1770. tempBv3.Minus(toData->liveInt32Syms, toData->liveLossyInt32Syms);
  1771. tempBv2.Minus(toData->liveVarSyms, &tempBv3);
  1772. tempBv3.Or(fromData->liveVarSyms, fromData->liveInt32Syms);
  1773. tempBv3.Or(fromData->liveFloat64Syms);
  1774. tempBv2.And(&tempBv3);
  1775. {
  1776. BVSparse<JitArenaAllocator> tempBv4(this->tempAlloc);
  1777. // fromData.temp & fromData.float64 | toData.temp & toData.float64
  1778. tempBv3.And(&tempBv1, fromData->liveFloat64Syms);
  1779. tempBv4.And(&tempBv2, toData->liveFloat64Syms);
  1780. tempBv3.Or(&tempBv4);
  1781. }
  1782. // (fromData.temp - fromData.float64) |
  1783. // (toData.temp - toData.float64)
  1784. tempBv1.Minus(fromData->liveFloat64Syms);
  1785. tempBv2.Minus(toData->liveFloat64Syms);
  1786. tempBv1.Or(&tempBv2);
  1787. // toData.var =
  1788. // (fromData.var & toData.var) |
  1789. // (fromData.temp - fromData.float64) |
  1790. // (toData.temp - toData.float64)
  1791. toData->liveVarSyms->And(fromData->liveVarSyms);
  1792. toData->liveVarSyms->Or(&tempBv1);
  1793. // toData.var |=
  1794. // (fromData.temp & fromData.float64 | toData.temp & toData.float64) & (value ~ int)
  1795. FOREACH_BITSET_IN_SPARSEBV(id, &tempBv3)
  1796. {
  1797. StackSym *const stackSym = this->func->m_symTable->FindStackSym(id);
  1798. Assert(stackSym);
  1799. Value *const value = this->FindValue(toData->symToValueMap, stackSym);
  1800. if(value)
  1801. {
  1802. ValueInfo *const valueInfo = value->GetValueInfo();
  1803. if(valueInfo->IsInt() || valueInfo->IsLikelyInt() && DoAggressiveIntTypeSpec())
  1804. {
  1805. toData->liveVarSyms->Set(id);
  1806. }
  1807. }
  1808. } NEXT_BITSET_IN_SPARSEBV;
  1809. // SIMD_JS
  1810. // Simd syms that need boxing
  1811. toData->liveVarSyms->Or(&simdSymsToVar);
  1812. }
  1813. // fromData.float64 & ((toData.int32 - toData.lossyInt32) | toData.float64)
  1814. tempBv1.Minus(toData->liveInt32Syms, toData->liveLossyInt32Syms);
  1815. tempBv1.Or(toData->liveFloat64Syms);
  1816. tempBv1.And(fromData->liveFloat64Syms);
  1817. // toData.float64 & ((fromData.int32 - fromData.lossyInt32) | fromData.float64)
  1818. tempBv2.Minus(fromData->liveInt32Syms, fromData->liveLossyInt32Syms);
  1819. tempBv2.Or(fromData->liveFloat64Syms);
  1820. tempBv2.And(toData->liveFloat64Syms);
  1821. // toData.float64 =
  1822. // fromData.float64 & ((toData.int32 - toData.lossyInt32) | toData.float64) |
  1823. // toData.float64 & ((fromData.int32 - fromData.lossyInt32) | fromData.float64)
  1824. toData->liveFloat64Syms->Or(&tempBv1, &tempBv2);
  1825. // toData.int32 &= fromData.int32
  1826. // toData.lossyInt32 = (fromData.lossyInt32 | toData.lossyInt32) & toData.int32
  1827. toData->liveInt32Syms->And(fromData->liveInt32Syms);
  1828. toData->liveLossyInt32Syms->Or(fromData->liveLossyInt32Syms);
  1829. toData->liveLossyInt32Syms->And(toData->liveInt32Syms);
  1830. }
  1831. if (TrackHoistableFields() && HasHoistableFields(fromData))
  1832. {
  1833. if (toData->hoistableFields)
  1834. {
  1835. toData->hoistableFields->Or(fromData->hoistableFields);
  1836. }
  1837. else
  1838. {
  1839. toData->hoistableFields = fromData->hoistableFields->CopyNew(this->alloc);
  1840. }
  1841. }
  1842. if (TrackArgumentsObject())
  1843. {
  1844. if (!toData->argObjSyms->Equal(fromData->argObjSyms))
  1845. {
  1846. CannotAllocateArgumentsObjectOnStack();
  1847. }
  1848. }
  1849. if (fromData->maybeTempObjectSyms && !fromData->maybeTempObjectSyms->IsEmpty())
  1850. {
  1851. if (toData->maybeTempObjectSyms)
  1852. {
  1853. toData->maybeTempObjectSyms->Or(fromData->maybeTempObjectSyms);
  1854. }
  1855. else
  1856. {
  1857. toData->maybeTempObjectSyms = fromData->maybeTempObjectSyms->CopyNew(this->alloc);
  1858. }
  1859. if (fromData->canStoreTempObjectSyms && !fromData->canStoreTempObjectSyms->IsEmpty())
  1860. {
  1861. if (toData->canStoreTempObjectSyms)
  1862. {
  1863. // Both need to be temp object
  1864. toData->canStoreTempObjectSyms->And(fromData->canStoreTempObjectSyms);
  1865. }
  1866. }
  1867. else if (toData->canStoreTempObjectSyms)
  1868. {
  1869. toData->canStoreTempObjectSyms->ClearAll();
  1870. }
  1871. }
  1872. else
  1873. {
  1874. Assert(!fromData->canStoreTempObjectSyms || fromData->canStoreTempObjectSyms->IsEmpty());
  1875. if (toData->canStoreTempObjectSyms)
  1876. {
  1877. toData->canStoreTempObjectSyms->ClearAll();
  1878. }
  1879. }
  1880. Assert(toData->curFunc == fromData->curFunc);
  1881. Assert((toData->callSequence == nullptr && fromData->callSequence == nullptr) || toData->callSequence->Equals(*(fromData->callSequence)));
  1882. Assert(toData->startCallCount == fromData->startCallCount);
  1883. Assert(toData->argOutCount == fromData->argOutCount);
  1884. Assert(toData->totalOutParamCount == fromData->totalOutParamCount);
  1885. Assert(toData->inlinedArgOutCount == fromData->inlinedArgOutCount);
  1886. // stackLiteralInitFldDataMap is a union of the stack literal from two path.
  1887. // Although we don't need the data on loop prepass, we need to do it for the loop header
  1888. // because we capture the loop header bailout on loop prepass.
  1889. if (fromData->stackLiteralInitFldDataMap != nullptr &&
  1890. (!this->IsLoopPrePass() || (toBlock->isLoopHeader && toBlock->loop == this->rootLoopPrePass)))
  1891. {
  1892. if (toData->stackLiteralInitFldDataMap == nullptr)
  1893. {
  1894. toData->stackLiteralInitFldDataMap = fromData->stackLiteralInitFldDataMap->Clone();
  1895. }
  1896. else
  1897. {
  1898. StackLiteralInitFldDataMap * toMap = toData->stackLiteralInitFldDataMap;
  1899. fromData->stackLiteralInitFldDataMap->Map([toMap](StackSym * stackSym, StackLiteralInitFldData const& data)
  1900. {
  1901. if (toMap->AddNew(stackSym, data) == -1)
  1902. {
  1903. // If there is an existing data for the stackSym, both path should match
  1904. DebugOnly(StackLiteralInitFldData const * currentData);
  1905. Assert(toMap->TryGetReference(stackSym, &currentData));
  1906. Assert(currentData->currentInitFldCount == data.currentInitFldCount);
  1907. Assert(currentData->propIds == data.propIds);
  1908. }
  1909. });
  1910. }
  1911. }
  1912. }
  1913. void
  1914. GlobOpt::DeleteBlockData(GlobOptBlockData *data)
  1915. {
  1916. JitArenaAllocator *const alloc = this->alloc;
  1917. data->symToValueMap->Delete();
  1918. data->exprToValueMap->Delete();
  1919. JitAdelete(alloc, data->liveFields);
  1920. JitAdelete(alloc, data->liveArrayValues);
  1921. if (data->maybeWrittenTypeSyms)
  1922. {
  1923. JitAdelete(alloc, data->maybeWrittenTypeSyms);
  1924. }
  1925. JitAdelete(alloc, data->isTempSrc);
  1926. JitAdelete(alloc, data->liveVarSyms);
  1927. JitAdelete(alloc, data->liveInt32Syms);
  1928. JitAdelete(alloc, data->liveLossyInt32Syms);
  1929. JitAdelete(alloc, data->liveFloat64Syms);
  1930. // SIMD_JS
  1931. JitAdelete(alloc, data->liveSimd128F4Syms);
  1932. JitAdelete(alloc, data->liveSimd128I4Syms);
  1933. if (data->hoistableFields)
  1934. {
  1935. JitAdelete(alloc, data->hoistableFields);
  1936. }
  1937. if (data->argObjSyms)
  1938. {
  1939. JitAdelete(alloc, data->argObjSyms);
  1940. }
  1941. if (data->maybeTempObjectSyms)
  1942. {
  1943. JitAdelete(alloc, data->maybeTempObjectSyms);
  1944. if (data->canStoreTempObjectSyms)
  1945. {
  1946. JitAdelete(alloc, data->canStoreTempObjectSyms);
  1947. }
  1948. }
  1949. else
  1950. {
  1951. Assert(!data->canStoreTempObjectSyms);
  1952. }
  1953. JitAdelete(alloc, data->valuesToKillOnCalls);
  1954. if(data->inductionVariables)
  1955. {
  1956. JitAdelete(alloc, data->inductionVariables);
  1957. }
  1958. if(data->availableIntBoundChecks)
  1959. {
  1960. JitAdelete(alloc, data->availableIntBoundChecks);
  1961. }
  1962. if (data->stackLiteralInitFldDataMap)
  1963. {
  1964. JitAdelete(alloc, data->stackLiteralInitFldDataMap);
  1965. }
  1966. data->OnDataDeleted();
  1967. }
  1968. void
  1969. GlobOpt::ToVar(BVSparse<JitArenaAllocator> *bv, BasicBlock *block)
  1970. {
  1971. FOREACH_BITSET_IN_SPARSEBV(id, bv)
  1972. {
  1973. StackSym *stackSym = this->func->m_symTable->FindStackSym(id);
  1974. IR::RegOpnd *newOpnd = IR::RegOpnd::New(stackSym, TyVar, this->func);
  1975. IR::Instr *lastInstr = block->GetLastInstr();
  1976. if (lastInstr->IsBranchInstr() || lastInstr->m_opcode == Js::OpCode::BailTarget)
  1977. {
  1978. // If branch is using this symbol, hoist the operand as the ToVar load will get
  1979. // inserted right before the branch.
  1980. IR::Opnd *src1 = lastInstr->GetSrc1();
  1981. if (src1)
  1982. {
  1983. if (src1->IsRegOpnd() && src1->AsRegOpnd()->m_sym == stackSym)
  1984. {
  1985. lastInstr->HoistSrc1(Js::OpCode::Ld_A);
  1986. }
  1987. IR::Opnd *src2 = lastInstr->GetSrc2();
  1988. if (src2)
  1989. {
  1990. if (src2->IsRegOpnd() && src2->AsRegOpnd()->m_sym == stackSym)
  1991. {
  1992. lastInstr->HoistSrc2(Js::OpCode::Ld_A);
  1993. }
  1994. }
  1995. }
  1996. this->ToVar(lastInstr, newOpnd, block, nullptr, false);
  1997. }
  1998. else
  1999. {
  2000. IR::Instr *lastNextInstr = lastInstr->m_next;
  2001. this->ToVar(lastNextInstr, newOpnd, block, nullptr, false);
  2002. }
  2003. } NEXT_BITSET_IN_SPARSEBV;
  2004. }
  2005. void
  2006. GlobOpt::ToInt32(BVSparse<JitArenaAllocator> *bv, BasicBlock *block, bool lossy, IR::Instr *insertBeforeInstr)
  2007. {
  2008. return this->ToTypeSpec(bv, block, TyInt32, IR::BailOutIntOnly, lossy, insertBeforeInstr);
  2009. }
  2010. void
  2011. GlobOpt::ToFloat64(BVSparse<JitArenaAllocator> *bv, BasicBlock *block)
  2012. {
  2013. return this->ToTypeSpec(bv, block, TyFloat64, IR::BailOutNumberOnly);
  2014. }
  2015. void
  2016. GlobOpt::ToTypeSpec(BVSparse<JitArenaAllocator> *bv, BasicBlock *block, IRType toType, IR::BailOutKind bailOutKind, bool lossy, IR::Instr *insertBeforeInstr)
  2017. {
  2018. FOREACH_BITSET_IN_SPARSEBV(id, bv)
  2019. {
  2020. StackSym *stackSym = this->func->m_symTable->FindStackSym(id);
  2021. IRType fromType;
  2022. // Win8 bug: 757126. If we are trying to type specialize the arguments object,
  2023. // let's make sure stack args optimization is not enabled. This is a problem, particularly,
  2024. // if the instruction comes from an unreachable block. In other cases, the pass on the
  2025. // instruction itself should disable arguments object optimization.
  2026. if(block->globOptData.argObjSyms && IsArgumentsSymID(id, block->globOptData))
  2027. {
  2028. CannotAllocateArgumentsObjectOnStack();
  2029. }
  2030. if (block->globOptData.liveVarSyms->Test(id))
  2031. {
  2032. fromType = TyVar;
  2033. }
  2034. else if (block->globOptData.liveInt32Syms->Test(id) && !block->globOptData.liveLossyInt32Syms->Test(id))
  2035. {
  2036. fromType = TyInt32;
  2037. stackSym = stackSym->GetInt32EquivSym(this->func);
  2038. }
  2039. else if (block->globOptData.liveFloat64Syms->Test(id))
  2040. {
  2041. fromType = TyFloat64;
  2042. stackSym = stackSym->GetFloat64EquivSym(this->func);
  2043. }
  2044. else
  2045. {
  2046. Assert(IsLiveAsSimd128(stackSym, &block->globOptData));
  2047. if (IsLiveAsSimd128F4(stackSym, &block->globOptData))
  2048. {
  2049. fromType = TySimd128F4;
  2050. stackSym = stackSym->GetSimd128F4EquivSym(this->func);
  2051. }
  2052. else
  2053. {
  2054. fromType = TySimd128I4;
  2055. stackSym = stackSym->GetSimd128I4EquivSym(this->func);
  2056. }
  2057. }
  2058. IR::RegOpnd *newOpnd = IR::RegOpnd::New(stackSym, fromType, this->func);
  2059. IR::Instr *lastInstr = block->GetLastInstr();
  2060. if (!insertBeforeInstr && lastInstr->IsBranchInstr())
  2061. {
  2062. // If branch is using this symbol, hoist the operand as the ToInt32 load will get
  2063. // inserted right before the branch.
  2064. IR::Instr *instrPrev = lastInstr->m_prev;
  2065. IR::Opnd *src1 = lastInstr->GetSrc1();
  2066. if (src1)
  2067. {
  2068. if (src1->IsRegOpnd() && src1->AsRegOpnd()->m_sym == stackSym)
  2069. {
  2070. lastInstr->HoistSrc1(Js::OpCode::Ld_A);
  2071. }
  2072. IR::Opnd *src2 = lastInstr->GetSrc2();
  2073. if (src2)
  2074. {
  2075. if (src2->IsRegOpnd() && src2->AsRegOpnd()->m_sym == stackSym)
  2076. {
  2077. lastInstr->HoistSrc2(Js::OpCode::Ld_A);
  2078. }
  2079. }
  2080. // Did we insert anything?
  2081. if (lastInstr->m_prev != instrPrev)
  2082. {
  2083. // If we had ByteCodeUses right before the branch, move them back down.
  2084. IR::Instr *insertPoint = lastInstr;
  2085. for (IR::Instr *instrBytecode = instrPrev; instrBytecode->m_opcode == Js::OpCode::ByteCodeUses; instrBytecode = instrBytecode->m_prev)
  2086. {
  2087. instrBytecode->Unlink();
  2088. insertPoint->InsertBefore(instrBytecode);
  2089. insertPoint = instrBytecode;
  2090. }
  2091. }
  2092. }
  2093. }
  2094. this->ToTypeSpecUse(nullptr, newOpnd, block, nullptr, nullptr, toType, bailOutKind, lossy, insertBeforeInstr);
  2095. } NEXT_BITSET_IN_SPARSEBV;
  2096. }
  2097. void
  2098. GlobOpt::CleanUpValueMaps()
  2099. {
  2100. // Don't do cleanup if it's been done recently.
  2101. // Landing pad could get optimized twice...
  2102. // We want the same info out the first and second time. So always cleanup.
  2103. // Increasing the cleanup threshold count for asmjs to 500
  2104. uint cleanupCount = (!GetIsAsmJSFunc()) ? CONFIG_FLAG(GoptCleanupThreshold) : CONFIG_FLAG(AsmGoptCleanupThreshold);
  2105. if (!this->currentBlock->IsLandingPad() && this->instrCountSinceLastCleanUp < cleanupCount)
  2106. {
  2107. return;
  2108. }
  2109. this->instrCountSinceLastCleanUp = 0;
  2110. GlobHashTable *thisTable = this->blockData.symToValueMap;
  2111. BVSparse<JitArenaAllocator> deadSymsBv(this->tempAlloc);
  2112. BVSparse<JitArenaAllocator> keepAliveSymsBv(this->tempAlloc);
  2113. BVSparse<JitArenaAllocator> availableValueNumbers(this->tempAlloc);
  2114. availableValueNumbers.Copy(byteCodeConstantValueNumbersBv);
  2115. BVSparse<JitArenaAllocator> *upwardExposedUses = this->currentBlock->upwardExposedUses;
  2116. BVSparse<JitArenaAllocator> *upwardExposedFields = this->currentBlock->upwardExposedFields;
  2117. bool isInLoop = !!this->currentBlock->loop;
  2118. for (uint i = 0; i < thisTable->tableSize; i++)
  2119. {
  2120. FOREACH_SLISTBASE_ENTRY_EDITING(GlobHashBucket, bucket, &thisTable->table[i], iter)
  2121. {
  2122. // Make sure symbol was created before backward pass.
  2123. // If symbols isn't upward exposed, mark it as dead.
  2124. // If a symbol was copy-prop'd in a loop prepass, the upwardExposedUses info could be wrong. So wait until we are out of the loop before clearing it.
  2125. if ((SymID)bucket.value->m_id <= this->maxInitialSymID && !upwardExposedUses->Test(bucket.value->m_id) && !upwardExposedFields->Test(bucket.value->m_id)
  2126. && (!isInLoop || !this->prePassCopyPropSym->Test(bucket.value->m_id)))
  2127. {
  2128. Value *val = bucket.element;
  2129. ValueInfo *valueInfo = val->GetValueInfo();
  2130. Sym * sym = bucket.value;
  2131. Sym *symStore = valueInfo->GetSymStore();
  2132. if (symStore && symStore == bucket.value)
  2133. {
  2134. // Keep constants around, as we don't know if there will be further uses
  2135. if (!bucket.element->GetValueInfo()->IsVarConstant() && !bucket.element->GetValueInfo()->HasIntConstantValue())
  2136. {
  2137. // Symbol may still be a copy-prop candidate. Wait before deleting it.
  2138. deadSymsBv.Set(bucket.value->m_id);
  2139. // Make sure the type sym is added to the dead syms vector as well, because type syms are
  2140. // created in backward pass and so their symIds > maxInitialSymID.
  2141. if (sym->IsStackSym() && sym->AsStackSym()->HasObjectTypeSym())
  2142. {
  2143. deadSymsBv.Set(sym->AsStackSym()->GetObjectTypeSym()->m_id);
  2144. }
  2145. }
  2146. availableValueNumbers.Set(val->GetValueNumber());
  2147. }
  2148. else
  2149. {
  2150. // Make sure the type sym is added to the dead syms vector as well, because type syms are
  2151. // created in backward pass and so their symIds > maxInitialSymID. Perhaps we could remove
  2152. // it explicitly here, but would it work alright with the iterator?
  2153. if (sym->IsStackSym() && sym->AsStackSym()->HasObjectTypeSym())
  2154. {
  2155. deadSymsBv.Set(sym->AsStackSym()->GetObjectTypeSym()->m_id);
  2156. }
  2157. // Not a copy-prop candidate; delete it right away.
  2158. iter.RemoveCurrent(thisTable->alloc);
  2159. this->blockData.liveInt32Syms->Clear(sym->m_id);
  2160. this->blockData.liveLossyInt32Syms->Clear(sym->m_id);
  2161. this->blockData.liveFloat64Syms->Clear(sym->m_id);
  2162. }
  2163. }
  2164. else
  2165. {
  2166. Sym * sym = bucket.value;
  2167. if (sym->IsPropertySym() && !this->blockData.liveFields->Test(sym->m_id))
  2168. {
  2169. // Remove propertySyms which are not live anymore.
  2170. iter.RemoveCurrent(thisTable->alloc);
  2171. this->blockData.liveInt32Syms->Clear(sym->m_id);
  2172. this->blockData.liveLossyInt32Syms->Clear(sym->m_id);
  2173. this->blockData.liveFloat64Syms->Clear(sym->m_id);
  2174. }
  2175. else
  2176. {
  2177. // Look at the copy-prop candidate. We don't want to get rid of the data for a symbol which is
  2178. // a copy-prop candidate.
  2179. Value *val = bucket.element;
  2180. ValueInfo *valueInfo = val->GetValueInfo();
  2181. Sym *symStore = valueInfo->GetSymStore();
  2182. if (symStore && symStore != bucket.value)
  2183. {
  2184. keepAliveSymsBv.Set(symStore->m_id);
  2185. if (symStore->IsStackSym() && symStore->AsStackSym()->HasObjectTypeSym())
  2186. {
  2187. keepAliveSymsBv.Set(symStore->AsStackSym()->GetObjectTypeSym()->m_id);
  2188. }
  2189. }
  2190. availableValueNumbers.Set(val->GetValueNumber());
  2191. }
  2192. }
  2193. } NEXT_SLISTBASE_ENTRY_EDITING;
  2194. }
  2195. deadSymsBv.Minus(&keepAliveSymsBv);
  2196. // Now cleanup exprToValueMap table
  2197. ExprHashTable *thisExprTable = this->blockData.exprToValueMap;
  2198. bool oldHasCSECandidatesValue = this->currentBlock->globOptData.hasCSECandidates; // Could be false if none need bailout.
  2199. this->currentBlock->globOptData.hasCSECandidates = false;
  2200. for (uint i = 0; i < thisExprTable->tableSize; i++)
  2201. {
  2202. FOREACH_SLISTBASE_ENTRY_EDITING(ExprHashBucket, bucket, &thisExprTable->table[i], iter)
  2203. {
  2204. ExprHash hash = bucket.value;
  2205. ValueNumber src1ValNum = hash.GetSrc1ValueNumber();
  2206. ValueNumber src2ValNum = hash.GetSrc2ValueNumber();
  2207. // If src1Val or src2Val are not available anymore, no point keeping this CSE candidate
  2208. bool removeCurrent = false;
  2209. if ((src1ValNum && !availableValueNumbers.Test(src1ValNum))
  2210. || (src2ValNum && !availableValueNumbers.Test(src2ValNum)))
  2211. {
  2212. removeCurrent = true;
  2213. }
  2214. else
  2215. {
  2216. // If we are keeping this value, make sure we also keep the symStore in the value table
  2217. removeCurrent = true; // Remove by default, unless it's set to false later below.
  2218. Value *val = bucket.element;
  2219. if (val)
  2220. {
  2221. Sym *symStore = val->GetValueInfo()->GetSymStore();
  2222. if (symStore)
  2223. {
  2224. Value *symStoreVal = this->FindValue(this->currentBlock->globOptData.symToValueMap, symStore);
  2225. if (symStoreVal && symStoreVal->GetValueNumber() == val->GetValueNumber())
  2226. {
  2227. removeCurrent = false;
  2228. deadSymsBv.Clear(symStore->m_id);
  2229. if (symStore->IsStackSym() && symStore->AsStackSym()->HasObjectTypeSym())
  2230. {
  2231. deadSymsBv.Clear(symStore->AsStackSym()->GetObjectTypeSym()->m_id);
  2232. }
  2233. }
  2234. }
  2235. }
  2236. }
  2237. if(removeCurrent)
  2238. {
  2239. iter.RemoveCurrent(thisExprTable->alloc);
  2240. }
  2241. else
  2242. {
  2243. this->currentBlock->globOptData.hasCSECandidates = oldHasCSECandidatesValue;
  2244. }
  2245. } NEXT_SLISTBASE_ENTRY_EDITING;
  2246. }
  2247. FOREACH_BITSET_IN_SPARSEBV(dead_id, &deadSymsBv)
  2248. {
  2249. thisTable->Clear(dead_id);
  2250. }
  2251. NEXT_BITSET_IN_SPARSEBV;
  2252. if (!deadSymsBv.IsEmpty())
  2253. {
  2254. if (this->func->IsJitInDebugMode())
  2255. {
  2256. // Do not remove non-temp local vars from liveVarSyms (i.e. do not let them become dead).
  2257. // We will need to restore all initialized/used so far non-temp local during bail out.
  2258. // (See BackwardPass::ProcessBailOutInfo)
  2259. Assert(this->func->m_nonTempLocalVars);
  2260. BVSparse<JitArenaAllocator> tempBv(this->tempAlloc);
  2261. tempBv.Minus(&deadSymsBv, this->func->m_nonTempLocalVars);
  2262. this->blockData.liveVarSyms->Minus(&tempBv);
  2263. #if DBG
  2264. tempBv.And(this->blockData.liveInt32Syms, this->func->m_nonTempLocalVars);
  2265. AssertMsg(tempBv.IsEmpty(), "Type spec is disabled under debugger. How come did we get a non-temp local in liveInt32Syms?");
  2266. tempBv.And(this->blockData.liveLossyInt32Syms, this->func->m_nonTempLocalVars);
  2267. AssertMsg(tempBv.IsEmpty(), "Type spec is disabled under debugger. How come did we get a non-temp local in liveLossyInt32Syms?");
  2268. tempBv.And(this->blockData.liveFloat64Syms, this->func->m_nonTempLocalVars);
  2269. AssertMsg(tempBv.IsEmpty(), "Type spec is disabled under debugger. How come did we get a non-temp local in liveFloat64Syms?");
  2270. #endif
  2271. }
  2272. else
  2273. {
  2274. this->blockData.liveVarSyms->Minus(&deadSymsBv);
  2275. }
  2276. this->blockData.liveInt32Syms->Minus(&deadSymsBv);
  2277. this->blockData.liveLossyInt32Syms->Minus(&deadSymsBv);
  2278. this->blockData.liveFloat64Syms->Minus(&deadSymsBv);
  2279. }
  2280. JitAdelete(this->alloc, upwardExposedUses);
  2281. this->currentBlock->upwardExposedUses = nullptr;
  2282. JitAdelete(this->alloc, upwardExposedFields);
  2283. this->currentBlock->upwardExposedFields = nullptr;
  2284. if (this->currentBlock->cloneStrCandidates)
  2285. {
  2286. JitAdelete(this->alloc, this->currentBlock->cloneStrCandidates);
  2287. this->currentBlock->cloneStrCandidates = nullptr;
  2288. }
  2289. }
  2290. PRECandidatesList * GlobOpt::FindBackEdgePRECandidates(BasicBlock *block, JitArenaAllocator *alloc)
  2291. {
  2292. // Iterate over the value table looking for propertySyms which are candidates to
  2293. // pre-load in the landing pad for field PRE
  2294. GlobHashTable *valueTable = block->globOptData.symToValueMap;
  2295. Loop *loop = block->loop;
  2296. PRECandidatesList *candidates = nullptr;
  2297. for (uint i = 0; i < valueTable->tableSize; i++)
  2298. {
  2299. FOREACH_SLISTBASE_ENTRY(GlobHashBucket, bucket, &valueTable->table[i])
  2300. {
  2301. Sym *sym = bucket.value;
  2302. if (!sym->IsPropertySym())
  2303. {
  2304. continue;
  2305. }
  2306. PropertySym *propertySym = sym->AsPropertySym();
  2307. // Field should be live on the back-edge
  2308. if (!block->globOptData.liveFields->Test(propertySym->m_id))
  2309. {
  2310. continue;
  2311. }
  2312. // Field should be live in the landing pad as well
  2313. if (!loop->landingPad->globOptData.liveFields->Test(propertySym->m_id))
  2314. {
  2315. continue;
  2316. }
  2317. Value *value = bucket.element;
  2318. Sym *symStore = value->GetValueInfo()->GetSymStore();
  2319. if (!symStore || !symStore->IsStackSym())
  2320. {
  2321. continue;
  2322. }
  2323. // Check upwardExposed in case of:
  2324. // s1 = 0;
  2325. // loop:
  2326. // = o.x;
  2327. // foo();
  2328. // o.x = s1;
  2329. // Can't thrash s1 in loop top.
  2330. if (!symStore->AsStackSym()->IsSingleDef() || loop->GetHeadBlock()->upwardExposedUses->Test(symStore->m_id))
  2331. {
  2332. // If symStore isn't singleDef, we need to make sure it still has the same value.
  2333. // This usually fails if we are not aggressive at transferring values in the prepass.
  2334. Value **pSymStoreFromValue = valueTable->Get(symStore->m_id);
  2335. // Consider: We should be fine if symStore isn't live in landing pad...
  2336. if (!pSymStoreFromValue || (*pSymStoreFromValue)->GetValueNumber() != value->GetValueNumber())
  2337. {
  2338. continue;
  2339. }
  2340. }
  2341. BasicBlock *landingPad = loop->landingPad;
  2342. Value *landingPadValue = this->FindValue(landingPad->globOptData.symToValueMap, propertySym);
  2343. if (!landingPadValue)
  2344. {
  2345. // Value should be added as initial value or already be there.
  2346. return false;
  2347. }
  2348. IR::Instr * ldInstr = this->prePassInstrMap->Lookup(propertySym->m_id, nullptr);
  2349. if (!ldInstr)
  2350. {
  2351. continue;
  2352. }
  2353. if (!candidates)
  2354. {
  2355. candidates = Anew(alloc, PRECandidatesList, alloc);
  2356. }
  2357. candidates->Prepend(&bucket);
  2358. } NEXT_SLISTBASE_ENTRY;
  2359. }
  2360. return candidates;
  2361. }
  2362. PRECandidatesList * GlobOpt::RemoveUnavailableCandidates(BasicBlock *block, PRECandidatesList *candidates, JitArenaAllocator *alloc)
  2363. {
  2364. // In case of multiple back-edges to the loop, make sure the candidates are still valid.
  2365. FOREACH_SLIST_ENTRY_EDITING(GlobHashBucket*, candidate, (SList<GlobHashBucket*>*)candidates, iter)
  2366. {
  2367. Value *candidateValue = candidate->element;
  2368. PropertySym *candidatePropertySym = candidate->value->AsPropertySym();
  2369. ValueNumber valueNumber = candidateValue->GetValueNumber();
  2370. Sym *symStore = candidateValue->GetValueInfo()->GetSymStore();
  2371. Value *blockValue = this->FindValue(block->globOptData.symToValueMap, candidatePropertySym);
  2372. if (blockValue && blockValue->GetValueNumber() == valueNumber
  2373. && blockValue->GetValueInfo()->GetSymStore() == symStore)
  2374. {
  2375. Value *symStoreValue = this->FindValue(block->globOptData.symToValueMap, symStore);
  2376. if (symStoreValue && symStoreValue->GetValueNumber() == valueNumber)
  2377. {
  2378. continue;
  2379. }
  2380. }
  2381. iter.RemoveCurrent();
  2382. } NEXT_SLIST_ENTRY_EDITING;
  2383. return candidates;
  2384. }
  2385. PRECandidatesList * GlobOpt::FindPossiblePRECandidates(Loop *loop, JitArenaAllocator *alloc)
  2386. {
  2387. // Find the set of PRE candidates
  2388. BasicBlock *loopHeader = loop->GetHeadBlock();
  2389. PRECandidatesList *candidates = nullptr;
  2390. bool firstBackEdge = true;
  2391. FOREACH_PREDECESSOR_BLOCK(blockPred, loopHeader)
  2392. {
  2393. if (!loop->IsDescendentOrSelf(blockPred->loop))
  2394. {
  2395. // Not a loop back-edge
  2396. continue;
  2397. }
  2398. if (firstBackEdge)
  2399. {
  2400. candidates = this->FindBackEdgePRECandidates(blockPred, alloc);
  2401. }
  2402. else
  2403. {
  2404. candidates = this->RemoveUnavailableCandidates(blockPred, candidates, alloc);
  2405. }
  2406. } NEXT_PREDECESSOR_BLOCK;
  2407. return candidates;
  2408. }
  2409. BOOL GlobOpt::PreloadPRECandidate(Loop *loop, GlobHashBucket* candidate)
  2410. {
  2411. // Insert a load for each field PRE candidate.
  2412. PropertySym *propertySym = candidate->value->AsPropertySym();
  2413. StackSym *objPtrSym = propertySym->m_stackSym;
  2414. // If objPtr isn't live, we'll retry later.
  2415. // Another PRE candidate may insert a load for it.
  2416. if (!this->IsLive(objPtrSym, loop->landingPad))
  2417. {
  2418. return false;
  2419. }
  2420. BasicBlock *landingPad = loop->landingPad;
  2421. Value *value = candidate->element;
  2422. Sym *symStore = value->GetValueInfo()->GetSymStore();
  2423. // The symStore can't be live into the loop
  2424. // The symStore needs to still have the same value
  2425. Assert(symStore && symStore->IsStackSym());
  2426. if (this->IsLive(symStore, loop->landingPad))
  2427. {
  2428. // May have already been hoisted:
  2429. // o.x = t1;
  2430. // o.y = t1;
  2431. return false;
  2432. }
  2433. Value *landingPadValue = this->FindValue(landingPad->globOptData.symToValueMap, propertySym);
  2434. // Value should be added as initial value or already be there.
  2435. Assert(landingPadValue);
  2436. IR::Instr * ldInstr = this->prePassInstrMap->Lookup(propertySym->m_id, nullptr);
  2437. Assert(ldInstr);
  2438. Js::Type *propertyType = nullptr;
  2439. // Create instr to put in landing pad for compensation
  2440. Assert(IsPREInstrCandidateLoad(ldInstr->m_opcode));
  2441. IR::SymOpnd *ldSrc = ldInstr->GetSrc1()->AsSymOpnd();
  2442. if (ldSrc->m_sym != propertySym)
  2443. {
  2444. // It's possible that the propertySym but have equivalent objPtrs. Verify their values.
  2445. Value *val1 = this->FindValue(ldSrc->m_sym->AsPropertySym()->m_stackSym);
  2446. Value *val2 = this->FindValue(propertySym->m_stackSym);
  2447. if (!val1 || !val2 || val1->GetValueNumber() != val2->GetValueNumber())
  2448. {
  2449. return false;
  2450. }
  2451. }
  2452. ldInstr = ldInstr->Copy();
  2453. // Consider: Shouldn't be necessary once we have copy-prop in prepass...
  2454. ldInstr->GetSrc1()->AsSymOpnd()->m_sym = propertySym;
  2455. ldSrc = ldInstr->GetSrc1()->AsSymOpnd();
  2456. if (ldSrc->IsPropertySymOpnd())
  2457. {
  2458. IR::PropertySymOpnd *propSymOpnd = ldSrc->AsPropertySymOpnd();
  2459. IR::PropertySymOpnd *newPropSymOpnd;
  2460. if (propSymOpnd->IsMonoObjTypeSpecCandidate())
  2461. {
  2462. propertyType = propSymOpnd->GetType();
  2463. }
  2464. newPropSymOpnd = propSymOpnd->AsPropertySymOpnd()->CopyWithoutFlowSensitiveInfo(this->func);
  2465. ldInstr->ReplaceSrc1(newPropSymOpnd);
  2466. }
  2467. if (ldInstr->GetDst()->AsRegOpnd()->m_sym != symStore)
  2468. {
  2469. ldInstr->ReplaceDst(IR::RegOpnd::New(symStore->AsStackSym(), TyVar, this->func));
  2470. }
  2471. ldInstr->GetSrc1()->SetIsJITOptimizedReg(true);
  2472. ldInstr->GetDst()->SetIsJITOptimizedReg(true);
  2473. landingPad->globOptData.liveVarSyms->Set(symStore->m_id);
  2474. loop->fieldPRESymStore->Set(symStore->m_id);
  2475. ValueType valueType(ValueType::Uninitialized);
  2476. Value *initialValue;
  2477. if (loop->initialValueFieldMap.TryGetValue(propertySym, &initialValue))
  2478. {
  2479. if (ldInstr->IsProfiledInstr())
  2480. {
  2481. if (initialValue->GetValueNumber() == value->GetValueNumber())
  2482. {
  2483. if (value->GetValueInfo()->IsUninitialized())
  2484. {
  2485. valueType = ldInstr->AsProfiledInstr()->u.FldInfo().valueType;
  2486. }
  2487. else
  2488. {
  2489. valueType = value->GetValueInfo()->Type();
  2490. }
  2491. }
  2492. else
  2493. {
  2494. valueType = ValueType::Uninitialized;
  2495. }
  2496. ldInstr->AsProfiledInstr()->u.FldInfo().valueType = valueType;
  2497. }
  2498. }
  2499. else
  2500. {
  2501. valueType = landingPadValue->GetValueInfo()->Type();
  2502. }
  2503. loop->symsUsedBeforeDefined->Set(symStore->m_id);
  2504. if (valueType.IsLikelyNumber())
  2505. {
  2506. loop->likelyNumberSymsUsedBeforeDefined->Set(symStore->m_id);
  2507. if (DoAggressiveIntTypeSpec() ? valueType.IsLikelyInt() : valueType.IsInt())
  2508. {
  2509. // Can only force int conversions in the landing pad based on likely-int values if aggressive int type
  2510. // specialization is enabled
  2511. loop->likelyIntSymsUsedBeforeDefined->Set(symStore->m_id);
  2512. }
  2513. }
  2514. // Insert in landing pad
  2515. if (OpCodeAttr::HasImplicitCall(ldInstr->m_opcode))
  2516. {
  2517. IR::Instr * bailInstr = EnsureDisableImplicitCallRegion(loop);
  2518. bailInstr->InsertBefore(ldInstr);
  2519. }
  2520. else
  2521. {
  2522. // Currently there are only LdSlot and LdSlotArr that are PRE candidate and doesn't have implicit call
  2523. Assert(ldInstr->m_opcode == Js::OpCode::LdSlot || ldInstr->m_opcode == Js::OpCode::LdSlotArr);
  2524. if (loop->endDisableImplicitCall)
  2525. {
  2526. loop->endDisableImplicitCall->InsertBefore(ldInstr);
  2527. }
  2528. else
  2529. {
  2530. loop->landingPad->InsertAfter(ldInstr);
  2531. }
  2532. }
  2533. ldInstr->ClearByteCodeOffset();
  2534. ldInstr->SetByteCodeOffset(landingPad->GetFirstInstr());
  2535. #if DBG_DUMP
  2536. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::FieldPREPhase, this->func->GetSourceContextId(), this->func->GetLocalFunctionId()))
  2537. {
  2538. Output::Print(_u("** TRACE: Field PRE: field pre-loaded in landing pad of loop head #%-3d: "), loop->GetHeadBlock()->GetBlockNum());
  2539. ldInstr->Dump();
  2540. Output::Print(_u("\n"));
  2541. }
  2542. #endif
  2543. return true;
  2544. }
  2545. void GlobOpt::PreloadPRECandidates(Loop *loop, PRECandidatesList *candidates)
  2546. {
  2547. // Insert loads in landing pad for field PRE candidates. Iterate while(changed)
  2548. // for the o.x.y cases.
  2549. BOOL changed = true;
  2550. if (!candidates)
  2551. {
  2552. return;
  2553. }
  2554. Assert(loop->landingPad->GetFirstInstr() == loop->landingPad->GetLastInstr());
  2555. while (changed)
  2556. {
  2557. changed = false;
  2558. FOREACH_SLIST_ENTRY_EDITING(GlobHashBucket*, candidate, (SList<GlobHashBucket*>*)candidates, iter)
  2559. {
  2560. if (this->PreloadPRECandidate(loop, candidate))
  2561. {
  2562. changed = true;
  2563. iter.RemoveCurrent();
  2564. }
  2565. } NEXT_SLIST_ENTRY_EDITING;
  2566. }
  2567. }
  2568. void GlobOpt::FieldPRE(Loop *loop)
  2569. {
  2570. if (!DoFieldPRE(loop))
  2571. {
  2572. return;
  2573. }
  2574. PRECandidatesList *candidates;
  2575. JitArenaAllocator *alloc = this->tempAlloc;
  2576. candidates = this->FindPossiblePRECandidates(loop, alloc);
  2577. this->PreloadPRECandidates(loop, candidates);
  2578. }
  2579. void GlobOpt::InsertCloneStrs(BasicBlock *toBlock, GlobOptBlockData *toData, GlobOptBlockData *fromData)
  2580. {
  2581. if (toBlock->isLoopHeader // isLoopBackEdge
  2582. && toBlock->cloneStrCandidates
  2583. && !IsLoopPrePass())
  2584. {
  2585. Loop *loop = toBlock->loop;
  2586. BasicBlock *landingPad = loop->landingPad;
  2587. const SymTable *const symTable = func->m_symTable;
  2588. Assert(tempBv->IsEmpty());
  2589. tempBv->And(toBlock->cloneStrCandidates, fromData->isTempSrc);
  2590. FOREACH_BITSET_IN_SPARSEBV(id, tempBv)
  2591. {
  2592. StackSym *const sym = (StackSym *)symTable->Find(id);
  2593. Assert(sym);
  2594. if (!landingPad->globOptData.liveVarSyms->Test(id)
  2595. || !fromData->liveVarSyms->Test(id))
  2596. {
  2597. continue;
  2598. }
  2599. Value * landingPadValue = FindValue(landingPad->globOptData.symToValueMap, sym);
  2600. if (landingPadValue == nullptr)
  2601. {
  2602. continue;
  2603. }
  2604. Value * loopValue = FindValue(fromData->symToValueMap, sym);
  2605. if (loopValue == nullptr)
  2606. {
  2607. continue;
  2608. }
  2609. ValueInfo *landingPadValueInfo = landingPadValue->GetValueInfo();
  2610. ValueInfo *loopValueInfo = loopValue->GetValueInfo();
  2611. if (landingPadValueInfo->IsLikelyString()
  2612. && loopValueInfo->IsLikelyString())
  2613. {
  2614. IR::Instr *cloneStr = IR::Instr::New(Js::OpCode::CloneStr, this->func);
  2615. IR::RegOpnd *opnd = IR::RegOpnd::New(sym, IRType::TyVar, this->func);
  2616. cloneStr->SetDst(opnd);
  2617. cloneStr->SetSrc1(opnd);
  2618. if (loop->bailOutInfo->bailOutInstr)
  2619. {
  2620. loop->bailOutInfo->bailOutInstr->InsertBefore(cloneStr);
  2621. }
  2622. else
  2623. {
  2624. landingPad->InsertAfter(cloneStr);
  2625. }
  2626. toData->isTempSrc->Set(id);
  2627. }
  2628. }
  2629. NEXT_BITSET_IN_SPARSEBV;
  2630. tempBv->ClearAll();
  2631. }
  2632. }
  2633. void
  2634. GlobOpt::MergeValueMaps(
  2635. GlobOptBlockData *toData,
  2636. BasicBlock *toBlock,
  2637. BasicBlock *fromBlock,
  2638. BVSparse<JitArenaAllocator> *const symsRequiringCompensation,
  2639. BVSparse<JitArenaAllocator> *const symsCreatedForMerge)
  2640. {
  2641. GlobOptBlockData *fromData = &(fromBlock->globOptData);
  2642. bool isLoopBackEdge = toBlock->isLoopHeader;
  2643. Loop *loop = toBlock->loop;
  2644. bool isLoopPrepass = (loop && this->prePassLoop == loop);
  2645. Assert(valuesCreatedForMerge->Count() == 0);
  2646. DebugOnly(ValueSetByValueNumber mergedValues(tempAlloc, 64));
  2647. BVSparse<JitArenaAllocator> *const mergedValueTypesTrackedForKills = tempBv;
  2648. Assert(mergedValueTypesTrackedForKills->IsEmpty());
  2649. toData->valuesToKillOnCalls->Clear(); // the tracking will be reevaluated based on merged value types
  2650. GlobHashTable *thisTable = toData->symToValueMap;
  2651. GlobHashTable *otherTable = fromData->symToValueMap;
  2652. for (uint i = 0; i < thisTable->tableSize; i++)
  2653. {
  2654. SListBase<GlobHashBucket>::Iterator iter2(&otherTable->table[i]);
  2655. iter2.Next();
  2656. FOREACH_SLISTBASE_ENTRY_EDITING(GlobHashBucket, bucket, &thisTable->table[i], iter)
  2657. {
  2658. while (iter2.IsValid() && bucket.value->m_id < iter2.Data().value->m_id)
  2659. {
  2660. iter2.Next();
  2661. }
  2662. Value *newValue = nullptr;
  2663. if (iter2.IsValid() && bucket.value->m_id == iter2.Data().value->m_id)
  2664. {
  2665. newValue =
  2666. MergeValues(
  2667. bucket.element,
  2668. iter2.Data().element,
  2669. iter2.Data().value,
  2670. toData,
  2671. fromData,
  2672. isLoopBackEdge,
  2673. symsRequiringCompensation,
  2674. symsCreatedForMerge);
  2675. }
  2676. if (newValue == nullptr)
  2677. {
  2678. iter.RemoveCurrent(thisTable->alloc);
  2679. continue;
  2680. }
  2681. else
  2682. {
  2683. #if DBG
  2684. // Ensure that only one value per value number is produced by merge. Byte-code constant values are reused in
  2685. // multiple blocks without cloning, so exclude those value numbers.
  2686. {
  2687. Value *const previouslyMergedValue = mergedValues.Lookup(newValue->GetValueNumber());
  2688. if (previouslyMergedValue)
  2689. {
  2690. if (!byteCodeConstantValueNumbersBv->Test(newValue->GetValueNumber()))
  2691. {
  2692. Assert(newValue == previouslyMergedValue);
  2693. }
  2694. }
  2695. else
  2696. {
  2697. mergedValues.Add(newValue);
  2698. }
  2699. }
  2700. #endif
  2701. TrackMergedValueForKills(newValue, toData, mergedValueTypesTrackedForKills);
  2702. bucket.element = newValue;
  2703. }
  2704. iter2.Next();
  2705. } NEXT_SLISTBASE_ENTRY_EDITING;
  2706. if (isLoopPrepass && !this->rootLoopPrePass->allFieldsKilled)
  2707. {
  2708. while (iter2.IsValid())
  2709. {
  2710. iter2.Next();
  2711. }
  2712. }
  2713. }
  2714. valuesCreatedForMerge->Clear();
  2715. DebugOnly(mergedValues.Reset());
  2716. mergedValueTypesTrackedForKills->ClearAll();
  2717. toData->exprToValueMap->And(fromData->exprToValueMap);
  2718. ProcessValueKills(toBlock, toData);
  2719. bool isLastLoopBackEdge = false;
  2720. if (isLoopBackEdge)
  2721. {
  2722. ProcessValueKillsForLoopHeaderAfterBackEdgeMerge(toBlock, toData);
  2723. BasicBlock *lastBlock = nullptr;
  2724. FOREACH_PREDECESSOR_BLOCK(pred, toBlock)
  2725. {
  2726. Assert(!lastBlock || pred->GetBlockNum() > lastBlock->GetBlockNum());
  2727. lastBlock = pred;
  2728. }NEXT_PREDECESSOR_BLOCK;
  2729. isLastLoopBackEdge = (lastBlock == fromBlock);
  2730. }
  2731. }
  2732. Value *
  2733. GlobOpt::MergeValues(
  2734. Value *toDataValue,
  2735. Value *fromDataValue,
  2736. Sym *fromDataSym,
  2737. GlobOptBlockData *toData,
  2738. GlobOptBlockData *fromData,
  2739. bool isLoopBackEdge,
  2740. BVSparse<JitArenaAllocator> *const symsRequiringCompensation,
  2741. BVSparse<JitArenaAllocator> *const symsCreatedForMerge)
  2742. {
  2743. // Same map
  2744. if (toDataValue == fromDataValue)
  2745. {
  2746. return toDataValue;
  2747. }
  2748. const ValueNumberPair sourceValueNumberPair(toDataValue->GetValueNumber(), fromDataValue->GetValueNumber());
  2749. const bool sameValueNumber = sourceValueNumberPair.First() == sourceValueNumberPair.Second();
  2750. ValueInfo *newValueInfo =
  2751. this->MergeValueInfo(
  2752. toDataValue,
  2753. fromDataValue,
  2754. fromDataSym,
  2755. fromData,
  2756. isLoopBackEdge,
  2757. sameValueNumber,
  2758. symsRequiringCompensation,
  2759. symsCreatedForMerge);
  2760. if (newValueInfo == nullptr)
  2761. {
  2762. return nullptr;
  2763. }
  2764. if (sameValueNumber && newValueInfo == toDataValue->GetValueInfo())
  2765. {
  2766. return toDataValue;
  2767. }
  2768. // There may be other syms in toData that haven't been merged yet, referring to the current toData value for this sym. If
  2769. // the merge produced a new value info, don't corrupt the value info for the other sym by changing the same value. Instead,
  2770. // create one value per source value number pair per merge and reuse that for new value infos.
  2771. Value *newValue = valuesCreatedForMerge->Lookup(sourceValueNumberPair, nullptr);
  2772. if(newValue)
  2773. {
  2774. Assert(sameValueNumber == (newValue->GetValueNumber() == toDataValue->GetValueNumber()));
  2775. // This is an exception where Value::SetValueInfo is called directly instead of GlobOpt::ChangeValueInfo, because we're
  2776. // actually generating new value info through merges.
  2777. newValue->SetValueInfo(newValueInfo);
  2778. }
  2779. else
  2780. {
  2781. newValue = NewValue(sameValueNumber ? sourceValueNumberPair.First() : NewValueNumber(), newValueInfo);
  2782. valuesCreatedForMerge->Add(sourceValueNumberPair, newValue);
  2783. }
  2784. // Set symStore if same on both paths.
  2785. if (toDataValue->GetValueInfo()->GetSymStore() == fromDataValue->GetValueInfo()->GetSymStore())
  2786. {
  2787. newValueInfo->SetSymStore(toDataValue->GetValueInfo()->GetSymStore());
  2788. }
  2789. return newValue;
  2790. }
  2791. ValueInfo *
  2792. GlobOpt::MergeValueInfo(
  2793. Value *toDataVal,
  2794. Value *fromDataVal,
  2795. Sym *fromDataSym,
  2796. GlobOptBlockData *fromData,
  2797. bool isLoopBackEdge,
  2798. bool sameValueNumber,
  2799. BVSparse<JitArenaAllocator> *const symsRequiringCompensation,
  2800. BVSparse<JitArenaAllocator> *const symsCreatedForMerge)
  2801. {
  2802. ValueInfo *const toDataValueInfo = toDataVal->GetValueInfo();
  2803. ValueInfo *const fromDataValueInfo = fromDataVal->GetValueInfo();
  2804. // Same value
  2805. if (toDataValueInfo == fromDataValueInfo)
  2806. {
  2807. return toDataValueInfo;
  2808. }
  2809. if (toDataValueInfo->IsJsType() || fromDataValueInfo->IsJsType())
  2810. {
  2811. Assert(toDataValueInfo->IsJsType() && fromDataValueInfo->IsJsType());
  2812. return MergeJsTypeValueInfo(toDataValueInfo->AsJsType(), fromDataValueInfo->AsJsType(), isLoopBackEdge, sameValueNumber);
  2813. }
  2814. ValueType newValueType(toDataValueInfo->Type().Merge(fromDataValueInfo->Type()));
  2815. if (newValueType.IsLikelyInt())
  2816. {
  2817. return MergeLikelyIntValueInfo(toDataVal, fromDataVal, newValueType);
  2818. }
  2819. if(newValueType.IsLikelyAnyOptimizedArray())
  2820. {
  2821. if(newValueType.IsLikelyArrayOrObjectWithArray() &&
  2822. toDataValueInfo->IsLikelyArrayOrObjectWithArray() &&
  2823. fromDataValueInfo->IsLikelyArrayOrObjectWithArray())
  2824. {
  2825. // Value type merge for missing values is aggressive by default (for profile data) - if either side likely has no
  2826. // missing values, then the merged value type also likely has no missing values. This is because arrays often start
  2827. // off having missing values but are eventually filled up. In GlobOpt however, we need to be conservative because
  2828. // the existence of a value type that likely has missing values indicates that it is more likely for it to have
  2829. // missing values than not. Also, StElems that are likely to create missing values are tracked in profile data and
  2830. // will update value types to say they are now likely to have missing values, and that needs to be propagated
  2831. // conservatively.
  2832. newValueType =
  2833. newValueType.SetHasNoMissingValues(
  2834. toDataValueInfo->HasNoMissingValues() && fromDataValueInfo->HasNoMissingValues());
  2835. if(toDataValueInfo->HasIntElements() != fromDataValueInfo->HasIntElements() ||
  2836. toDataValueInfo->HasFloatElements() != fromDataValueInfo->HasFloatElements())
  2837. {
  2838. // When merging arrays with different native storage types, make the merged value type a likely version to force
  2839. // array checks to be done again and cause a conversion and/or bailout as necessary
  2840. newValueType = newValueType.ToLikely();
  2841. }
  2842. }
  2843. if(!(newValueType.IsObject() && toDataValueInfo->IsArrayValueInfo() && fromDataValueInfo->IsArrayValueInfo()))
  2844. {
  2845. return ValueInfo::New(alloc, newValueType);
  2846. }
  2847. return
  2848. MergeArrayValueInfo(
  2849. newValueType,
  2850. toDataValueInfo->AsArrayValueInfo(),
  2851. fromDataValueInfo->AsArrayValueInfo(),
  2852. fromDataSym,
  2853. symsRequiringCompensation,
  2854. symsCreatedForMerge);
  2855. }
  2856. // Consider: If both values are VarConstantValueInfo with the same value, we could
  2857. // merge them preserving the value.
  2858. return ValueInfo::New(this->alloc, newValueType);
  2859. }
  2860. ValueInfo *
  2861. GlobOpt::MergeLikelyIntValueInfo(Value *toDataVal, Value *fromDataVal, ValueType const newValueType)
  2862. {
  2863. Assert(newValueType.IsLikelyInt());
  2864. ValueInfo *const toDataValueInfo = toDataVal->GetValueInfo();
  2865. ValueInfo *const fromDataValueInfo = fromDataVal->GetValueInfo();
  2866. Assert(toDataValueInfo != fromDataValueInfo);
  2867. bool wasNegativeZeroPreventedByBailout;
  2868. if(newValueType.IsInt())
  2869. {
  2870. int32 toDataIntConstantValue, fromDataIntConstantValue;
  2871. if (toDataValueInfo->TryGetIntConstantValue(&toDataIntConstantValue) &&
  2872. fromDataValueInfo->TryGetIntConstantValue(&fromDataIntConstantValue) &&
  2873. toDataIntConstantValue == fromDataIntConstantValue)
  2874. {
  2875. // A new value number must be created to register the fact that the value has changed. Otherwise, if the value
  2876. // changed inside a loop, the sym may look invariant on the loop back-edge (and hence not turned into a number
  2877. // value), and its constant value from the first iteration may be incorrectly propagated after the loop.
  2878. return IntConstantValueInfo::New(this->alloc, toDataIntConstantValue);
  2879. }
  2880. wasNegativeZeroPreventedByBailout =
  2881. toDataValueInfo->WasNegativeZeroPreventedByBailout() ||
  2882. fromDataValueInfo->WasNegativeZeroPreventedByBailout();
  2883. }
  2884. else
  2885. {
  2886. wasNegativeZeroPreventedByBailout = false;
  2887. }
  2888. const IntBounds *const toDataValBounds =
  2889. toDataValueInfo->IsIntBounded() ? toDataValueInfo->AsIntBounded()->Bounds() : nullptr;
  2890. const IntBounds *const fromDataValBounds =
  2891. fromDataValueInfo->IsIntBounded() ? fromDataValueInfo->AsIntBounded()->Bounds() : nullptr;
  2892. if(toDataValBounds || fromDataValBounds)
  2893. {
  2894. const IntBounds *mergedBounds;
  2895. if(toDataValBounds && fromDataValBounds)
  2896. {
  2897. mergedBounds = IntBounds::Merge(toDataVal, toDataValBounds, fromDataVal, fromDataValBounds);
  2898. }
  2899. else
  2900. {
  2901. IntConstantBounds constantBounds;
  2902. if(toDataValBounds)
  2903. {
  2904. mergedBounds =
  2905. fromDataValueInfo->TryGetIntConstantBounds(&constantBounds, true)
  2906. ? IntBounds::Merge(toDataVal, toDataValBounds, fromDataVal, constantBounds)
  2907. : nullptr;
  2908. }
  2909. else
  2910. {
  2911. Assert(fromDataValBounds);
  2912. mergedBounds =
  2913. toDataValueInfo->TryGetIntConstantBounds(&constantBounds, true)
  2914. ? IntBounds::Merge(fromDataVal, fromDataValBounds, toDataVal, constantBounds)
  2915. : nullptr;
  2916. }
  2917. }
  2918. if(mergedBounds)
  2919. {
  2920. if(mergedBounds->RequiresIntBoundedValueInfo(newValueType))
  2921. {
  2922. return IntBoundedValueInfo::New(newValueType, mergedBounds, wasNegativeZeroPreventedByBailout, alloc);
  2923. }
  2924. mergedBounds->Delete();
  2925. }
  2926. }
  2927. if(newValueType.IsInt())
  2928. {
  2929. int32 min1, max1, min2, max2;
  2930. toDataValueInfo->GetIntValMinMax(&min1, &max1, false);
  2931. fromDataValueInfo->GetIntValMinMax(&min2, &max2, false);
  2932. return NewIntRangeValueInfo(min(min1, min2), max(max1, max2), wasNegativeZeroPreventedByBailout);
  2933. }
  2934. return ValueInfo::New(alloc, newValueType);
  2935. }
  2936. JsTypeValueInfo* GlobOpt::MergeJsTypeValueInfo(JsTypeValueInfo * toValueInfo, JsTypeValueInfo * fromValueInfo, bool isLoopBackEdge, bool sameValueNumber)
  2937. {
  2938. Assert(toValueInfo != fromValueInfo);
  2939. // On loop back edges we must be conservative and only consider type values which are invariant throughout the loop.
  2940. // That's because in dead store pass we can't correctly track object pointer assignments (o = p), and we may not
  2941. // be able to register correct type checks for the right properties upstream. If we ever figure out how to enhance
  2942. // the dead store pass to track this info we could go more aggressively, as below.
  2943. if (isLoopBackEdge && !sameValueNumber)
  2944. {
  2945. return nullptr;
  2946. }
  2947. const Js::Type* toType = toValueInfo->GetJsType();
  2948. const Js::Type* fromType = fromValueInfo->GetJsType();
  2949. const Js::Type* mergedType = toType == fromType ? toType : nullptr;
  2950. Js::EquivalentTypeSet* toTypeSet = toValueInfo->GetJsTypeSet();
  2951. Js::EquivalentTypeSet* fromTypeSet = fromValueInfo->GetJsTypeSet();
  2952. Js::EquivalentTypeSet* mergedTypeSet = (toTypeSet != nullptr && fromTypeSet != nullptr && AreTypeSetsIdentical(toTypeSet, fromTypeSet)) ? toTypeSet : nullptr;
  2953. #if DBG_DUMP
  2954. if (PHASE_TRACE(Js::ObjTypeSpecPhase, this->func) || PHASE_TRACE(Js::EquivObjTypeSpecPhase, this->func))
  2955. {
  2956. Output::Print(_u("ObjTypeSpec: Merging type value info:\n"));
  2957. Output::Print(_u(" from (shared %d): "), fromValueInfo->GetIsShared());
  2958. fromValueInfo->Dump();
  2959. Output::Print(_u("\n to (shared %d): "), toValueInfo->GetIsShared());
  2960. toValueInfo->Dump();
  2961. }
  2962. #endif
  2963. if (mergedType == toType && mergedTypeSet == toTypeSet)
  2964. {
  2965. #if DBG_DUMP
  2966. if (PHASE_TRACE(Js::ObjTypeSpecPhase, this->func) || PHASE_TRACE(Js::EquivObjTypeSpecPhase, this->func))
  2967. {
  2968. Output::Print(_u("\n result (shared %d): "), toValueInfo->GetIsShared());
  2969. toValueInfo->Dump();
  2970. Output::Print(_u("\n"));
  2971. }
  2972. #endif
  2973. return toValueInfo;
  2974. }
  2975. if (mergedType == nullptr && mergedTypeSet == nullptr)
  2976. {
  2977. // No info, so don't bother making a value.
  2978. return nullptr;
  2979. }
  2980. if (toValueInfo->GetIsShared())
  2981. {
  2982. JsTypeValueInfo* mergedValueInfo = JsTypeValueInfo::New(this->alloc, mergedType, mergedTypeSet);
  2983. #if DBG_DUMP
  2984. if (PHASE_TRACE(Js::ObjTypeSpecPhase, this->func) || PHASE_TRACE(Js::EquivObjTypeSpecPhase, this->func))
  2985. {
  2986. Output::Print(_u("\n result (shared %d): "), mergedValueInfo->GetIsShared());
  2987. mergedValueInfo->Dump();
  2988. Output::Print(_u("\n"));
  2989. }
  2990. #endif
  2991. return mergedValueInfo;
  2992. }
  2993. else
  2994. {
  2995. toValueInfo->SetJsType(mergedType);
  2996. toValueInfo->SetJsTypeSet(mergedTypeSet);
  2997. #if DBG_DUMP
  2998. if (PHASE_TRACE(Js::ObjTypeSpecPhase, this->func) || PHASE_TRACE(Js::EquivObjTypeSpecPhase, this->func))
  2999. {
  3000. Output::Print(_u("\n result (shared %d): "), toValueInfo->GetIsShared());
  3001. toValueInfo->Dump();
  3002. Output::Print(_u("\n"));
  3003. }
  3004. #endif
  3005. return toValueInfo;
  3006. }
  3007. }
  3008. ValueInfo *GlobOpt::MergeArrayValueInfo(
  3009. const ValueType mergedValueType,
  3010. const ArrayValueInfo *const toDataValueInfo,
  3011. const ArrayValueInfo *const fromDataValueInfo,
  3012. Sym *const arraySym,
  3013. BVSparse<JitArenaAllocator> *const symsRequiringCompensation,
  3014. BVSparse<JitArenaAllocator> *const symsCreatedForMerge)
  3015. {
  3016. Assert(mergedValueType.IsAnyOptimizedArray());
  3017. Assert(toDataValueInfo);
  3018. Assert(fromDataValueInfo);
  3019. Assert(toDataValueInfo != fromDataValueInfo);
  3020. Assert(arraySym);
  3021. Assert(!symsRequiringCompensation == IsLoopPrePass());
  3022. Assert(!symsCreatedForMerge == IsLoopPrePass());
  3023. // Merge the segment and segment length syms. If we have the segment and/or the segment length syms available on both sides
  3024. // but in different syms, create a new sym and record that the array sym requires compensation. Compensation will be
  3025. // inserted later to initialize this new sym from all predecessors of the merged block.
  3026. StackSym *newHeadSegmentSym;
  3027. if(toDataValueInfo->HeadSegmentSym() && fromDataValueInfo->HeadSegmentSym())
  3028. {
  3029. if(toDataValueInfo->HeadSegmentSym() == fromDataValueInfo->HeadSegmentSym())
  3030. {
  3031. newHeadSegmentSym = toDataValueInfo->HeadSegmentSym();
  3032. }
  3033. else
  3034. {
  3035. Assert(!IsLoopPrePass());
  3036. Assert(symsRequiringCompensation);
  3037. symsRequiringCompensation->Set(arraySym->m_id);
  3038. Assert(symsCreatedForMerge);
  3039. if(symsCreatedForMerge->Test(toDataValueInfo->HeadSegmentSym()->m_id))
  3040. {
  3041. newHeadSegmentSym = toDataValueInfo->HeadSegmentSym();
  3042. }
  3043. else
  3044. {
  3045. newHeadSegmentSym = StackSym::New(TyMachPtr, func);
  3046. symsCreatedForMerge->Set(newHeadSegmentSym->m_id);
  3047. }
  3048. }
  3049. }
  3050. else
  3051. {
  3052. newHeadSegmentSym = nullptr;
  3053. }
  3054. StackSym *newHeadSegmentLengthSym;
  3055. if(toDataValueInfo->HeadSegmentLengthSym() && fromDataValueInfo->HeadSegmentLengthSym())
  3056. {
  3057. if(toDataValueInfo->HeadSegmentLengthSym() == fromDataValueInfo->HeadSegmentLengthSym())
  3058. {
  3059. newHeadSegmentLengthSym = toDataValueInfo->HeadSegmentLengthSym();
  3060. }
  3061. else
  3062. {
  3063. Assert(!IsLoopPrePass());
  3064. Assert(symsRequiringCompensation);
  3065. symsRequiringCompensation->Set(arraySym->m_id);
  3066. Assert(symsCreatedForMerge);
  3067. if(symsCreatedForMerge->Test(toDataValueInfo->HeadSegmentLengthSym()->m_id))
  3068. {
  3069. newHeadSegmentLengthSym = toDataValueInfo->HeadSegmentLengthSym();
  3070. }
  3071. else
  3072. {
  3073. newHeadSegmentLengthSym = StackSym::New(TyUint32, func);
  3074. symsCreatedForMerge->Set(newHeadSegmentLengthSym->m_id);
  3075. }
  3076. }
  3077. }
  3078. else
  3079. {
  3080. newHeadSegmentLengthSym = nullptr;
  3081. }
  3082. StackSym *newLengthSym;
  3083. if(toDataValueInfo->LengthSym() && fromDataValueInfo->LengthSym())
  3084. {
  3085. if(toDataValueInfo->LengthSym() == fromDataValueInfo->LengthSym())
  3086. {
  3087. newLengthSym = toDataValueInfo->LengthSym();
  3088. }
  3089. else
  3090. {
  3091. Assert(!IsLoopPrePass());
  3092. Assert(symsRequiringCompensation);
  3093. symsRequiringCompensation->Set(arraySym->m_id);
  3094. Assert(symsCreatedForMerge);
  3095. if(symsCreatedForMerge->Test(toDataValueInfo->LengthSym()->m_id))
  3096. {
  3097. newLengthSym = toDataValueInfo->LengthSym();
  3098. }
  3099. else
  3100. {
  3101. newLengthSym = StackSym::New(TyUint32, func);
  3102. symsCreatedForMerge->Set(newLengthSym->m_id);
  3103. }
  3104. }
  3105. }
  3106. else
  3107. {
  3108. newLengthSym = nullptr;
  3109. }
  3110. if(newHeadSegmentSym || newHeadSegmentLengthSym || newLengthSym)
  3111. {
  3112. return ArrayValueInfo::New(alloc, mergedValueType, newHeadSegmentSym, newHeadSegmentLengthSym, newLengthSym);
  3113. }
  3114. if(symsRequiringCompensation)
  3115. {
  3116. symsRequiringCompensation->Clear(arraySym->m_id);
  3117. }
  3118. return ValueInfo::New(alloc, mergedValueType);
  3119. }
  3120. void GlobOpt::InsertValueCompensation(
  3121. BasicBlock *const predecessor,
  3122. const SymToValueInfoMap &symsRequiringCompensationToMergedValueInfoMap)
  3123. {
  3124. Assert(predecessor);
  3125. Assert(symsRequiringCompensationToMergedValueInfoMap.Count() != 0);
  3126. IR::Instr *insertBeforeInstr = predecessor->GetLastInstr();
  3127. Func *const func = insertBeforeInstr->m_func;
  3128. bool setLastInstrInPredecessor;
  3129. if(insertBeforeInstr->IsBranchInstr() || insertBeforeInstr->m_opcode == Js::OpCode::BailTarget)
  3130. {
  3131. // Don't insert code between the branch and the corresponding ByteCodeUses instructions
  3132. while(insertBeforeInstr->m_prev->m_opcode == Js::OpCode::ByteCodeUses)
  3133. {
  3134. insertBeforeInstr = insertBeforeInstr->m_prev;
  3135. }
  3136. setLastInstrInPredecessor = false;
  3137. }
  3138. else
  3139. {
  3140. // Insert at the end of the block and set the last instruction
  3141. Assert(insertBeforeInstr->m_next);
  3142. insertBeforeInstr = insertBeforeInstr->m_next; // Instruction after the last instruction in the predecessor
  3143. setLastInstrInPredecessor = true;
  3144. }
  3145. GlobOptBlockData &predecessorBlockData = predecessor->globOptData;
  3146. GlobHashTable *const predecessorSymToValueMap = predecessor->globOptData.symToValueMap;
  3147. GlobOptBlockData &successorBlockData = blockData;
  3148. GlobHashTable *const successorSymToValueMap = blockData.symToValueMap;
  3149. for(auto it = symsRequiringCompensationToMergedValueInfoMap.GetIterator(); it.IsValid(); it.MoveNext())
  3150. {
  3151. const auto &entry = it.Current();
  3152. Sym *const sym = entry.Key();
  3153. Value *const predecessorValue = FindValue(predecessorSymToValueMap, sym);
  3154. Assert(predecessorValue);
  3155. ValueInfo *const predecessorValueInfo = predecessorValue->GetValueInfo();
  3156. // Currently, array value infos are the only ones that require compensation based on values
  3157. Assert(predecessorValueInfo->IsAnyOptimizedArray());
  3158. const ArrayValueInfo *const predecessorArrayValueInfo = predecessorValueInfo->AsArrayValueInfo();
  3159. StackSym *const predecessorHeadSegmentSym = predecessorArrayValueInfo->HeadSegmentSym();
  3160. StackSym *const predecessorHeadSegmentLengthSym = predecessorArrayValueInfo->HeadSegmentLengthSym();
  3161. StackSym *const predecessorLengthSym = predecessorArrayValueInfo->LengthSym();
  3162. ValueInfo *const mergedValueInfo = entry.Value();
  3163. const ArrayValueInfo *const mergedArrayValueInfo = mergedValueInfo->AsArrayValueInfo();
  3164. StackSym *const mergedHeadSegmentSym = mergedArrayValueInfo->HeadSegmentSym();
  3165. StackSym *const mergedHeadSegmentLengthSym = mergedArrayValueInfo->HeadSegmentLengthSym();
  3166. StackSym *const mergedLengthSym = mergedArrayValueInfo->LengthSym();
  3167. Assert(!mergedHeadSegmentSym || predecessorHeadSegmentSym);
  3168. Assert(!mergedHeadSegmentLengthSym || predecessorHeadSegmentLengthSym);
  3169. Assert(!mergedLengthSym || predecessorLengthSym);
  3170. bool compensated = false;
  3171. if(mergedHeadSegmentSym && predecessorHeadSegmentSym != mergedHeadSegmentSym)
  3172. {
  3173. IR::Instr *const newInstr =
  3174. IR::Instr::New(
  3175. Js::OpCode::Ld_A,
  3176. IR::RegOpnd::New(mergedHeadSegmentSym, mergedHeadSegmentSym->GetType(), func),
  3177. IR::RegOpnd::New(predecessorHeadSegmentSym, predecessorHeadSegmentSym->GetType(), func),
  3178. func);
  3179. newInstr->GetDst()->SetIsJITOptimizedReg(true);
  3180. newInstr->GetSrc1()->SetIsJITOptimizedReg(true);
  3181. newInstr->SetByteCodeOffset(insertBeforeInstr);
  3182. insertBeforeInstr->InsertBefore(newInstr);
  3183. compensated = true;
  3184. }
  3185. if(mergedHeadSegmentLengthSym && predecessorHeadSegmentLengthSym != mergedHeadSegmentLengthSym)
  3186. {
  3187. IR::Instr *const newInstr =
  3188. IR::Instr::New(
  3189. Js::OpCode::Ld_I4,
  3190. IR::RegOpnd::New(mergedHeadSegmentLengthSym, mergedHeadSegmentLengthSym->GetType(), func),
  3191. IR::RegOpnd::New(predecessorHeadSegmentLengthSym, predecessorHeadSegmentLengthSym->GetType(), func),
  3192. func);
  3193. newInstr->GetDst()->SetIsJITOptimizedReg(true);
  3194. newInstr->GetSrc1()->SetIsJITOptimizedReg(true);
  3195. newInstr->SetByteCodeOffset(insertBeforeInstr);
  3196. insertBeforeInstr->InsertBefore(newInstr);
  3197. compensated = true;
  3198. // Merge the head segment length value
  3199. Assert(predecessorBlockData.liveVarSyms->Test(predecessorHeadSegmentLengthSym->m_id));
  3200. predecessorBlockData.liveVarSyms->Set(mergedHeadSegmentLengthSym->m_id);
  3201. successorBlockData.liveVarSyms->Set(mergedHeadSegmentLengthSym->m_id);
  3202. Value *const predecessorHeadSegmentLengthValue =
  3203. FindValue(predecessorSymToValueMap, predecessorHeadSegmentLengthSym);
  3204. Assert(predecessorHeadSegmentLengthValue);
  3205. SetValue(&predecessorBlockData, predecessorHeadSegmentLengthValue, mergedHeadSegmentLengthSym);
  3206. Value *const mergedHeadSegmentLengthValue = FindValue(successorSymToValueMap, mergedHeadSegmentLengthSym);
  3207. if(mergedHeadSegmentLengthValue)
  3208. {
  3209. Assert(mergedHeadSegmentLengthValue->GetValueNumber() != predecessorHeadSegmentLengthValue->GetValueNumber());
  3210. if(predecessorHeadSegmentLengthValue->GetValueInfo() != mergedHeadSegmentLengthValue->GetValueInfo())
  3211. {
  3212. mergedHeadSegmentLengthValue->SetValueInfo(
  3213. MergeLikelyIntValueInfo(
  3214. mergedHeadSegmentLengthValue,
  3215. predecessorHeadSegmentLengthValue,
  3216. mergedHeadSegmentLengthValue->GetValueInfo()->Type()
  3217. .Merge(predecessorHeadSegmentLengthValue->GetValueInfo()->Type())));
  3218. }
  3219. }
  3220. else
  3221. {
  3222. SetValue(&successorBlockData, CopyValue(predecessorHeadSegmentLengthValue), mergedHeadSegmentLengthSym);
  3223. }
  3224. }
  3225. if(mergedLengthSym && predecessorLengthSym != mergedLengthSym)
  3226. {
  3227. IR::Instr *const newInstr =
  3228. IR::Instr::New(
  3229. Js::OpCode::Ld_I4,
  3230. IR::RegOpnd::New(mergedLengthSym, mergedLengthSym->GetType(), func),
  3231. IR::RegOpnd::New(predecessorLengthSym, predecessorLengthSym->GetType(), func),
  3232. func);
  3233. newInstr->GetDst()->SetIsJITOptimizedReg(true);
  3234. newInstr->GetSrc1()->SetIsJITOptimizedReg(true);
  3235. newInstr->SetByteCodeOffset(insertBeforeInstr);
  3236. insertBeforeInstr->InsertBefore(newInstr);
  3237. compensated = true;
  3238. // Merge the length value
  3239. Assert(predecessorBlockData.liveVarSyms->Test(predecessorLengthSym->m_id));
  3240. predecessorBlockData.liveVarSyms->Set(mergedLengthSym->m_id);
  3241. successorBlockData.liveVarSyms->Set(mergedLengthSym->m_id);
  3242. Value *const predecessorLengthValue = FindValue(predecessorSymToValueMap, predecessorLengthSym);
  3243. Assert(predecessorLengthValue);
  3244. SetValue(&predecessorBlockData, predecessorLengthValue, mergedLengthSym);
  3245. Value *const mergedLengthValue = FindValue(successorSymToValueMap, mergedLengthSym);
  3246. if(mergedLengthValue)
  3247. {
  3248. Assert(mergedLengthValue->GetValueNumber() != predecessorLengthValue->GetValueNumber());
  3249. if(predecessorLengthValue->GetValueInfo() != mergedLengthValue->GetValueInfo())
  3250. {
  3251. mergedLengthValue->SetValueInfo(
  3252. MergeLikelyIntValueInfo(
  3253. mergedLengthValue,
  3254. predecessorLengthValue,
  3255. mergedLengthValue->GetValueInfo()->Type().Merge(predecessorLengthValue->GetValueInfo()->Type())));
  3256. }
  3257. }
  3258. else
  3259. {
  3260. SetValue(&successorBlockData, CopyValue(predecessorLengthValue), mergedLengthSym);
  3261. }
  3262. }
  3263. if(compensated)
  3264. {
  3265. ChangeValueInfo(
  3266. predecessor,
  3267. predecessorValue,
  3268. ArrayValueInfo::New(
  3269. alloc,
  3270. predecessorValueInfo->Type(),
  3271. mergedHeadSegmentSym ? mergedHeadSegmentSym : predecessorHeadSegmentSym,
  3272. mergedHeadSegmentLengthSym ? mergedHeadSegmentLengthSym : predecessorHeadSegmentLengthSym,
  3273. mergedLengthSym ? mergedLengthSym : predecessorLengthSym,
  3274. predecessorValueInfo->GetSymStore()),
  3275. false /*allowIncompatibleType*/,
  3276. compensated);
  3277. }
  3278. }
  3279. if(setLastInstrInPredecessor)
  3280. {
  3281. predecessor->SetLastInstr(insertBeforeInstr->m_prev);
  3282. }
  3283. }
  3284. BOOLEAN
  3285. GlobOpt::IsArgumentsSymID(SymID id, const GlobOptBlockData& blockData)
  3286. {
  3287. return blockData.argObjSyms->Test(id);
  3288. }
  3289. BOOLEAN
  3290. GlobOpt::IsArgumentsOpnd(IR::Opnd* opnd)
  3291. {
  3292. SymID id = 0;
  3293. if (opnd->IsRegOpnd())
  3294. {
  3295. id = opnd->AsRegOpnd()->m_sym->m_id;
  3296. return IsArgumentsSymID(id, this->blockData);
  3297. }
  3298. else if (opnd->IsSymOpnd())
  3299. {
  3300. Sym *sym = opnd->AsSymOpnd()->m_sym;
  3301. if (sym && sym->IsPropertySym())
  3302. {
  3303. PropertySym *propertySym = sym->AsPropertySym();
  3304. id = propertySym->m_stackSym->m_id;
  3305. return IsArgumentsSymID(id, this->blockData);
  3306. }
  3307. return false;
  3308. }
  3309. else if (opnd->IsIndirOpnd())
  3310. {
  3311. IR::RegOpnd *indexOpnd = opnd->AsIndirOpnd()->GetIndexOpnd();
  3312. IR::RegOpnd *baseOpnd = opnd->AsIndirOpnd()->GetBaseOpnd();
  3313. return IsArgumentsSymID(baseOpnd->m_sym->m_id, this->blockData) || (indexOpnd && IsArgumentsSymID(indexOpnd->m_sym->m_id, this->blockData));
  3314. }
  3315. AssertMsg(false, "Unknown type");
  3316. return false;
  3317. }
  3318. void
  3319. GlobOpt::TrackArgumentsSym(IR::RegOpnd* opnd)
  3320. {
  3321. if(!blockData.curFunc->argObjSyms)
  3322. {
  3323. blockData.curFunc->argObjSyms = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
  3324. }
  3325. blockData.curFunc->argObjSyms->Set(opnd->m_sym->m_id);
  3326. blockData.argObjSyms->Set(opnd->m_sym->m_id);
  3327. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  3328. if (PHASE_TESTTRACE(Js::StackArgOptPhase, this->func))
  3329. {
  3330. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  3331. char16 debugStringBuffer2[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  3332. Output::Print(_u("Created a new alias s%d for arguments object in function %s(%s) topFunc %s(%s)\n"),
  3333. opnd->m_sym->m_id,
  3334. blockData.curFunc->GetJnFunction()->GetDisplayName(),
  3335. blockData.curFunc->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  3336. this->func->GetJnFunction()->GetDisplayName(),
  3337. this->func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer2)
  3338. );
  3339. Output::Flush();
  3340. }
  3341. #endif
  3342. }
  3343. void
  3344. GlobOpt::ClearArgumentsSym(IR::RegOpnd* opnd)
  3345. {
  3346. // We blindly clear so need to check func has argObjSyms
  3347. if (blockData.curFunc->argObjSyms)
  3348. {
  3349. blockData.curFunc->argObjSyms->Clear(opnd->m_sym->m_id);
  3350. }
  3351. blockData.argObjSyms->Clear(opnd->m_sym->m_id);
  3352. }
  3353. bool
  3354. GlobOpt::AreFromSameBytecodeFunc(IR::RegOpnd* src1, IR::RegOpnd* dst)
  3355. {
  3356. Assert(this->func->m_symTable->FindStackSym(src1->m_sym->m_id) == src1->m_sym);
  3357. Assert(this->func->m_symTable->FindStackSym(dst->m_sym->m_id) == dst->m_sym);
  3358. if (dst->m_sym->HasByteCodeRegSlot() && src1->m_sym->HasByteCodeRegSlot())
  3359. {
  3360. return src1->m_sym->GetByteCodeFunc() == dst->m_sym->GetByteCodeFunc();
  3361. }
  3362. return false;
  3363. }
  3364. BOOLEAN
  3365. GlobOpt::TestAnyArgumentsSym()
  3366. {
  3367. return blockData.argObjSyms->TestEmpty();
  3368. }
  3369. void
  3370. GlobOpt::OptArguments(IR::Instr *instr)
  3371. {
  3372. IR::Opnd* dst = instr->GetDst();
  3373. IR::Opnd* src1 = instr->GetSrc1();
  3374. IR::Opnd* src2 = instr->GetSrc2();
  3375. if (!TrackArgumentsObject())
  3376. {
  3377. return;
  3378. }
  3379. if (instr->m_opcode == Js::OpCode::LdHeapArguments || instr->m_opcode == Js::OpCode::LdLetHeapArguments)
  3380. {
  3381. // Stackargs optimization is designed to work with only when function doesn't have formals.
  3382. if (instr->m_func->GetJnFunction()->GetInParamsCount() != 1)
  3383. {
  3384. #ifdef PERF_HINT
  3385. if (PHASE_TRACE1(Js::PerfHintPhase))
  3386. {
  3387. WritePerfHint(PerfHints::HeapArgumentsDueToFormals, instr->m_func->GetJnFunction(), instr->GetByteCodeOffset());
  3388. }
  3389. #endif
  3390. CannotAllocateArgumentsObjectOnStack();
  3391. }
  3392. TrackArgumentsSym(dst->AsRegOpnd());
  3393. return;
  3394. }
  3395. // Keep track of arguments objects and its aliases
  3396. // LdHeapArguments loads the arguments object and Ld_A tracks the aliases.
  3397. if ((instr->m_opcode == Js::OpCode::Ld_A || instr->m_opcode == Js::OpCode::BytecodeArgOutCapture) && (src1->IsRegOpnd() && IsArgumentsOpnd(src1)))
  3398. {
  3399. // In the debug mode, we don't want to optimize away the aliases. Since we may have to show them on the inspection.
  3400. if (((!AreFromSameBytecodeFunc(src1->AsRegOpnd(), dst->AsRegOpnd()) || this->currentBlock->loop) && instr->m_opcode != Js::OpCode::BytecodeArgOutCapture) || this->func->IsJitInDebugMode())
  3401. {
  3402. CannotAllocateArgumentsObjectOnStack();
  3403. return;
  3404. }
  3405. if(!dst->AsRegOpnd()->GetStackSym()->m_nonEscapingArgObjAlias)
  3406. {
  3407. TrackArgumentsSym(dst->AsRegOpnd());
  3408. }
  3409. return;
  3410. }
  3411. if (!TestAnyArgumentsSym())
  3412. {
  3413. // There are no syms to track yet, don't start tracking arguments sym.
  3414. return;
  3415. }
  3416. // Avoid loop prepass
  3417. if (this->currentBlock->loop && this->IsLoopPrePass())
  3418. {
  3419. return;
  3420. }
  3421. SymID id = 0;
  3422. switch(instr->m_opcode)
  3423. {
  3424. case Js::OpCode::LdElemI_A:
  3425. {
  3426. Assert(src1->IsIndirOpnd());
  3427. IR::RegOpnd *indexOpnd = src1->AsIndirOpnd()->GetIndexOpnd();
  3428. if (indexOpnd && IsArgumentsSymID(indexOpnd->m_sym->m_id, this->blockData))
  3429. {
  3430. // Pathological test cases such as a[arguments]
  3431. CannotAllocateArgumentsObjectOnStack();
  3432. return;
  3433. }
  3434. IR::RegOpnd *baseOpnd = src1->AsIndirOpnd()->GetBaseOpnd();
  3435. id = baseOpnd->m_sym->m_id;
  3436. if (IsArgumentsSymID(id, this->blockData))
  3437. {
  3438. instr->usesStackArgumentsObject = true;
  3439. }
  3440. break;
  3441. }
  3442. case Js::OpCode::LdLen_A:
  3443. {
  3444. Assert(src1->IsRegOpnd());
  3445. if(IsArgumentsOpnd(src1))
  3446. {
  3447. instr->usesStackArgumentsObject = true;
  3448. }
  3449. break;
  3450. }
  3451. case Js::OpCode::ArgOut_A_InlineBuiltIn:
  3452. {
  3453. if (IsArgumentsOpnd(src1) &&
  3454. src1->AsRegOpnd()->m_sym->GetInstrDef()->m_opcode == Js::OpCode::BytecodeArgOutCapture)
  3455. {
  3456. // Apply inlining results in such usage - this is to ignore this sym that is def'd by ByteCodeArgOutCapture
  3457. // It's needed because we do not have block level merging of arguments object and this def due to inlining can turn off stack args opt.
  3458. IR::Instr* builtinStart = instr->GetNextRealInstr();
  3459. if (builtinStart->m_opcode == Js::OpCode::InlineBuiltInStart)
  3460. {
  3461. IR::Opnd* builtinOpnd = builtinStart->GetSrc1();
  3462. if (builtinStart->GetSrc1()->IsAddrOpnd())
  3463. {
  3464. Assert(builtinOpnd->AsAddrOpnd()->m_isFunction);
  3465. Js::BuiltinFunction builtinFunction = Js::JavascriptLibrary::GetBuiltInForFuncInfo(((Js::JavascriptFunction*)builtinOpnd->AsAddrOpnd()->m_address)->GetFunctionInfo(), func->GetScriptContext());
  3466. if (builtinFunction == Js::BuiltinFunction::Function_Apply)
  3467. {
  3468. ClearArgumentsSym(src1->AsRegOpnd());
  3469. }
  3470. }
  3471. else if (builtinOpnd->IsRegOpnd())
  3472. {
  3473. if (builtinOpnd->AsRegOpnd()->m_sym->m_builtInIndex == Js::BuiltinFunction::Function_Apply)
  3474. {
  3475. ClearArgumentsSym(src1->AsRegOpnd());
  3476. }
  3477. }
  3478. }
  3479. }
  3480. break;
  3481. }
  3482. case Js::OpCode::BailOnNotStackArgs:
  3483. case Js::OpCode::ArgOut_A_FromStackArgs:
  3484. case Js::OpCode::LdArgumentsFromStack:
  3485. case Js::OpCode::BytecodeArgOutUse:
  3486. break;
  3487. default:
  3488. {
  3489. // Super conservative here, if we see the arguments or any of its alias being used in any
  3490. // other opcode just don't do this optimization. Revisit this to optimize further if we see any common
  3491. // case is missed.
  3492. if (src1)
  3493. {
  3494. if (src1->IsRegOpnd() || src1->IsSymOpnd() || src1->IsIndirOpnd())
  3495. {
  3496. if (IsArgumentsOpnd(src1))
  3497. {
  3498. #ifdef PERF_HINT
  3499. if (PHASE_TRACE1(Js::PerfHintPhase))
  3500. {
  3501. WritePerfHint(PerfHints::HeapArgumentsCreated, instr->m_func->GetJnFunction(), instr->GetByteCodeOffset());
  3502. }
  3503. #endif
  3504. CannotAllocateArgumentsObjectOnStack();
  3505. return;
  3506. }
  3507. }
  3508. }
  3509. if (src2)
  3510. {
  3511. if (src2->IsRegOpnd() || src2->IsSymOpnd() || src2->IsIndirOpnd())
  3512. {
  3513. if (IsArgumentsOpnd(src2))
  3514. {
  3515. #ifdef PERF_HINT
  3516. if (PHASE_TRACE1(Js::PerfHintPhase))
  3517. {
  3518. WritePerfHint(PerfHints::HeapArgumentsCreated, instr->m_func->GetJnFunction(), instr->GetByteCodeOffset());
  3519. }
  3520. #endif
  3521. CannotAllocateArgumentsObjectOnStack();
  3522. return;
  3523. }
  3524. }
  3525. }
  3526. // We should look at dst last to correctly handle cases where it's the same as one of the src operands.
  3527. if (dst)
  3528. {
  3529. if (dst->IsIndirOpnd() || dst->IsSymOpnd())
  3530. {
  3531. if (IsArgumentsOpnd(dst))
  3532. {
  3533. #ifdef PERF_HINT
  3534. if (PHASE_TRACE1(Js::PerfHintPhase))
  3535. {
  3536. WritePerfHint(PerfHints::HeapArgumentsModification, instr->m_func->GetJnFunction(), instr->GetByteCodeOffset());
  3537. }
  3538. #endif
  3539. CannotAllocateArgumentsObjectOnStack();
  3540. return;
  3541. }
  3542. }
  3543. else if (dst->IsRegOpnd())
  3544. {
  3545. if (this->currentBlock->loop && IsArgumentsOpnd(dst))
  3546. {
  3547. #ifdef PERF_HINT
  3548. if (PHASE_TRACE1(Js::PerfHintPhase))
  3549. {
  3550. WritePerfHint(PerfHints::HeapArgumentsModification, instr->m_func->GetJnFunction(), instr->GetByteCodeOffset());
  3551. }
  3552. #endif
  3553. CannotAllocateArgumentsObjectOnStack();
  3554. return;
  3555. }
  3556. ClearArgumentsSym(dst->AsRegOpnd());
  3557. }
  3558. }
  3559. }
  3560. break;
  3561. }
  3562. return;
  3563. }
  3564. void
  3565. GlobOpt::MarkArgumentsUsedForBranch(IR::Instr * instr)
  3566. {
  3567. // If it's a conditional branch instruction and the operand used for branching is one of the arguments
  3568. // to the function, tag the m_argUsedForBranch of the functionBody so that it can be used later for inlining decisions.
  3569. if (instr->IsBranchInstr() && !instr->AsBranchInstr()->IsUnconditional())
  3570. {
  3571. IR::BranchInstr * bInstr = instr->AsBranchInstr();
  3572. IR::Opnd *src2 = bInstr->GetSrc2();
  3573. if (((!src2 && (instr->m_opcode == Js::OpCode::BrFalse_A || instr->m_opcode == Js::OpCode::BrTrue_A))
  3574. || (src2 && src2->IsConstOpnd()))
  3575. && bInstr->GetSrc1()->IsRegOpnd())
  3576. {
  3577. IR::RegOpnd *src1 = bInstr->GetSrc1()->AsRegOpnd();
  3578. if (src1 && src1->m_sym->IsSingleDef())
  3579. {
  3580. IR::Instr * defInst = src1->m_sym->GetInstrDef();
  3581. IR::Opnd *defSym = defInst->GetSrc1();
  3582. if (defSym && defSym->IsSymOpnd() && defSym->AsSymOpnd()->m_sym->IsStackSym()
  3583. && defSym->AsSymOpnd()->m_sym->AsStackSym()->IsParamSlotSym())
  3584. {
  3585. Js::FunctionBody *funcBody = this->func->m_workItem->GetFunctionBody();
  3586. uint16 param = defSym->AsSymOpnd()->m_sym->AsStackSym()->GetParamSlotNum();
  3587. // We only support functions with 13 arguments to ensure optimal size of callSiteInfo
  3588. if (param < Js::Constants::MaximumArgumentCountForConstantArgumentInlining)
  3589. {
  3590. funcBody->m_argUsedForBranch = funcBody->m_argUsedForBranch | (1 << (param - 1));
  3591. }
  3592. }
  3593. }
  3594. }
  3595. }
  3596. }
  3597. const InductionVariable*
  3598. GlobOpt::GetInductionVariable(SymID sym, Loop *loop)
  3599. {
  3600. if (loop->inductionVariables)
  3601. {
  3602. for (auto it = loop->inductionVariables->GetIterator(); it.IsValid(); it.MoveNext())
  3603. {
  3604. InductionVariable* iv = &it.CurrentValueReference();
  3605. if (!iv->IsChangeDeterminate() || !iv->IsChangeUnidirectional())
  3606. {
  3607. continue;
  3608. }
  3609. if (iv->Sym()->m_id == sym)
  3610. {
  3611. return iv;
  3612. }
  3613. }
  3614. }
  3615. return nullptr;
  3616. }
  3617. bool
  3618. GlobOpt::IsSymIDInductionVariable(SymID sym, Loop *loop)
  3619. {
  3620. return GetInductionVariable(sym, loop) != nullptr;
  3621. }
  3622. SymID
  3623. GlobOpt::GetVarSymID(StackSym *sym)
  3624. {
  3625. if (sym && sym->m_type != TyVar)
  3626. {
  3627. sym = sym->GetVarEquivSym(nullptr);
  3628. }
  3629. if (!sym)
  3630. {
  3631. return Js::Constants::InvalidSymID;
  3632. }
  3633. return sym->m_id;
  3634. }
  3635. bool
  3636. GlobOpt::IsAllowedForMemOpt(IR::Instr* instr, bool isMemset, IR::RegOpnd *baseOpnd, IR::Opnd *indexOpnd)
  3637. {
  3638. Assert(instr);
  3639. if (!baseOpnd || !indexOpnd)
  3640. {
  3641. return false;
  3642. }
  3643. Loop* loop = this->currentBlock->loop;
  3644. const ValueType baseValueType(baseOpnd->GetValueType());
  3645. const ValueType indexValueType(indexOpnd->GetValueType());
  3646. // Validate the array and index types
  3647. if (
  3648. !indexValueType.IsInt() ||
  3649. !(
  3650. baseValueType.IsTypedIntOrFloatArray() ||
  3651. baseValueType.IsArray()
  3652. )
  3653. )
  3654. {
  3655. #if DBG_DUMP
  3656. wchar indexValueTypeStr[VALUE_TYPE_MAX_STRING_SIZE];
  3657. indexValueType.ToString(indexValueTypeStr);
  3658. wchar baseValueTypeStr[VALUE_TYPE_MAX_STRING_SIZE];
  3659. baseValueType.ToString(baseValueTypeStr);
  3660. TRACE_MEMOP_VERBOSE(loop, instr, _u("Index[%s] or Array[%s] value type is invalid"), indexValueTypeStr, baseValueTypeStr);
  3661. #endif
  3662. return false;
  3663. }
  3664. // The following is conservative and works around a bug in induction variable analysis.
  3665. if (baseOpnd->IsArrayRegOpnd())
  3666. {
  3667. IR::ArrayRegOpnd *baseArrayOp = baseOpnd->AsArrayRegOpnd();
  3668. bool hasBoundChecksRemoved = (
  3669. baseArrayOp->EliminatedLowerBoundCheck() &&
  3670. baseArrayOp->EliminatedUpperBoundCheck() &&
  3671. !instr->extractedUpperBoundCheckWithoutHoisting &&
  3672. !instr->loadedArrayHeadSegment &&
  3673. !instr->loadedArrayHeadSegmentLength
  3674. );
  3675. if (!hasBoundChecksRemoved)
  3676. {
  3677. TRACE_MEMOP_VERBOSE(loop, instr, L"Missing bounds check optimization");
  3678. return false;
  3679. }
  3680. }
  3681. if (!baseValueType.IsTypedArray())
  3682. {
  3683. // Check if the instr can kill the value type of the array
  3684. JsArrayKills arrayKills = CheckJsArrayKills(instr);
  3685. if (arrayKills.KillsValueType(baseValueType))
  3686. {
  3687. TRACE_MEMOP_VERBOSE(loop, instr, _u("The array (s%d) can lose its value type"), GetVarSymID(baseOpnd->GetStackSym()));
  3688. return false;
  3689. }
  3690. }
  3691. // Process the Index Operand
  3692. if (!this->OptIsInvariant(baseOpnd, this->currentBlock, loop, this->FindValue(baseOpnd->m_sym), false, true))
  3693. {
  3694. TRACE_MEMOP_VERBOSE(loop, instr, _u("Base (s%d) is not invariant"), GetVarSymID(baseOpnd->GetStackSym()));
  3695. return false;
  3696. }
  3697. // Validate the index
  3698. Assert(indexOpnd->GetStackSym());
  3699. SymID indexSymID = GetVarSymID(indexOpnd->GetStackSym());
  3700. const InductionVariable* iv = GetInductionVariable(indexSymID, loop);
  3701. if (!iv)
  3702. {
  3703. // If the index is not an induction variable return
  3704. TRACE_MEMOP_VERBOSE(loop, instr, _u("Index (s%d) is not an induction variable"), indexSymID);
  3705. return false;
  3706. }
  3707. Assert(iv->IsChangeDeterminate() && iv->IsChangeUnidirectional());
  3708. const IntConstantBounds & bounds = iv->ChangeBounds();
  3709. // Only accept induction variables that increments by 1
  3710. Loop::InductionVariableChangeInfo inductionVariableChangeInfo = { 0, 0 };
  3711. inductionVariableChangeInfo = loop->memOpInfo->inductionVariableChangeInfoMap->Lookup(indexSymID, inductionVariableChangeInfo);
  3712. if (
  3713. (bounds.LowerBound() != 1 && bounds.LowerBound() != -1) ||
  3714. (bounds.UpperBound() != bounds.LowerBound()) ||
  3715. inductionVariableChangeInfo.unroll > 1 // Must be 0 (not seen yet) or 1 (already seen)
  3716. )
  3717. {
  3718. TRACE_MEMOP_VERBOSE(loop, instr, _u("The index does not change by 1: %d><%d, unroll=%d"), bounds.LowerBound(), bounds.UpperBound(), inductionVariableChangeInfo.unroll);
  3719. return false;
  3720. }
  3721. // Check if the index is the same in all MemOp optimization in this loop
  3722. if (!loop->memOpInfo->candidates->Empty())
  3723. {
  3724. Loop::MemOpCandidate* previousCandidate = loop->memOpInfo->candidates->Head();
  3725. // All MemOp operations within the same loop must use the same index
  3726. if (previousCandidate->index != indexSymID)
  3727. {
  3728. TRACE_MEMOP_VERBOSE(loop, instr, _u("The index is not the same as other MemOp in the loop"));
  3729. return false;
  3730. }
  3731. }
  3732. return true;
  3733. }
  3734. bool
  3735. GlobOpt::CollectMemcopyLdElementI(IR::Instr *instr, Loop *loop)
  3736. {
  3737. Assert(instr->GetSrc1()->IsIndirOpnd());
  3738. IR::IndirOpnd *src1 = instr->GetSrc1()->AsIndirOpnd();
  3739. IR::Opnd *indexOpnd = src1->GetIndexOpnd();
  3740. IR::RegOpnd *baseOpnd = src1->GetBaseOpnd()->AsRegOpnd();
  3741. SymID baseSymID = GetVarSymID(baseOpnd->GetStackSym());
  3742. if (!IsAllowedForMemOpt(instr, false, baseOpnd, indexOpnd))
  3743. {
  3744. return false;
  3745. }
  3746. SymID inductionSymID = GetVarSymID(indexOpnd->GetStackSym());
  3747. Assert(IsSymIDInductionVariable(inductionSymID, loop));
  3748. bool isIndexPreIncr = loop->memOpInfo->inductionVariableChangeInfoMap->ContainsKey(inductionSymID);
  3749. IR::Opnd * dst = instr->GetDst();
  3750. if (!dst->IsRegOpnd() || !dst->AsRegOpnd()->GetStackSym()->IsSingleDef())
  3751. {
  3752. return false;
  3753. }
  3754. Loop::MemCopyCandidate* memcopyInfo = memcopyInfo = JitAnewStruct(this->func->GetTopFunc()->m_fg->alloc, Loop::MemCopyCandidate);
  3755. memcopyInfo->ldBase = baseSymID;
  3756. memcopyInfo->ldCount = 1;
  3757. memcopyInfo->count = 0;
  3758. memcopyInfo->bIndexAlreadyChanged = isIndexPreIncr;
  3759. memcopyInfo->base = Js::Constants::InvalidSymID; //need to find the stElem first
  3760. memcopyInfo->index = inductionSymID;
  3761. memcopyInfo->transferSym = dst->AsRegOpnd()->GetStackSym();
  3762. loop->memOpInfo->candidates->Prepend(memcopyInfo);
  3763. return true;
  3764. }
  3765. bool
  3766. GlobOpt::CollectMemsetStElementI(IR::Instr *instr, Loop *loop)
  3767. {
  3768. Assert(instr->GetDst()->IsIndirOpnd());
  3769. IR::IndirOpnd *dst = instr->GetDst()->AsIndirOpnd();
  3770. IR::Opnd *indexOp = dst->GetIndexOpnd();
  3771. IR::RegOpnd *baseOp = dst->GetBaseOpnd()->AsRegOpnd();
  3772. if (!IsAllowedForMemOpt(instr, true, baseOp, indexOp))
  3773. {
  3774. return false;
  3775. }
  3776. SymID baseSymID = GetVarSymID(baseOp->GetStackSym());
  3777. IR::Opnd *srcDef = instr->GetSrc1();
  3778. StackSym *srcSym = nullptr;
  3779. if (srcDef->IsRegOpnd())
  3780. {
  3781. IR::RegOpnd* opnd = srcDef->AsRegOpnd();
  3782. if (this->OptIsInvariant(opnd, this->currentBlock, loop, this->FindValue(opnd->m_sym), true, true))
  3783. {
  3784. srcSym = opnd->GetStackSym();
  3785. }
  3786. }
  3787. BailoutConstantValue constant = {TyIllegal, 0};
  3788. if (srcDef->IsFloatConstOpnd())
  3789. {
  3790. constant.InitFloatConstValue(srcDef->AsFloatConstOpnd()->m_value);
  3791. }
  3792. else if (srcDef->IsIntConstOpnd())
  3793. {
  3794. constant.InitIntConstValue(srcDef->AsIntConstOpnd()->GetValue(), srcDef->AsIntConstOpnd()->GetType());
  3795. }
  3796. else if (srcDef->IsAddrOpnd())
  3797. {
  3798. constant.InitVarConstValue(srcDef->AsAddrOpnd()->m_address);
  3799. }
  3800. else if(!srcSym)
  3801. {
  3802. TRACE_MEMOP_PHASE_VERBOSE(MemSet, loop, instr, _u("Source is not an invariant"));
  3803. return false;
  3804. }
  3805. // Process the Index Operand
  3806. Assert(indexOp->GetStackSym());
  3807. SymID inductionSymID = GetVarSymID(indexOp->GetStackSym());
  3808. Assert(IsSymIDInductionVariable(inductionSymID, loop));
  3809. bool isIndexPreIncr = loop->memOpInfo->inductionVariableChangeInfoMap->ContainsKey(inductionSymID);
  3810. Loop::MemSetCandidate* memsetInfo = JitAnewStruct(this->func->GetTopFunc()->m_fg->alloc, Loop::MemSetCandidate);
  3811. memsetInfo->base = baseSymID;
  3812. memsetInfo->index = inductionSymID;
  3813. memsetInfo->constant = constant;
  3814. memsetInfo->srcSym = srcSym;
  3815. memsetInfo->count = 1;
  3816. memsetInfo->bIndexAlreadyChanged = isIndexPreIncr;
  3817. loop->memOpInfo->candidates->Prepend(memsetInfo);
  3818. return true;
  3819. }
  3820. bool GlobOpt::CollectMemcopyStElementI(IR::Instr *instr, Loop *loop)
  3821. {
  3822. Assert(instr->GetDst()->IsIndirOpnd());
  3823. IR::IndirOpnd *dst = instr->GetDst()->AsIndirOpnd();
  3824. IR::Opnd *indexOp = dst->GetIndexOpnd();
  3825. IR::RegOpnd *baseOp = dst->GetBaseOpnd()->AsRegOpnd();
  3826. SymID baseSymID = GetVarSymID(baseOp->GetStackSym());
  3827. if (!instr->GetSrc1()->IsRegOpnd())
  3828. {
  3829. return false;
  3830. }
  3831. IR::RegOpnd* src1 = instr->GetSrc1()->AsRegOpnd();
  3832. if (!src1->GetIsDead())
  3833. {
  3834. // This must be the last use of the register.
  3835. // It will invalidate `var m = a[i]; b[i] = m;` but this is not a very interesting case.
  3836. TRACE_MEMOP_PHASE_VERBOSE(MemCopy, loop, instr, _u("Source (s%d) is still alive after StElemI"), baseSymID);
  3837. return false;
  3838. }
  3839. if (!IsAllowedForMemOpt(instr, false, baseOp, indexOp))
  3840. {
  3841. return false;
  3842. }
  3843. SymID srcSymID = GetVarSymID(src1->GetStackSym());
  3844. // Prepare the memcopyCandidate entry
  3845. if (loop->memOpInfo->candidates->Empty())
  3846. {
  3847. // There is no ldElem matching this stElem
  3848. return false;
  3849. }
  3850. Loop::MemOpCandidate* previousCandidate = loop->memOpInfo->candidates->Head();
  3851. if (!previousCandidate->IsMemCopy())
  3852. {
  3853. return false;
  3854. }
  3855. Loop::MemCopyCandidate* memcopyInfo = previousCandidate->AsMemCopy();
  3856. // The previous candidate has to have been created by the matching ldElem
  3857. if (
  3858. memcopyInfo->base != Js::Constants::InvalidSymID ||
  3859. GetVarSymID(memcopyInfo->transferSym) != srcSymID
  3860. )
  3861. {
  3862. TRACE_MEMOP_PHASE_VERBOSE(MemCopy, loop, instr, _u("No matching LdElem found (s%d)"), baseSymID);
  3863. return false;
  3864. }
  3865. Assert(indexOp->GetStackSym());
  3866. SymID inductionSymID = GetVarSymID(indexOp->GetStackSym());
  3867. Assert(IsSymIDInductionVariable(inductionSymID, loop));
  3868. bool isIndexPreIncr = loop->memOpInfo->inductionVariableChangeInfoMap->ContainsKey(inductionSymID);
  3869. if (isIndexPreIncr != memcopyInfo->bIndexAlreadyChanged)
  3870. {
  3871. // The index changed between the load and the store
  3872. TRACE_MEMOP_PHASE_VERBOSE(MemCopy, loop, instr, _u("Index value changed between ldElem and stElem"));
  3873. return false;
  3874. }
  3875. // Consider: Can we remove the count field?
  3876. memcopyInfo->count++;
  3877. memcopyInfo->base = baseSymID;
  3878. return true;
  3879. }
  3880. bool
  3881. GlobOpt::CollectMemOpLdElementI(IR::Instr *instr, Loop *loop)
  3882. {
  3883. Assert(instr->m_opcode == Js::OpCode::LdElemI_A);
  3884. return (!PHASE_OFF(Js::MemCopyPhase, this->func) && CollectMemcopyLdElementI(instr, loop));
  3885. }
  3886. bool
  3887. GlobOpt::CollectMemOpStElementI(IR::Instr *instr, Loop *loop)
  3888. {
  3889. Assert(instr->m_opcode == Js::OpCode::StElemI_A || instr->m_opcode == Js::OpCode::StElemI_A_Strict);
  3890. Assert(instr->GetSrc1());
  3891. return (!PHASE_OFF(Js::MemSetPhase, this->func) && CollectMemsetStElementI(instr, loop)) ||
  3892. (!PHASE_OFF(Js::MemCopyPhase, this->func) && CollectMemcopyStElementI(instr, loop));
  3893. }
  3894. bool
  3895. GlobOpt::CollectMemOpInfo(IR::Instr *instr, Value *src1Val, Value *src2Val)
  3896. {
  3897. Assert(this->currentBlock->loop);
  3898. Loop *loop = this->currentBlock->loop;
  3899. if (!loop->blockList.HasTwo())
  3900. {
  3901. // We support memcopy and memset for loops which have only two blocks.
  3902. return false;
  3903. }
  3904. if (!loop->EnsureMemOpVariablesInitialized())
  3905. {
  3906. return false;
  3907. }
  3908. Assert(loop->memOpInfo->doMemOp);
  3909. bool isIncr = true, isChangedByOne = false;
  3910. switch (instr->m_opcode)
  3911. {
  3912. case Js::OpCode::StElemI_A:
  3913. case Js::OpCode::StElemI_A_Strict:
  3914. if (!CollectMemOpStElementI(instr, loop))
  3915. {
  3916. loop->memOpInfo->doMemOp = false;
  3917. return false;
  3918. }
  3919. break;
  3920. case Js::OpCode::LdElemI_A:
  3921. if (!CollectMemOpLdElementI(instr, loop))
  3922. {
  3923. loop->memOpInfo->doMemOp = false;
  3924. return false;
  3925. }
  3926. break;
  3927. case Js::OpCode::Decr_A:
  3928. isIncr = false;
  3929. case Js::OpCode::Incr_A:
  3930. isChangedByOne = true;
  3931. goto MemOpCheckInductionVariable;
  3932. case Js::OpCode::Sub_I4:
  3933. case Js::OpCode::Sub_A:
  3934. isIncr = false;
  3935. case Js::OpCode::Add_A:
  3936. case Js::OpCode::Add_I4:
  3937. {
  3938. MemOpCheckInductionVariable:
  3939. StackSym *sym = instr->GetSrc1()->GetStackSym();
  3940. if (!sym)
  3941. {
  3942. sym = instr->GetSrc2()->GetStackSym();
  3943. }
  3944. SymID inductionSymID = GetVarSymID(sym);
  3945. if (IsSymIDInductionVariable(inductionSymID, this->currentBlock->loop))
  3946. {
  3947. if (!isChangedByOne)
  3948. {
  3949. IR::Opnd *src1, *src2;
  3950. src1 = instr->GetSrc1();
  3951. src2 = instr->GetSrc2();
  3952. if (src2->IsRegOpnd())
  3953. {
  3954. Value *val = this->FindValue(src2->AsRegOpnd()->m_sym);
  3955. if (val)
  3956. {
  3957. ValueInfo *vi = val->GetValueInfo();
  3958. int constValue;
  3959. if (vi && vi->TryGetIntConstantValue(&constValue))
  3960. {
  3961. if (constValue == 1)
  3962. {
  3963. isChangedByOne = true;
  3964. }
  3965. }
  3966. }
  3967. }
  3968. else if (src2->IsIntConstOpnd())
  3969. {
  3970. if (src2->AsIntConstOpnd()->GetValue() == 1)
  3971. {
  3972. isChangedByOne = true;
  3973. }
  3974. }
  3975. }
  3976. if (!isChangedByOne)
  3977. {
  3978. Loop::InductionVariableChangeInfo inductionVariableChangeInfo = { Js::Constants::InvalidLoopUnrollFactor, 0 };
  3979. if (!loop->memOpInfo->inductionVariableChangeInfoMap->ContainsKey(inductionSymID))
  3980. {
  3981. loop->memOpInfo->inductionVariableChangeInfoMap->Add(inductionSymID, inductionVariableChangeInfo);
  3982. }
  3983. else
  3984. {
  3985. loop->memOpInfo->inductionVariableChangeInfoMap->Item(inductionSymID, inductionVariableChangeInfo);
  3986. }
  3987. }
  3988. else
  3989. {
  3990. if (!loop->memOpInfo->inductionVariableChangeInfoMap->ContainsKey(inductionSymID))
  3991. {
  3992. Loop::InductionVariableChangeInfo inductionVariableChangeInfo = { 1, isIncr };
  3993. loop->memOpInfo->inductionVariableChangeInfoMap->Add(inductionSymID, inductionVariableChangeInfo);
  3994. }
  3995. else
  3996. {
  3997. Loop::InductionVariableChangeInfo inductionVariableChangeInfo = { 0, 0 };
  3998. inductionVariableChangeInfo = loop->memOpInfo->inductionVariableChangeInfoMap->Lookup(inductionSymID, inductionVariableChangeInfo);
  3999. inductionVariableChangeInfo.unroll++;
  4000. inductionVariableChangeInfo.isIncremental = isIncr;
  4001. loop->memOpInfo->inductionVariableChangeInfoMap->Item(inductionSymID, inductionVariableChangeInfo);
  4002. }
  4003. }
  4004. break;
  4005. }
  4006. // Fallthrough if not an induction variable
  4007. }
  4008. default:
  4009. // Check prev instr because it could have been added by an optimization and we won't see it here.
  4010. if (OpCodeAttr::FastFldInstr(instr->m_opcode) || (instr->m_prev && OpCodeAttr::FastFldInstr(instr->m_prev->m_opcode)))
  4011. {
  4012. // Refuse any operations interacting with Fields
  4013. loop->memOpInfo->doMemOp = false;
  4014. TRACE_MEMOP_VERBOSE(loop, instr, _u("Field interaction detected"));
  4015. return false;
  4016. }
  4017. if (Js::OpCodeUtil::GetOpCodeLayout(instr->m_opcode) == Js::OpLayoutType::ElementSlot)
  4018. {
  4019. // Refuse any operations interacting with slots
  4020. loop->memOpInfo->doMemOp = false;
  4021. TRACE_MEMOP_VERBOSE(loop, instr, _u("Slot interaction detected"));
  4022. return false;
  4023. }
  4024. if (this->MayNeedBailOnImplicitCall(instr, src1Val, src2Val))
  4025. {
  4026. loop->memOpInfo->doMemOp = false;
  4027. TRACE_MEMOP_VERBOSE(loop, instr, _u("Implicit call bailout detected"));
  4028. return false;
  4029. }
  4030. // Make sure this instruction doesn't use the memcopy transfer sym before it is checked by StElemI
  4031. if (!loop->memOpInfo->candidates->Empty())
  4032. {
  4033. Loop::MemOpCandidate* prevCandidate = loop->memOpInfo->candidates->Head();
  4034. if (prevCandidate->IsMemCopy())
  4035. {
  4036. Loop::MemCopyCandidate* memcopyCandidate = prevCandidate->AsMemCopy();
  4037. if (memcopyCandidate->base == Js::Constants::InvalidSymID)
  4038. {
  4039. if (instr->FindRegUse(memcopyCandidate->transferSym))
  4040. {
  4041. loop->memOpInfo->doMemOp = false;
  4042. TRACE_MEMOP_PHASE_VERBOSE(MemCopy, loop, instr, _u("Found illegal use of LdElemI value(s%d)"), GetVarSymID(memcopyCandidate->transferSym));
  4043. return false;
  4044. }
  4045. }
  4046. }
  4047. }
  4048. }
  4049. return true;
  4050. }
  4051. IR::Instr *
  4052. GlobOpt::OptInstr(IR::Instr *&instr, bool* isInstrRemoved)
  4053. {
  4054. Assert(instr->m_func->IsTopFunc() || instr->m_func->isGetterSetter || instr->m_func->callSiteIdInParentFunc != UINT16_MAX);
  4055. IR::Opnd *src1, *src2;
  4056. Value *src1Val = nullptr, *src2Val = nullptr, *dstVal = nullptr;
  4057. Value *src1IndirIndexVal = nullptr, *dstIndirIndexVal = nullptr;
  4058. IR::Instr *instrPrev = instr->m_prev;
  4059. IR::Instr *instrNext = instr->m_next;
  4060. if (instr->IsLabelInstr() && this->func->HasTry() && this->func->DoOptimizeTryCatch())
  4061. {
  4062. this->currentRegion = instr->AsLabelInstr()->GetRegion();
  4063. Assert(this->currentRegion);
  4064. }
  4065. if(PrepareForIgnoringIntOverflow(instr))
  4066. {
  4067. if(!IsLoopPrePass())
  4068. {
  4069. *isInstrRemoved = true;
  4070. currentBlock->RemoveInstr(instr);
  4071. }
  4072. return instrNext;
  4073. }
  4074. if (!instr->IsRealInstr() || instr->IsByteCodeUsesInstr() || instr->m_opcode == Js::OpCode::Conv_Bool)
  4075. {
  4076. return instrNext;
  4077. }
  4078. if (instr->m_opcode == Js::OpCode::Yield)
  4079. {
  4080. // TODO[generators][ianhall]: Can this and the FillBailOutInfo call below be moved to after Src1 and Src2 so that Yield can be optimized right up to the actual yield?
  4081. this->KillStateForGeneratorYield();
  4082. }
  4083. // Consider: Do we ever get post-op bailout here, and if so is the FillBailOutInfo call in the right place?
  4084. if (instr->HasBailOutInfo() && !this->IsLoopPrePass())
  4085. {
  4086. this->FillBailOutInfo(this->currentBlock, instr->GetBailOutInfo());
  4087. }
  4088. this->instrCountSinceLastCleanUp++;
  4089. instr = this->PreOptPeep(instr);
  4090. this->OptArguments(instr);
  4091. #if DBG
  4092. PropertySym *propertySymUseBefore = nullptr;
  4093. Assert(this->byteCodeUses == nullptr);
  4094. this->byteCodeUsesBeforeOpt->ClearAll();
  4095. GlobOpt::TrackByteCodeSymUsed(instr, this->byteCodeUsesBeforeOpt, &propertySymUseBefore);
  4096. Assert(noImplicitCallUsesToInsert->Count() == 0);
  4097. #endif
  4098. this->ignoredIntOverflowForCurrentInstr = false;
  4099. this->ignoredNegativeZeroForCurrentInstr = false;
  4100. src1 = instr->GetSrc1();
  4101. src2 = instr->GetSrc2();
  4102. if (src1)
  4103. {
  4104. src1Val = this->OptSrc(src1, &instr, &src1IndirIndexVal);
  4105. instr = this->SetTypeCheckBailOut(instr->GetSrc1(), instr, nullptr);
  4106. if (src2)
  4107. {
  4108. src2Val = this->OptSrc(src2, &instr);
  4109. }
  4110. }
  4111. if(instr->GetDst() && instr->GetDst()->IsIndirOpnd())
  4112. {
  4113. this->OptSrc(instr->GetDst(), &instr, &dstIndirIndexVal);
  4114. }
  4115. MarkArgumentsUsedForBranch(instr);
  4116. CSEOptimize(this->currentBlock, &instr, &src1Val, &src2Val, &src1IndirIndexVal);
  4117. OptArraySrc(&instr);
  4118. OptNewScObject(&instr, src1Val);
  4119. instr = this->OptPeep(instr, src1Val, src2Val);
  4120. if (instr->m_opcode == Js::OpCode::Nop ||
  4121. (instr->m_opcode == Js::OpCode::CheckThis &&
  4122. instr->GetSrc1()->IsRegOpnd() &&
  4123. instr->GetSrc1()->AsRegOpnd()->m_sym->m_isSafeThis))
  4124. {
  4125. instrNext = instr->m_next;
  4126. InsertNoImplicitCallUses(instr);
  4127. if (this->byteCodeUses)
  4128. {
  4129. this->InsertByteCodeUses(instr);
  4130. }
  4131. *isInstrRemoved = true;
  4132. this->currentBlock->RemoveInstr(instr);
  4133. return instrNext;
  4134. }
  4135. else if (instr->m_opcode == Js::OpCode::GetNewScObject && src1Val->GetValueInfo()->IsPrimitive())
  4136. {
  4137. // Constructor returned (src1) a primitive value, so fold this into "dst = Ld_A src2", where src2 is the new object that
  4138. // was passed into the constructor as its 'this' parameter
  4139. instr->FreeSrc1();
  4140. instr->SetSrc1(instr->UnlinkSrc2());
  4141. instr->m_opcode = Js::OpCode::Ld_A;
  4142. src1Val = src2Val;
  4143. src2Val = nullptr;
  4144. }
  4145. else if (instr->m_opcode == Js::OpCode::TryCatch && this->func->DoOptimizeTryCatch())
  4146. {
  4147. ProcessTryCatch(instr);
  4148. }
  4149. else if (instr->m_opcode == Js::OpCode::BrOnException)
  4150. {
  4151. // BrOnException was added to model flow from try region to the catch region to assist
  4152. // the backward pass in propagating bytecode upward exposed info from the catch block
  4153. // to the try, and to handle break blocks. Removing it here as it has served its purpose
  4154. // and keeping it around might also have unintended effects while merging block data for
  4155. // the catch block's predecessors.
  4156. // Note that the Deadstore pass will still be able to propagate bytecode upward exposed info
  4157. // because it doesn't skip dead blocks for that.
  4158. this->RemoveFlowEdgeToCatchBlock(instr);
  4159. *isInstrRemoved = true;
  4160. this->currentBlock->RemoveInstr(instr);
  4161. return instrNext;
  4162. }
  4163. else if (instr->m_opcode == Js::OpCode::BrOnNoException)
  4164. {
  4165. this->RemoveFlowEdgeToCatchBlock(instr);
  4166. }
  4167. bool isAlreadyTypeSpecialized = false;
  4168. if (!IsLoopPrePass() && instr->HasBailOutInfo())
  4169. {
  4170. if (instr->GetBailOutKind() == IR::BailOutExpectingInteger)
  4171. {
  4172. isAlreadyTypeSpecialized = TypeSpecializeBailoutExpectedInteger(instr, src1Val, &dstVal);
  4173. }
  4174. else if (instr->GetBailOutKind() == IR::BailOutExpectingString)
  4175. {
  4176. if (instr->GetSrc1()->IsRegOpnd())
  4177. {
  4178. if (!src1Val || !src1Val->GetValueInfo()->IsLikelyString())
  4179. {
  4180. // Disable SwitchOpt if the source is definitely not a string - This may be realized only in Globopt
  4181. Assert(IsSwitchOptEnabled());
  4182. throw Js::RejitException(RejitReason::DisableSwitchOptExpectingString);
  4183. }
  4184. }
  4185. }
  4186. }
  4187. bool forceInvariantHoisting = false;
  4188. const bool ignoreIntOverflowInRangeForInstr = instr->ignoreIntOverflowInRange; // Save it since the instr can change
  4189. if (!isAlreadyTypeSpecialized)
  4190. {
  4191. bool redoTypeSpec;
  4192. instr = this->TypeSpecialization(instr, &src1Val, &src2Val, &dstVal, &redoTypeSpec, &forceInvariantHoisting);
  4193. if(redoTypeSpec && instr->m_opcode != Js::OpCode::Nop)
  4194. {
  4195. forceInvariantHoisting = false;
  4196. instr = this->TypeSpecialization(instr, &src1Val, &src2Val, &dstVal, &redoTypeSpec, &forceInvariantHoisting);
  4197. Assert(!redoTypeSpec);
  4198. }
  4199. if (instr->m_opcode == Js::OpCode::Nop)
  4200. {
  4201. InsertNoImplicitCallUses(instr);
  4202. if (this->byteCodeUses)
  4203. {
  4204. this->InsertByteCodeUses(instr);
  4205. }
  4206. instrNext = instr->m_next;
  4207. *isInstrRemoved = true;
  4208. this->currentBlock->RemoveInstr(instr);
  4209. return instrNext;
  4210. }
  4211. }
  4212. if (ignoreIntOverflowInRangeForInstr)
  4213. {
  4214. VerifyIntSpecForIgnoringIntOverflow(instr);
  4215. }
  4216. // Track calls after any pre-op bailouts have been inserted before the call, because they will need to restore out params.
  4217. // We don't inline in asmjs and hence we don't need to track calls in asmjs too, skipping this step for asmjs.
  4218. if (!GetIsAsmJSFunc())
  4219. {
  4220. this->TrackCalls(instr);
  4221. }
  4222. if (instr->GetSrc1())
  4223. {
  4224. this->UpdateObjPtrValueType(instr->GetSrc1(), instr);
  4225. }
  4226. IR::Opnd *dst = instr->GetDst();
  4227. if (dst)
  4228. {
  4229. // Copy prop dst uses and mark live/available type syms before tracking kills.
  4230. CopyPropDstUses(dst, instr, src1Val);
  4231. }
  4232. // Track mark temp object before we process the dst so we can generate pre-op bailout
  4233. instr = this->TrackMarkTempObject(instrPrev->m_next, instr);
  4234. bool removed = OptTagChecks(instr);
  4235. if (removed)
  4236. {
  4237. *isInstrRemoved = true;
  4238. return instrNext;
  4239. }
  4240. dstVal = this->OptDst(&instr, dstVal, src1Val, src2Val, dstIndirIndexVal, src1IndirIndexVal);
  4241. dst = instr->GetDst();
  4242. instrNext = instr->m_next;
  4243. if (dst)
  4244. {
  4245. if (this->func->HasTry() && this->func->DoOptimizeTryCatch())
  4246. {
  4247. this->InsertToVarAtDefInTryRegion(instr, dst);
  4248. }
  4249. instr = this->SetTypeCheckBailOut(dst, instr, nullptr);
  4250. this->UpdateObjPtrValueType(dst, instr);
  4251. }
  4252. BVSparse<JitArenaAllocator> instrByteCodeStackSymUsedAfter(this->alloc);
  4253. PropertySym *propertySymUseAfter = nullptr;
  4254. if (this->byteCodeUses != nullptr)
  4255. {
  4256. GlobOpt::TrackByteCodeSymUsed(instr, &instrByteCodeStackSymUsedAfter, &propertySymUseAfter);
  4257. }
  4258. #if DBG
  4259. else
  4260. {
  4261. GlobOpt::TrackByteCodeSymUsed(instr, &instrByteCodeStackSymUsedAfter, &propertySymUseAfter);
  4262. instrByteCodeStackSymUsedAfter.Equal(this->byteCodeUsesBeforeOpt);
  4263. Assert(propertySymUseAfter == propertySymUseBefore);
  4264. }
  4265. #endif
  4266. bool isHoisted = false;
  4267. if (this->currentBlock->loop && !this->IsLoopPrePass())
  4268. {
  4269. isHoisted = this->TryHoistInvariant(instr, this->currentBlock, dstVal, src1Val, src2Val, true, false, forceInvariantHoisting);
  4270. }
  4271. src1 = instr->GetSrc1();
  4272. if (!this->IsLoopPrePass() && src1)
  4273. {
  4274. // instr const, nonConst => canonicalize by swapping operands
  4275. // This simplifies lowering. (somewhat machine dependent)
  4276. // Note that because of Var overflows, src1 may not have been constant prop'd to an IntConst
  4277. this->PreLowerCanonicalize(instr, &src1Val, &src2Val);
  4278. }
  4279. if (!PHASE_OFF(Js::MemOpPhase, this->func) &&
  4280. !isHoisted &&
  4281. !(instr->IsJitProfilingInstr()) &&
  4282. this->currentBlock->loop && !IsLoopPrePass() &&
  4283. !func->IsJitInDebugMode() &&
  4284. (func->HasProfileInfo() && !func->GetProfileInfo()->IsMemOpDisabled()) &&
  4285. (!this->currentBlock->loop->memOpInfo || this->currentBlock->loop->memOpInfo->doMemOp))
  4286. {
  4287. CollectMemOpInfo(instr, src1Val, src2Val);
  4288. }
  4289. InsertNoImplicitCallUses(instr);
  4290. if (this->byteCodeUses != nullptr)
  4291. {
  4292. // Optimization removed some uses from the instruction.
  4293. // Need to insert fake uses so we can get the correct live register to restore in bailout.
  4294. this->byteCodeUses->Minus(&instrByteCodeStackSymUsedAfter);
  4295. if (this->propertySymUse == propertySymUseAfter)
  4296. {
  4297. this->propertySymUse = nullptr;
  4298. }
  4299. this->InsertByteCodeUses(instr);
  4300. }
  4301. if (!this->IsLoopPrePass() && !isHoisted && this->IsImplicitCallBailOutCurrentlyNeeded(instr, src1Val, src2Val))
  4302. {
  4303. IR::BailOutKind kind = IR::BailOutOnImplicitCalls;
  4304. if(instr->HasBailOutInfo())
  4305. {
  4306. Assert(instr->GetBailOutInfo()->bailOutOffset == instr->GetByteCodeOffset());
  4307. const IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  4308. if((bailOutKind & ~IR::BailOutKindBits) != IR::BailOutOnImplicitCallsPreOp)
  4309. {
  4310. Assert(!(bailOutKind & ~IR::BailOutKindBits));
  4311. instr->SetBailOutKind(bailOutKind + IR::BailOutOnImplicitCallsPreOp);
  4312. }
  4313. }
  4314. else if (instr->forcePreOpBailOutIfNeeded || this->isRecursiveCallOnLandingPad)
  4315. {
  4316. // We can't have a byte code reg slot as dst to generate a
  4317. // pre-op implicit call after we have processed the dst.
  4318. // Consider: This might miss an opportunity to use a copy prop sym to restore
  4319. // some other byte code reg if the dst is that copy prop that we already killed.
  4320. Assert(!instr->GetDst()
  4321. || !instr->GetDst()->IsRegOpnd()
  4322. || instr->GetDst()->AsRegOpnd()->GetIsJITOptimizedReg()
  4323. || !instr->GetDst()->AsRegOpnd()->m_sym->HasByteCodeRegSlot());
  4324. this->GenerateBailAtOperation(&instr, IR::BailOutOnImplicitCallsPreOp);
  4325. }
  4326. else
  4327. {
  4328. // Capture value of the bailout after the operation is done.
  4329. this->GenerateBailAfterOperation(&instr, kind);
  4330. }
  4331. }
  4332. return instrNext;
  4333. }
  4334. bool
  4335. GlobOpt::OptTagChecks(IR::Instr *instr)
  4336. {
  4337. if (PHASE_OFF(Js::OptTagChecksPhase, this->func))
  4338. {
  4339. return false;
  4340. }
  4341. StackSym *stackSym = nullptr;
  4342. IR::SymOpnd *symOpnd = nullptr;
  4343. IR::RegOpnd *regOpnd = nullptr;
  4344. switch(instr->m_opcode)
  4345. {
  4346. case Js::OpCode::LdFld:
  4347. case Js::OpCode::LdMethodFld:
  4348. case Js::OpCode::CheckFixedFld:
  4349. case Js::OpCode::CheckPropertyGuardAndLoadType:
  4350. symOpnd = instr->GetSrc1()->AsSymOpnd();
  4351. stackSym = symOpnd->m_sym->AsPropertySym()->m_stackSym;
  4352. break;
  4353. case Js::OpCode::BailOnNotObject:
  4354. case Js::OpCode::BailOnNotArray:
  4355. if (instr->GetSrc1()->IsRegOpnd())
  4356. {
  4357. regOpnd = instr->GetSrc1()->AsRegOpnd();
  4358. stackSym = regOpnd->m_sym;
  4359. }
  4360. break;
  4361. case Js::OpCode::StFld:
  4362. symOpnd = instr->GetDst()->AsSymOpnd();
  4363. stackSym = symOpnd->m_sym->AsPropertySym()->m_stackSym;
  4364. break;
  4365. }
  4366. if (stackSym)
  4367. {
  4368. Value *value = FindValue(blockData.symToValueMap, stackSym);
  4369. if (value)
  4370. {
  4371. ValueType valueType = value->GetValueInfo()->Type();
  4372. if (instr->m_opcode == Js::OpCode::BailOnNotObject)
  4373. {
  4374. if (valueType.CanBeTaggedValue())
  4375. {
  4376. ChangeValueType(nullptr, value, valueType.SetCanBeTaggedValue(false), false);
  4377. return false;
  4378. }
  4379. if (this->byteCodeUses)
  4380. {
  4381. this->InsertByteCodeUses(instr);
  4382. }
  4383. this->currentBlock->RemoveInstr(instr);
  4384. return true;
  4385. }
  4386. if (valueType.CanBeTaggedValue() &&
  4387. !valueType.HasBeenNumber() &&
  4388. (this->IsLoopPrePass() || !this->currentBlock->loop))
  4389. {
  4390. ValueType newValueType = valueType.SetCanBeTaggedValue(false);
  4391. // Split out the tag check as a separate instruction.
  4392. IR::Instr *bailOutInstr;
  4393. bailOutInstr = IR::BailOutInstr::New(Js::OpCode::BailOnNotObject, IR::BailOutOnTaggedValue, instr, instr->m_func);
  4394. if (!this->IsLoopPrePass())
  4395. {
  4396. FillBailOutInfo(this->currentBlock, bailOutInstr->GetBailOutInfo());
  4397. }
  4398. IR::RegOpnd *srcOpnd = regOpnd;
  4399. if (!srcOpnd)
  4400. {
  4401. srcOpnd = IR::RegOpnd::New(stackSym, stackSym->GetType(), instr->m_func);
  4402. AnalysisAssert(symOpnd);
  4403. if (symOpnd->GetIsJITOptimizedReg())
  4404. {
  4405. srcOpnd->SetIsJITOptimizedReg(true);
  4406. }
  4407. }
  4408. bailOutInstr->SetSrc1(srcOpnd);
  4409. bailOutInstr->GetSrc1()->SetValueType(valueType);
  4410. instr->InsertBefore(bailOutInstr);
  4411. if (symOpnd)
  4412. {
  4413. symOpnd->SetPropertyOwnerValueType(newValueType);
  4414. }
  4415. else
  4416. {
  4417. regOpnd->SetValueType(newValueType);
  4418. }
  4419. ChangeValueType(nullptr, value, newValueType, false);
  4420. }
  4421. }
  4422. }
  4423. return false;
  4424. }
  4425. bool
  4426. GlobOpt::TypeSpecializeBailoutExpectedInteger(IR::Instr* instr, Value* src1Val, Value** dstVal)
  4427. {
  4428. bool isAlreadyTypeSpecialized = false;
  4429. if(instr->GetSrc1()->IsRegOpnd())
  4430. {
  4431. if (!src1Val || !src1Val->GetValueInfo()->IsLikelyInt() || instr->GetSrc1()->AsRegOpnd()->m_sym->m_isNotInt)
  4432. {
  4433. Assert(IsSwitchOptEnabled());
  4434. throw Js::RejitException(RejitReason::DisableSwitchOptExpectingInteger);
  4435. }
  4436. // Attach the BailOutExpectingInteger to FromVar and Remove the bail out info on the Ld_A (Begin Switch) instr.
  4437. this->ToTypeSpecUse(instr, instr->GetSrc1(), this->currentBlock, src1Val, nullptr, TyInt32, IR::BailOutExpectingInteger, false, instr);
  4438. //TypeSpecialize the dst of Ld_A
  4439. TypeSpecializeIntDst(instr, instr->m_opcode, src1Val, src1Val, nullptr, IR::BailOutInvalid, INT32_MIN, INT32_MAX, dstVal);
  4440. isAlreadyTypeSpecialized = true;
  4441. }
  4442. instr->ClearBailOutInfo();
  4443. return isAlreadyTypeSpecialized;
  4444. }
  4445. Value*
  4446. GlobOpt::OptDst(
  4447. IR::Instr ** pInstr,
  4448. Value *dstVal,
  4449. Value *src1Val,
  4450. Value *src2Val,
  4451. Value *dstIndirIndexVal,
  4452. Value *src1IndirIndexVal)
  4453. {
  4454. IR::Instr *&instr = *pInstr;
  4455. IR::Opnd *opnd = instr->GetDst();
  4456. if (opnd)
  4457. {
  4458. if (opnd->IsSymOpnd() && opnd->AsSymOpnd()->IsPropertySymOpnd())
  4459. {
  4460. this->FinishOptPropOp(instr, opnd->AsPropertySymOpnd());
  4461. }
  4462. else if (instr->m_opcode == Js::OpCode::StElemI_A ||
  4463. instr->m_opcode == Js::OpCode::StElemI_A_Strict ||
  4464. instr->m_opcode == Js::OpCode::InitComputedProperty)
  4465. {
  4466. this->KillObjectHeaderInlinedTypeSyms(this->currentBlock, false);
  4467. }
  4468. if (opnd->IsIndirOpnd() && !this->IsLoopPrePass())
  4469. {
  4470. IR::RegOpnd *baseOpnd = opnd->AsIndirOpnd()->GetBaseOpnd();
  4471. const ValueType baseValueType(baseOpnd->GetValueType());
  4472. if ((
  4473. baseValueType.IsLikelyNativeArray() ||
  4474. #ifdef _M_IX86
  4475. (
  4476. !AutoSystemInfo::Data.SSE2Available() &&
  4477. baseValueType.IsLikelyObject() &&
  4478. (
  4479. baseValueType.GetObjectType() == ObjectType::Float32Array ||
  4480. baseValueType.GetObjectType() == ObjectType::Float64Array
  4481. )
  4482. )
  4483. #else
  4484. false
  4485. #endif
  4486. ) &&
  4487. instr->GetSrc1()->IsVar())
  4488. {
  4489. if(instr->m_opcode == Js::OpCode::StElemC)
  4490. {
  4491. // StElemC has different code that handles native array conversion or missing value stores. Add a bailout
  4492. // for those cases.
  4493. Assert(baseValueType.IsLikelyNativeArray());
  4494. Assert(!instr->HasBailOutInfo());
  4495. GenerateBailAtOperation(&instr, IR::BailOutConventionalNativeArrayAccessOnly);
  4496. }
  4497. else if(instr->HasBailOutInfo())
  4498. {
  4499. // The lowerer is not going to generate a fast path for this case. Remove any bailouts that require the fast
  4500. // path. Note that the removed bailouts should not be necessary for correctness. Bailout on native array
  4501. // conversion will be handled automatically as normal.
  4502. IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  4503. if(bailOutKind & IR::BailOutOnArrayAccessHelperCall)
  4504. {
  4505. bailOutKind -= IR::BailOutOnArrayAccessHelperCall;
  4506. }
  4507. if(bailOutKind == IR::BailOutOnImplicitCallsPreOp)
  4508. {
  4509. bailOutKind -= IR::BailOutOnImplicitCallsPreOp;
  4510. }
  4511. if(bailOutKind)
  4512. {
  4513. instr->SetBailOutKind(bailOutKind);
  4514. }
  4515. else
  4516. {
  4517. instr->ClearBailOutInfo();
  4518. }
  4519. }
  4520. }
  4521. }
  4522. }
  4523. this->ProcessKills(instr);
  4524. if (opnd)
  4525. {
  4526. if (dstVal == nullptr)
  4527. {
  4528. dstVal = ValueNumberDst(pInstr, src1Val, src2Val);
  4529. }
  4530. if (this->IsLoopPrePass())
  4531. {
  4532. // Keep track of symbols defined in the loop.
  4533. if (opnd->IsRegOpnd())
  4534. {
  4535. StackSym *symDst = opnd->AsRegOpnd()->m_sym;
  4536. rootLoopPrePass->symsDefInLoop->Set(symDst->m_id);
  4537. }
  4538. }
  4539. else if (dstVal)
  4540. {
  4541. opnd->SetValueType(dstVal->GetValueInfo()->Type());
  4542. if(currentBlock->loop &&
  4543. !IsLoopPrePass() &&
  4544. (instr->m_opcode == Js::OpCode::Ld_A || instr->m_opcode == Js::OpCode::Ld_I4) &&
  4545. instr->GetSrc1()->IsRegOpnd() &&
  4546. !func->IsJitInDebugMode() &&
  4547. func->DoGlobOptsForGeneratorFunc())
  4548. {
  4549. // Look for the following patterns:
  4550. //
  4551. // Pattern 1:
  4552. // s1[liveOnBackEdge] = s3[dead]
  4553. //
  4554. // Pattern 2:
  4555. // s3 = operation(s1[liveOnBackEdge], s2)
  4556. // s1[liveOnBackEdge] = s3
  4557. //
  4558. // In both patterns, s1 and s3 have the same value by the end. Prefer to use s1 as the sym store instead of s3
  4559. // since s1 is live on back-edge, as otherwise, their lifetimes overlap, requiring two registers to hold the
  4560. // value instead of one.
  4561. do
  4562. {
  4563. IR::RegOpnd *const src = instr->GetSrc1()->AsRegOpnd();
  4564. StackSym *srcVarSym = src->m_sym;
  4565. if(srcVarSym->IsTypeSpec())
  4566. {
  4567. srcVarSym = srcVarSym->GetVarEquivSym(nullptr);
  4568. Assert(srcVarSym);
  4569. }
  4570. if(dstVal->GetValueInfo()->GetSymStore() != srcVarSym)
  4571. {
  4572. break;
  4573. }
  4574. IR::RegOpnd *const dst = opnd->AsRegOpnd();
  4575. StackSym *dstVarSym = dst->m_sym;
  4576. if(dstVarSym->IsTypeSpec())
  4577. {
  4578. dstVarSym = dstVarSym->GetVarEquivSym(nullptr);
  4579. Assert(dstVarSym);
  4580. }
  4581. if(!currentBlock->loop->regAlloc.liveOnBackEdgeSyms->Test(dstVarSym->m_id))
  4582. {
  4583. break;
  4584. }
  4585. Value *const srcValue = FindValue(srcVarSym);
  4586. if(srcValue->GetValueNumber() != dstVal->GetValueNumber())
  4587. {
  4588. break;
  4589. }
  4590. if(!src->GetIsDead())
  4591. {
  4592. IR::Instr *const prevInstr = instr->GetPrevRealInstrOrLabel();
  4593. IR::Opnd *const prevDst = prevInstr->GetDst();
  4594. if(!prevDst ||
  4595. !src->IsEqualInternal(prevDst) ||
  4596. !(
  4597. prevInstr->GetSrc1() && dst->IsEqual(prevInstr->GetSrc1()) ||
  4598. prevInstr->GetSrc2() && dst->IsEqual(prevInstr->GetSrc2())
  4599. ))
  4600. {
  4601. break;
  4602. }
  4603. }
  4604. dstVal->GetValueInfo()->SetSymStore(dstVarSym);
  4605. } while(false);
  4606. }
  4607. }
  4608. this->ValueNumberObjectType(opnd, instr);
  4609. }
  4610. this->CSEAddInstr(this->currentBlock, *pInstr, dstVal, src1Val, src2Val, dstIndirIndexVal, src1IndirIndexVal);
  4611. return dstVal;
  4612. }
  4613. void
  4614. GlobOpt::CopyPropDstUses(IR::Opnd *opnd, IR::Instr *instr, Value *src1Val)
  4615. {
  4616. if (opnd->IsSymOpnd())
  4617. {
  4618. IR::SymOpnd *symOpnd = opnd->AsSymOpnd();
  4619. if (symOpnd->m_sym->IsPropertySym())
  4620. {
  4621. PropertySym * originalPropertySym = symOpnd->m_sym->AsPropertySym();
  4622. Value *const objectValue = FindValue(originalPropertySym->m_stackSym);
  4623. symOpnd->SetPropertyOwnerValueType(objectValue ? objectValue->GetValueInfo()->Type() : ValueType::Uninitialized);
  4624. this->FieldHoistOptDst(instr, originalPropertySym, src1Val);
  4625. PropertySym * sym = this->CopyPropPropertySymObj(symOpnd, instr);
  4626. if (sym != originalPropertySym && !this->IsLoopPrePass())
  4627. {
  4628. // Consider: This doesn't detect hoistability of a property sym after object pointer copy prop
  4629. // on loop prepass. But if it so happened that the property sym is hoisted, we might as well do so.
  4630. this->FieldHoistOptDst(instr, sym, src1Val);
  4631. }
  4632. }
  4633. }
  4634. }
  4635. void
  4636. GlobOpt::SetLoopFieldInitialValue(Loop *loop, IR::Instr *instr, PropertySym *propertySym, PropertySym *originalPropertySym)
  4637. {
  4638. Value *initialValue;
  4639. StackSym *symStore;
  4640. if (loop->allFieldsKilled || loop->fieldKilled->Test(originalPropertySym->m_id))
  4641. {
  4642. return;
  4643. }
  4644. Assert(!loop->fieldKilled->Test(propertySym->m_id));
  4645. // Value already exists
  4646. if (this->FindValue(propertySym))
  4647. {
  4648. return;
  4649. }
  4650. // If this initial value was already added, we would find in the current value table.
  4651. Assert(!loop->initialValueFieldMap.TryGetValue(propertySym, &initialValue));
  4652. // If propertySym is live in landingPad, we don't need an initial value.
  4653. if (loop->landingPad->globOptData.liveFields->Test(propertySym->m_id))
  4654. {
  4655. return;
  4656. }
  4657. Value *landingPadObjPtrVal, *currentObjPtrVal;
  4658. landingPadObjPtrVal = this->FindValue(loop->landingPad->globOptData.symToValueMap, propertySym->m_stackSym);
  4659. currentObjPtrVal = this->FindValue(propertySym->m_stackSym);
  4660. if (!currentObjPtrVal || !landingPadObjPtrVal || currentObjPtrVal->GetValueNumber() != landingPadObjPtrVal->GetValueNumber())
  4661. {
  4662. // objPtr has a different value in the landing pad.
  4663. return;
  4664. }
  4665. // The opnd's value type has not yet been initialized. Since the property sym doesn't have a value, it effectively has an
  4666. // Uninitialized value type. Use the profiled value type from the instruction.
  4667. const ValueType profiledValueType =
  4668. instr->IsProfiledInstr() ? instr->AsProfiledInstr()->u.FldInfo().valueType : ValueType::Uninitialized;
  4669. Assert(!profiledValueType.IsDefinite()); // Hence the values created here don't need to be tracked for kills
  4670. initialValue = this->NewGenericValue(profiledValueType, propertySym);
  4671. symStore = StackSym::New(this->func);
  4672. initialValue->GetValueInfo()->SetSymStore(symStore);
  4673. loop->initialValueFieldMap.Add(propertySym, initialValue->Copy(this->alloc, initialValue->GetValueNumber()));
  4674. // Copy the initial value into the landing pad, but without a symStore
  4675. Value *landingPadInitialValue = Value::New(this->alloc, initialValue->GetValueNumber(),
  4676. ValueInfo::New(this->alloc, initialValue->GetValueInfo()->Type()));
  4677. this->SetValue(&(loop->landingPad->globOptData), landingPadInitialValue, propertySym);
  4678. loop->landingPad->globOptData.liveFields->Set(propertySym->m_id);
  4679. #if DBG_DUMP
  4680. if (PHASE_TRACE(Js::FieldPREPhase, this->func))
  4681. {
  4682. Output::Print(_u("** TRACE: Field PRE initial value for loop head #%d. Val:%d symStore:"),
  4683. loop->GetHeadBlock()->GetBlockNum(), initialValue->GetValueNumber());
  4684. symStore->Dump();
  4685. Output::Print(_u("\n Instr: "));
  4686. instr->Dump();
  4687. }
  4688. #endif
  4689. // Add initial value to all the previous blocks in the loop.
  4690. FOREACH_BLOCK_BACKWARD_IN_RANGE(block, this->currentBlock->GetPrev(), loop->GetHeadBlock())
  4691. {
  4692. if (block->GetDataUseCount() == 0)
  4693. {
  4694. // All successor blocks have been processed, no point in adding the value.
  4695. continue;
  4696. }
  4697. Value *newValue = initialValue->Copy(this->alloc, initialValue->GetValueNumber());
  4698. this->SetValue(&(block->globOptData), newValue, propertySym);
  4699. block->globOptData.liveFields->Set(propertySym->m_id);
  4700. this->SetValue(&(block->globOptData), newValue, symStore);
  4701. block->globOptData.liveVarSyms->Set(symStore->m_id);
  4702. } NEXT_BLOCK_BACKWARD_IN_RANGE;
  4703. this->SetValue(&(this->currentBlock->globOptData), initialValue, symStore);
  4704. this->currentBlock->globOptData.liveVarSyms->Set(symStore->m_id);
  4705. this->blockData.liveFields->Set(propertySym->m_id);
  4706. }
  4707. // Examine src, apply copy prop and value number it
  4708. Value*
  4709. GlobOpt::OptSrc(IR::Opnd *opnd, IR::Instr * *pInstr, Value **indirIndexValRef, IR::IndirOpnd *parentIndirOpnd)
  4710. {
  4711. IR::Instr * &instr = *pInstr;
  4712. Assert(!indirIndexValRef || !*indirIndexValRef);
  4713. Assert(
  4714. parentIndirOpnd
  4715. ? opnd == parentIndirOpnd->GetBaseOpnd() || opnd == parentIndirOpnd->GetIndexOpnd()
  4716. : opnd == instr->GetSrc1() || opnd == instr->GetSrc2() || opnd == instr->GetDst() && opnd->IsIndirOpnd());
  4717. Sym *sym;
  4718. Value *val;
  4719. PropertySym *originalPropertySym = nullptr;
  4720. switch(opnd->GetKind())
  4721. {
  4722. case IR::OpndKindIntConst:
  4723. val = this->GetIntConstantValue(opnd->AsIntConstOpnd()->AsInt32(), instr);
  4724. opnd->SetValueType(val->GetValueInfo()->Type());
  4725. return val;
  4726. case IR::OpndKindFloatConst:
  4727. {
  4728. const FloatConstType floatValue = opnd->AsFloatConstOpnd()->m_value;
  4729. int32 int32Value;
  4730. if(Js::JavascriptNumber::TryGetInt32Value(floatValue, &int32Value))
  4731. {
  4732. val = GetIntConstantValue(int32Value, instr);
  4733. }
  4734. else
  4735. {
  4736. val = NewFloatConstantValue(floatValue);
  4737. }
  4738. opnd->SetValueType(val->GetValueInfo()->Type());
  4739. return val;
  4740. }
  4741. case IR::OpndKindAddr:
  4742. {
  4743. IR::AddrOpnd *addrOpnd = opnd->AsAddrOpnd();
  4744. if (addrOpnd->m_isFunction)
  4745. {
  4746. AssertMsg(!PHASE_OFF(Js::FixedMethodsPhase, instr->m_func->GetJnFunction()), "Fixed function address operand with fixed method calls phase disabled?");
  4747. val = NewFixedFunctionValue((Js::JavascriptFunction *)addrOpnd->m_address, addrOpnd);
  4748. opnd->SetValueType(val->GetValueInfo()->Type());
  4749. return val;
  4750. }
  4751. else if (addrOpnd->IsVar() && Js::TaggedInt::Is(addrOpnd->m_address))
  4752. {
  4753. val = this->GetIntConstantValue(Js::TaggedInt::ToInt32(addrOpnd->m_address), instr);
  4754. opnd->SetValueType(val->GetValueInfo()->Type());
  4755. return val;
  4756. }
  4757. val = this->GetVarConstantValue(addrOpnd);
  4758. return val;
  4759. }
  4760. case IR::OpndKindSym:
  4761. {
  4762. // Clear the opnd's value type up-front, so that this code cannot accidentally use the value type set from a previous
  4763. // OptSrc on the same instruction (for instance, from an earlier loop prepass). The value type will be set from the
  4764. // value if available, before returning from this function.
  4765. opnd->SetValueType(ValueType::Uninitialized);
  4766. sym = opnd->AsSymOpnd()->m_sym;
  4767. // Don't create a new value for ArgSlots and don't copy prop them away.
  4768. if (sym->IsStackSym() && sym->AsStackSym()->IsArgSlotSym())
  4769. {
  4770. return nullptr;
  4771. }
  4772. // Unless we have profile info, don't create a new value for ArgSlots and don't copy prop them away.
  4773. if (sym->IsStackSym() && sym->AsStackSym()->IsParamSlotSym())
  4774. {
  4775. if (!instr->m_func->IsLoopBody() && instr->m_func->HasProfileInfo())
  4776. {
  4777. // Skip "this" pointer.
  4778. int paramSlotNum = sym->AsStackSym()->GetParamSlotNum() - 2;
  4779. if (paramSlotNum >= 0)
  4780. {
  4781. const auto parameterType = instr->m_func->GetProfileInfo()->GetParameterInfo(
  4782. instr->m_func->GetJnFunction(), static_cast<Js::ArgSlot>(paramSlotNum));
  4783. val = NewGenericValue(parameterType);
  4784. opnd->SetValueType(val->GetValueInfo()->Type());
  4785. return val;
  4786. }
  4787. }
  4788. return nullptr;
  4789. }
  4790. if (!sym->IsPropertySym())
  4791. {
  4792. break;
  4793. }
  4794. originalPropertySym = sym->AsPropertySym();
  4795. Value *const objectValue = FindValue(originalPropertySym->m_stackSym);
  4796. opnd->AsSymOpnd()->SetPropertyOwnerValueType(
  4797. objectValue ? objectValue->GetValueInfo()->Type() : ValueType::Uninitialized);
  4798. if (!FieldHoistOptSrc(opnd->AsSymOpnd(), instr, originalPropertySym))
  4799. {
  4800. sym = this->CopyPropPropertySymObj(opnd->AsSymOpnd(), instr);
  4801. // Consider: This doesn't detect hoistability of a property sym after object pointer copy prop
  4802. // on loop prepass. But if it so happened that the property sym is hoisted, we might as well do so.
  4803. if (originalPropertySym == sym || this->IsLoopPrePass() ||
  4804. !FieldHoistOptSrc(opnd->AsSymOpnd(), instr, sym->AsPropertySym()))
  4805. {
  4806. if (!DoFieldCopyProp())
  4807. {
  4808. if (opnd->AsSymOpnd()->IsPropertySymOpnd())
  4809. {
  4810. this->FinishOptPropOp(instr, opnd->AsPropertySymOpnd());
  4811. }
  4812. return nullptr;
  4813. }
  4814. switch (instr->m_opcode)
  4815. {
  4816. // These need the symbolic reference to the field, don't copy prop the value of the field
  4817. case Js::OpCode::DeleteFld:
  4818. case Js::OpCode::DeleteRootFld:
  4819. case Js::OpCode::DeleteFldStrict:
  4820. case Js::OpCode::DeleteRootFldStrict:
  4821. case Js::OpCode::ScopedDeleteFld:
  4822. case Js::OpCode::ScopedDeleteFldStrict:
  4823. case Js::OpCode::LdMethodFromFlags:
  4824. case Js::OpCode::BrOnNoProperty:
  4825. case Js::OpCode::BrOnHasProperty:
  4826. case Js::OpCode::LdMethodFldPolyInlineMiss:
  4827. case Js::OpCode::StSlotChkUndecl:
  4828. return nullptr;
  4829. };
  4830. if (instr->CallsGetter())
  4831. {
  4832. return nullptr;
  4833. }
  4834. if (this->IsLoopPrePass() && this->DoFieldPRE(this->rootLoopPrePass))
  4835. {
  4836. if (!this->prePassLoop->allFieldsKilled && !this->prePassLoop->fieldKilled->Test(sym->m_id))
  4837. {
  4838. this->SetLoopFieldInitialValue(this->rootLoopPrePass, instr, sym->AsPropertySym(), originalPropertySym);
  4839. }
  4840. if (this->IsPREInstrCandidateLoad(instr->m_opcode))
  4841. {
  4842. // Foreach property sym, remember the first instruction that loads it.
  4843. // Can this be done in one call?
  4844. if (!this->prePassInstrMap->ContainsKey(sym->m_id))
  4845. {
  4846. this->prePassInstrMap->AddNew(sym->m_id, instr);
  4847. }
  4848. }
  4849. }
  4850. break;
  4851. }
  4852. }
  4853. // We field hoisted, we can continue as a reg.
  4854. opnd = instr->GetSrc1();
  4855. }
  4856. case IR::OpndKindReg:
  4857. // Clear the opnd's value type up-front, so that this code cannot accidentally use the value type set from a previous
  4858. // OptSrc on the same instruction (for instance, from an earlier loop prepass). The value type will be set from the
  4859. // value if available, before returning from this function.
  4860. opnd->SetValueType(ValueType::Uninitialized);
  4861. sym = opnd->AsRegOpnd()->m_sym;
  4862. this->MarkTempLastUse(instr, opnd->AsRegOpnd());
  4863. if (sym->AsStackSym()->IsTypeSpec())
  4864. {
  4865. sym = sym->AsStackSym()->GetVarEquivSym(this->func);
  4866. }
  4867. break;
  4868. case IR::OpndKindIndir:
  4869. this->OptimizeIndirUses(opnd->AsIndirOpnd(), &instr, indirIndexValRef);
  4870. return nullptr;
  4871. default:
  4872. return nullptr;
  4873. }
  4874. val = this->FindValue(sym);
  4875. if (val)
  4876. {
  4877. Assert(GlobOpt::IsLive(sym, this->currentBlock) || (sym->IsPropertySym()));
  4878. if (instr)
  4879. {
  4880. opnd = this->CopyProp(opnd, instr, val, parentIndirOpnd);
  4881. }
  4882. // Check if we freed the operand.
  4883. if (opnd == nullptr)
  4884. {
  4885. return nullptr;
  4886. }
  4887. // In a loop prepass, determine stack syms that are used before they are defined in the root loop for which the prepass
  4888. // is being done. This information is used to do type specialization conversions in the landing pad where appropriate.
  4889. if(IsLoopPrePass() &&
  4890. sym->IsStackSym() &&
  4891. !rootLoopPrePass->symsUsedBeforeDefined->Test(sym->m_id) &&
  4892. IsLive(sym, &rootLoopPrePass->landingPad->globOptData) && !isAsmJSFunc) // no typespec in asmjs and hence skipping this
  4893. {
  4894. Value *const landingPadValue = FindValue(rootLoopPrePass->landingPad->globOptData.symToValueMap, sym);
  4895. if(landingPadValue && val->GetValueNumber() == landingPadValue->GetValueNumber())
  4896. {
  4897. rootLoopPrePass->symsUsedBeforeDefined->Set(sym->m_id);
  4898. ValueInfo *landingPadValueInfo = landingPadValue->GetValueInfo();
  4899. if(landingPadValueInfo->IsLikelyNumber())
  4900. {
  4901. rootLoopPrePass->likelyNumberSymsUsedBeforeDefined->Set(sym->m_id);
  4902. if(DoAggressiveIntTypeSpec() ? landingPadValueInfo->IsLikelyInt() : landingPadValueInfo->IsInt())
  4903. {
  4904. // Can only force int conversions in the landing pad based on likely-int values if aggressive int type
  4905. // specialization is enabled.
  4906. rootLoopPrePass->likelyIntSymsUsedBeforeDefined->Set(sym->m_id);
  4907. }
  4908. }
  4909. // SIMD_JS
  4910. // For uses before defs, we set likelySimd128*SymsUsedBeforeDefined bits for syms that have landing pad value info that allow type-spec to happen in the loop body.
  4911. // The BV will be added to loop header if the backedge has a live matching type-spec value. We then compensate in the loop header to unbox the value.
  4912. // This allows type-spec in the landing pad instead of boxing/unboxing on each iteration.
  4913. if (Js::IsSimd128Opcode(instr->m_opcode))
  4914. {
  4915. // Simd ops are strongly typed. We type-spec only if the type is likely/Definitely the expected type or if we have object which can come from merging different Simd types.
  4916. // Simd value must be initialized properly on all paths before the loop entry. Cannot be merged with Undefined/Null.
  4917. ThreadContext::SimdFuncSignature funcSignature;
  4918. instr->m_func->GetScriptContext()->GetThreadContext()->GetSimdFuncSignatureFromOpcode(instr->m_opcode, funcSignature);
  4919. Assert(funcSignature.valid);
  4920. ValueType expectedType = funcSignature.args[opnd == instr->GetSrc1() ? 0 : 1];
  4921. if (expectedType.IsSimd128Float32x4())
  4922. {
  4923. if (
  4924. (landingPadValueInfo->IsLikelySimd128Float32x4() || (landingPadValueInfo->IsLikelyObject() && landingPadValueInfo->GetObjectType() == ObjectType::Object))
  4925. &&
  4926. !landingPadValueInfo->HasBeenUndefined() && !landingPadValueInfo->HasBeenNull()
  4927. )
  4928. {
  4929. rootLoopPrePass->likelySimd128F4SymsUsedBeforeDefined->Set(sym->m_id);
  4930. }
  4931. }
  4932. else if (expectedType.IsSimd128Int32x4())
  4933. {
  4934. if (
  4935. (landingPadValueInfo->IsLikelySimd128Int32x4() || (landingPadValueInfo->IsLikelyObject() && landingPadValueInfo->GetObjectType() == ObjectType::Object))
  4936. &&
  4937. !landingPadValueInfo->HasBeenUndefined() && !landingPadValueInfo->HasBeenNull()
  4938. )
  4939. {
  4940. rootLoopPrePass->likelySimd128I4SymsUsedBeforeDefined->Set(sym->m_id);
  4941. }
  4942. }
  4943. }
  4944. else if (instr->m_opcode == Js::OpCode::ExtendArg_A && opnd == instr->GetSrc1() && instr->GetDst()->GetValueType().IsSimd128())
  4945. {
  4946. // Extended_Args for Simd ops are annotated with the expected type by the inliner. Use this info to find out if type-spec is supposed to happen.
  4947. ValueType expectedType = instr->GetDst()->GetValueType();
  4948. if ((landingPadValueInfo->IsLikelySimd128Float32x4() || (landingPadValueInfo->IsLikelyObject() && landingPadValueInfo->GetObjectType() == ObjectType::Object))
  4949. && expectedType.IsSimd128Float32x4())
  4950. {
  4951. rootLoopPrePass->likelySimd128F4SymsUsedBeforeDefined->Set(sym->m_id);
  4952. }
  4953. else if ((landingPadValueInfo->IsLikelySimd128Int32x4() || (landingPadValueInfo->IsLikelyObject() && landingPadValueInfo->GetObjectType() == ObjectType::Object))
  4954. && expectedType.IsSimd128Int32x4())
  4955. {
  4956. rootLoopPrePass->likelySimd128I4SymsUsedBeforeDefined->Set(sym->m_id);
  4957. }
  4958. }
  4959. }
  4960. }
  4961. }
  4962. else if ((GlobOpt::TransferSrcValue(instr) || OpCodeAttr::CanCSE(instr->m_opcode)) && (opnd == instr->GetSrc1() || opnd == instr->GetSrc2()))
  4963. {
  4964. if (sym->IsPropertySym())
  4965. {
  4966. val = this->CreateFieldSrcValue(sym->AsPropertySym(), originalPropertySym, &opnd, instr);
  4967. }
  4968. else
  4969. {
  4970. val = this->NewGenericValue(ValueType::Uninitialized, opnd);
  4971. }
  4972. }
  4973. if (opnd->IsSymOpnd() && opnd->AsSymOpnd()->IsPropertySymOpnd())
  4974. {
  4975. TryOptimizeInstrWithFixedDataProperty(&instr);
  4976. this->FinishOptPropOp(instr, opnd->AsPropertySymOpnd());
  4977. }
  4978. if (val)
  4979. {
  4980. ValueType valueType(val->GetValueInfo()->Type());
  4981. if (valueType.IsLikelyNativeArray() && !valueType.IsObject() && instr->IsProfiledInstr())
  4982. {
  4983. // See if we have profile data for the array type
  4984. IR::ProfiledInstr *const profiledInstr = instr->AsProfiledInstr();
  4985. ValueType profiledArrayType;
  4986. switch(instr->m_opcode)
  4987. {
  4988. case Js::OpCode::LdElemI_A:
  4989. if(instr->GetSrc1()->IsIndirOpnd() && opnd == instr->GetSrc1()->AsIndirOpnd()->GetBaseOpnd())
  4990. {
  4991. profiledArrayType = profiledInstr->u.ldElemInfo->GetArrayType();
  4992. }
  4993. break;
  4994. case Js::OpCode::StElemI_A:
  4995. case Js::OpCode::StElemI_A_Strict:
  4996. case Js::OpCode::StElemC:
  4997. if(instr->GetDst()->IsIndirOpnd() && opnd == instr->GetDst()->AsIndirOpnd()->GetBaseOpnd())
  4998. {
  4999. profiledArrayType = profiledInstr->u.stElemInfo->GetArrayType();
  5000. }
  5001. break;
  5002. case Js::OpCode::LdLen_A:
  5003. if(instr->GetSrc1()->IsRegOpnd() && opnd == instr->GetSrc1())
  5004. {
  5005. profiledArrayType = profiledInstr->u.ldElemInfo->GetArrayType();
  5006. }
  5007. break;
  5008. }
  5009. if(profiledArrayType.IsLikelyObject() &&
  5010. profiledArrayType.GetObjectType() == valueType.GetObjectType() &&
  5011. (profiledArrayType.HasVarElements() || valueType.HasIntElements() && profiledArrayType.HasFloatElements()))
  5012. {
  5013. // Merge array type we pulled from profile with type propagated by dataflow.
  5014. valueType = valueType.Merge(profiledArrayType).SetHasNoMissingValues(valueType.HasNoMissingValues());
  5015. ChangeValueType(currentBlock, FindValue(blockData.symToValueMap, opnd->AsRegOpnd()->m_sym), valueType, false);
  5016. }
  5017. }
  5018. opnd->SetValueType(valueType);
  5019. if(!IsLoopPrePass() && opnd->IsSymOpnd() && valueType.IsDefinite())
  5020. {
  5021. Sym *const sym = opnd->AsSymOpnd()->m_sym;
  5022. if(sym->IsPropertySym())
  5023. {
  5024. // A property sym can only be guaranteed to have a definite value type when implicit calls are disabled from the
  5025. // point where the sym was defined with the definite value type. Insert an instruction to indicate to the
  5026. // dead-store pass that implicit calls need to be kept disabled until after this instruction.
  5027. Assert(DoFieldCopyProp());
  5028. CaptureNoImplicitCallUses(opnd, false, instr);
  5029. }
  5030. }
  5031. }
  5032. else
  5033. {
  5034. opnd->SetValueType(ValueType::Uninitialized);
  5035. }
  5036. return val;
  5037. }
  5038. /*
  5039. * GlobOpt::TryOptimizeInstrWithFixedDataProperty
  5040. * Converts Ld[Root]Fld instr to
  5041. * * CheckFixedFld
  5042. * * Dst = Ld_A <int Constant value>
  5043. * This API assumes that the source operand is a Sym/PropertySym kind.
  5044. */
  5045. void
  5046. GlobOpt::TryOptimizeInstrWithFixedDataProperty(IR::Instr ** const pInstr)
  5047. {
  5048. Assert(pInstr);
  5049. IR::Instr * &instr = *pInstr;
  5050. IR::Opnd * src1 = instr->GetSrc1();
  5051. Assert(src1 && src1->IsSymOpnd() && src1->AsSymOpnd()->IsPropertySymOpnd());
  5052. if(PHASE_OFF(Js::UseFixedDataPropsPhase, instr->m_func->GetJnFunction()))
  5053. {
  5054. return;
  5055. }
  5056. if (!this->IsLoopPrePass() && !this->isRecursiveCallOnLandingPad &&
  5057. OpCodeAttr::CanLoadFixedFields(instr->m_opcode))
  5058. {
  5059. instr->TryOptimizeInstrWithFixedDataProperty(&instr, this);
  5060. }
  5061. }
  5062. bool
  5063. GlobOpt::TransferSrcValue(IR::Instr * instr)
  5064. {
  5065. // Return whether the instruction transfers a value to the destination.
  5066. // This is used to determine whether we should generate a value for the src so that it will
  5067. // match with the dst for copy prop.
  5068. // No point creating an unknown value for the src of a binary instr, as the dst will just be a different
  5069. // Don't create value for instruction without dst as well. The value doesn't go anywhere.
  5070. // if (src2 == nullptr) Disable copy prop for ScopedLdFld/ScopeStFld, etc., consider enabling that in the future
  5071. // Consider: Add opcode attribute to indicate whether the opcode would use the value or not
  5072. return instr->GetDst() != nullptr && instr->GetSrc2() == nullptr && !OpCodeAttr::DoNotTransfer(instr->m_opcode) && !instr->CallsAccessor();
  5073. }
  5074. Value*
  5075. GlobOpt::FindValue(Sym *sym)
  5076. {
  5077. return FindValue(this->blockData.symToValueMap, sym);
  5078. }
  5079. Value*
  5080. GlobOpt::FindValue(GlobHashTable *valueNumberMap, Sym *sym)
  5081. {
  5082. Assert(valueNumberMap);
  5083. if (sym->IsStackSym() && sym->AsStackSym()->IsTypeSpec())
  5084. {
  5085. sym = sym->AsStackSym()->GetVarEquivSym(this->func);
  5086. }
  5087. else if (sym->IsPropertySym())
  5088. {
  5089. return FindPropertyValue(valueNumberMap, sym->m_id);
  5090. }
  5091. if (sym->IsStackSym() && sym->AsStackSym()->IsFromByteCodeConstantTable())
  5092. {
  5093. return this->byteCodeConstantValueArray->Get(sym->m_id);
  5094. }
  5095. else
  5096. {
  5097. return FindValueFromHashTable(valueNumberMap, sym->m_id);
  5098. }
  5099. }
  5100. ValueNumber
  5101. GlobOpt::FindValueNumber(GlobHashTable *valueNumberMap, Sym *sym)
  5102. {
  5103. Value *val = FindValue(valueNumberMap, sym);
  5104. return val->GetValueNumber();
  5105. }
  5106. Value *
  5107. GlobOpt::FindPropertyValue(GlobHashTable *valueNumberMap, SymID symId)
  5108. {
  5109. Assert(this->func->m_symTable->Find(symId)->IsPropertySym());
  5110. if (!this->blockData.liveFields->Test(symId))
  5111. {
  5112. Assert(!IsHoistablePropertySym(symId));
  5113. return nullptr;
  5114. }
  5115. return FindValueFromHashTable(valueNumberMap, symId);
  5116. }
  5117. ValueNumber
  5118. GlobOpt::FindPropertyValueNumber(GlobHashTable *valueNumberMap, SymID symId)
  5119. {
  5120. Value *val = FindPropertyValue(valueNumberMap, symId);
  5121. return val->GetValueNumber();
  5122. }
  5123. Value *
  5124. GlobOpt::FindObjectTypeValue(StackSym* typeSym)
  5125. {
  5126. return FindObjectTypeValue(typeSym, this->blockData.symToValueMap);
  5127. }
  5128. Value *
  5129. GlobOpt::FindObjectTypeValue(StackSym* typeSym, BasicBlock* block)
  5130. {
  5131. return FindObjectTypeValue(typeSym->m_id, block);
  5132. }
  5133. Value *
  5134. GlobOpt::FindObjectTypeValue(SymID typeSymId, BasicBlock* block)
  5135. {
  5136. return FindObjectTypeValue(typeSymId, block->globOptData.symToValueMap, block->globOptData.liveFields);
  5137. }
  5138. Value *
  5139. GlobOpt::FindObjectTypeValue(StackSym* typeSym, GlobHashTable *valueNumberMap)
  5140. {
  5141. return FindObjectTypeValue(typeSym->m_id, valueNumberMap);
  5142. }
  5143. Value *
  5144. GlobOpt::FindObjectTypeValue(SymID typeSymId, GlobHashTable *valueNumberMap)
  5145. {
  5146. return FindObjectTypeValue(typeSymId, valueNumberMap, this->blockData.liveFields);
  5147. }
  5148. Value *
  5149. GlobOpt::FindObjectTypeValue(StackSym* typeSym, GlobHashTable *valueNumberMap, BVSparse<JitArenaAllocator>* liveFields)
  5150. {
  5151. return FindObjectTypeValue(typeSym->m_id, valueNumberMap, liveFields);
  5152. }
  5153. Value *
  5154. GlobOpt::FindObjectTypeValue(SymID typeSymId, GlobHashTable *valueNumberMap, BVSparse<JitArenaAllocator>* liveFields)
  5155. {
  5156. Assert(this->func->m_symTable->Find(typeSymId)->IsStackSym());
  5157. if (!liveFields->Test(typeSymId))
  5158. {
  5159. return nullptr;
  5160. }
  5161. Value* value = FindValueFromHashTable(valueNumberMap, typeSymId);
  5162. Assert(value == nullptr || value->GetValueInfo()->IsJsType());
  5163. return value;
  5164. }
  5165. Value *
  5166. GlobOpt::FindFuturePropertyValue(PropertySym *const propertySym)
  5167. {
  5168. Assert(propertySym);
  5169. // Try a direct lookup based on this sym
  5170. Value *const value = FindValue(propertySym);
  5171. if(value)
  5172. {
  5173. return value;
  5174. }
  5175. if(PHASE_OFF(Js::CopyPropPhase, func))
  5176. {
  5177. // Need to use copy-prop info to backtrack
  5178. return nullptr;
  5179. }
  5180. // Try to get the property object's value
  5181. StackSym *const objectSym = propertySym->m_stackSym;
  5182. Value *objectValue = FindValue(objectSym);
  5183. if(!objectValue)
  5184. {
  5185. if(!objectSym->IsSingleDef())
  5186. {
  5187. return nullptr;
  5188. }
  5189. switch(objectSym->m_instrDef->m_opcode)
  5190. {
  5191. case Js::OpCode::Ld_A:
  5192. case Js::OpCode::LdSlotArr:
  5193. case Js::OpCode::LdSlot:
  5194. // Allow only these op-codes for tracking the object sym's value transfer backwards. Other transfer op-codes
  5195. // could be included here if this function is used in scenarios that need them.
  5196. break;
  5197. default:
  5198. return nullptr;
  5199. }
  5200. // Try to get the property object's value from the src of the definition
  5201. IR::Opnd *const objectTransferSrc = objectSym->m_instrDef->GetSrc1();
  5202. if(!objectTransferSrc)
  5203. {
  5204. return nullptr;
  5205. }
  5206. if(objectTransferSrc->IsRegOpnd())
  5207. {
  5208. objectValue = FindValue(objectTransferSrc->AsRegOpnd()->m_sym);
  5209. }
  5210. else if(objectTransferSrc->IsSymOpnd())
  5211. {
  5212. Sym *const objectTransferSrcSym = objectTransferSrc->AsSymOpnd()->m_sym;
  5213. if(objectTransferSrcSym->IsStackSym())
  5214. {
  5215. objectValue = FindValue(objectTransferSrcSym);
  5216. }
  5217. else
  5218. {
  5219. // About to make a recursive call, so when jitting in the foreground, probe the stack
  5220. if(!func->IsBackgroundJIT())
  5221. {
  5222. PROBE_STACK(func->GetScriptContext(), Js::Constants::MinStackDefault);
  5223. }
  5224. objectValue = FindFuturePropertyValue(objectTransferSrcSym->AsPropertySym());
  5225. }
  5226. }
  5227. else
  5228. {
  5229. return nullptr;
  5230. }
  5231. if(!objectValue)
  5232. {
  5233. return nullptr;
  5234. }
  5235. }
  5236. // Try to use the property object's copy-prop sym and the property ID to find a mapped property sym, and get its value
  5237. StackSym *const objectCopyPropSym = GetCopyPropSym(nullptr, objectValue);
  5238. if(!objectCopyPropSym)
  5239. {
  5240. return nullptr;
  5241. }
  5242. PropertySym *const propertyCopyPropSym = PropertySym::Find(objectCopyPropSym->m_id, propertySym->m_propertyId, func);
  5243. if(!propertyCopyPropSym)
  5244. {
  5245. return nullptr;
  5246. }
  5247. return FindValue(propertyCopyPropSym);
  5248. }
  5249. Value *
  5250. GlobOpt::FindValueFromHashTable(GlobHashTable *valueNumberMap, SymID symId)
  5251. {
  5252. Value ** valuePtr = valueNumberMap->Get(symId);
  5253. if (valuePtr == nullptr)
  5254. {
  5255. return 0;
  5256. }
  5257. return (*valuePtr);
  5258. }
  5259. StackSym *
  5260. GlobOpt::GetCopyPropSym(Sym * sym, Value * value)
  5261. {
  5262. return GetCopyPropSym(this->currentBlock, sym, value);
  5263. }
  5264. StackSym *
  5265. GlobOpt::GetCopyPropSym(BasicBlock * block, Sym * sym, Value * value)
  5266. {
  5267. ValueInfo *valueInfo = value->GetValueInfo();
  5268. Sym * copySym = valueInfo->GetSymStore();
  5269. if (!copySym)
  5270. {
  5271. return nullptr;
  5272. }
  5273. // Only copy prop stackSym, as a propertySym wouldn't improve anything.
  5274. // SingleDef info isn't flow sensitive, so make sure the symbol is actually live.
  5275. if (copySym->IsStackSym() && copySym != sym)
  5276. {
  5277. Assert(!copySym->AsStackSym()->IsTypeSpec());
  5278. Value *copySymVal = this->FindValue(block->globOptData.symToValueMap, valueInfo->GetSymStore());
  5279. if (copySymVal && copySymVal->GetValueNumber() == value->GetValueNumber())
  5280. {
  5281. if (valueInfo->IsVarConstant() && !GlobOpt::IsLive(copySym, block))
  5282. {
  5283. // Because the addrConstantToValueMap isn't flow-based, the symStore of
  5284. // varConstants may not be live.
  5285. return nullptr;
  5286. }
  5287. return copySym->AsStackSym();
  5288. }
  5289. }
  5290. return nullptr;
  5291. }
  5292. // Constant prop if possible, otherwise if this value already resides in another
  5293. // symbol, reuse this previous symbol. This should help register allocation.
  5294. IR::Opnd *
  5295. GlobOpt::CopyProp(IR::Opnd *opnd, IR::Instr *instr, Value *val, IR::IndirOpnd *parentIndirOpnd)
  5296. {
  5297. Assert(
  5298. parentIndirOpnd
  5299. ? opnd == parentIndirOpnd->GetBaseOpnd() || opnd == parentIndirOpnd->GetIndexOpnd()
  5300. : opnd == instr->GetSrc1() || opnd == instr->GetSrc2() || opnd == instr->GetDst() && opnd->IsIndirOpnd());
  5301. if (this->IsLoopPrePass())
  5302. {
  5303. // Transformations are not legal in prepass...
  5304. return opnd;
  5305. }
  5306. if (!this->func->DoGlobOptsForGeneratorFunc())
  5307. {
  5308. // Don't copy prop in generator functions because non-bytecode temps that span a yield
  5309. // cannot be saved and restored by the current bail-out mechanics utilized by generator
  5310. // yield/resume.
  5311. // TODO[generators][ianhall]: Enable copy-prop at least for in between yields.
  5312. return opnd;
  5313. }
  5314. if (instr->m_opcode == Js::OpCode::CheckFixedFld || instr->m_opcode == Js::OpCode::CheckPropertyGuardAndLoadType)
  5315. {
  5316. // Don't copy prop into CheckFixedFld or CheckPropertyGuardAndLoadType
  5317. return opnd;
  5318. }
  5319. // Don't copy-prop link operands of ExtendedArgs
  5320. if (instr->m_opcode == Js::OpCode::ExtendArg_A && opnd == instr->GetSrc2())
  5321. {
  5322. return opnd;
  5323. }
  5324. // Don't copy-prop operand of SIMD instr with ExtendedArg operands. Each instr should have its exclusive EA sequence.
  5325. if (
  5326. Js::IsSimd128Opcode(instr->m_opcode) &&
  5327. instr->GetSrc1() != nullptr &&
  5328. instr->GetSrc1()->IsRegOpnd() &&
  5329. instr->GetSrc2() == nullptr
  5330. )
  5331. {
  5332. StackSym *sym = instr->GetSrc1()->GetStackSym();
  5333. if (sym && sym->IsSingleDef() && sym->GetInstrDef()->m_opcode == Js::OpCode::ExtendArg_A)
  5334. {
  5335. return opnd;
  5336. }
  5337. }
  5338. ValueInfo *valueInfo = val->GetValueInfo();
  5339. // Constant prop?
  5340. int32 intConstantValue;
  5341. if (valueInfo->TryGetIntConstantValue(&intConstantValue))
  5342. {
  5343. if (PHASE_OFF(Js::ConstPropPhase, this->func))
  5344. {
  5345. return opnd;
  5346. }
  5347. if ((
  5348. instr->m_opcode == Js::OpCode::StElemI_A ||
  5349. instr->m_opcode == Js::OpCode::StElemI_A_Strict ||
  5350. instr->m_opcode == Js::OpCode::StElemC
  5351. ) && instr->GetSrc1() == opnd)
  5352. {
  5353. // Disabling prop to src of native array store, because we were losing the chance to type specialize.
  5354. // Is it possible to type specialize this src if we allow constants, etc., to be prop'd here?
  5355. if (instr->GetDst()->AsIndirOpnd()->GetBaseOpnd()->GetValueType().IsLikelyNativeArray())
  5356. {
  5357. return opnd;
  5358. }
  5359. }
  5360. if(opnd != instr->GetSrc1() && opnd != instr->GetSrc2())
  5361. {
  5362. if(PHASE_OFF(Js::IndirCopyPropPhase, instr->m_func->GetJnFunction()))
  5363. {
  5364. return opnd;
  5365. }
  5366. // Const-prop an indir opnd's constant index into its offset
  5367. IR::Opnd *srcs[] = { instr->GetSrc1(), instr->GetSrc2(), instr->GetDst() };
  5368. for(int i = 0; i < sizeof(srcs) / sizeof(srcs[0]); ++i)
  5369. {
  5370. const auto src = srcs[i];
  5371. if(!src || !src->IsIndirOpnd())
  5372. {
  5373. continue;
  5374. }
  5375. const auto indir = src->AsIndirOpnd();
  5376. if(opnd == indir->GetIndexOpnd())
  5377. {
  5378. GOPT_TRACE_OPND(opnd, _u("Constant prop indir index into offset (value: %d)\n"), intConstantValue);
  5379. this->CaptureByteCodeSymUses(instr);
  5380. indir->SetOffset(intConstantValue);
  5381. indir->SetIndexOpnd(nullptr);
  5382. }
  5383. }
  5384. return opnd;
  5385. }
  5386. if (Js::TaggedInt::IsOverflow(intConstantValue))
  5387. {
  5388. return opnd;
  5389. }
  5390. IR::Opnd *constOpnd;
  5391. if (opnd->IsVar())
  5392. {
  5393. IR::AddrOpnd *addrOpnd = IR::AddrOpnd::New(Js::TaggedInt::ToVarUnchecked((int)intConstantValue), IR::AddrOpndKindConstantVar, instr->m_func);
  5394. GOPT_TRACE_OPND(opnd, _u("Constant prop %d (value:%d)\n"), addrOpnd->m_address, intConstantValue);
  5395. constOpnd = addrOpnd;
  5396. }
  5397. else
  5398. {
  5399. // Note: Jit loop body generates some i32 operands...
  5400. Assert(opnd->IsInt32() || opnd->IsInt64() || opnd->IsUInt32());
  5401. IRType opndType;
  5402. IntConstType constVal;
  5403. if (opnd->IsUInt32())
  5404. {
  5405. // avoid sign extension
  5406. constVal = (uint32)intConstantValue;
  5407. opndType = TyUint32;
  5408. }
  5409. else
  5410. {
  5411. constVal = intConstantValue;
  5412. opndType = TyInt32;
  5413. }
  5414. IR::IntConstOpnd *intOpnd = IR::IntConstOpnd::New(constVal, opndType, instr->m_func);
  5415. GOPT_TRACE_OPND(opnd, _u("Constant prop %d (value:%d)\n"), intOpnd->GetImmediateValue(), intConstantValue);
  5416. constOpnd = intOpnd;
  5417. }
  5418. #if ENABLE_DEBUG_CONFIG_OPTIONS
  5419. //Need to update DumpFieldCopyPropTestTrace for every new opcode that is added for fieldcopyprop
  5420. if(Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::FieldCopyPropPhase))
  5421. {
  5422. instr->DumpFieldCopyPropTestTrace();
  5423. }
  5424. #endif
  5425. this->CaptureByteCodeSymUses(instr);
  5426. opnd = instr->ReplaceSrc(opnd, constOpnd);
  5427. switch (instr->m_opcode)
  5428. {
  5429. case Js::OpCode::LdSlot:
  5430. case Js::OpCode::LdSlotArr:
  5431. case Js::OpCode::LdFld:
  5432. case Js::OpCode::LdFldForTypeOf:
  5433. case Js::OpCode::LdRootFldForTypeOf:
  5434. case Js::OpCode::LdFldForCallApplyTarget:
  5435. case Js::OpCode::LdRootFld:
  5436. case Js::OpCode::LdMethodFld:
  5437. case Js::OpCode::LdRootMethodFld:
  5438. case Js::OpCode::LdMethodFromFlags:
  5439. case Js::OpCode::ScopedLdMethodFld:
  5440. instr->m_opcode = Js::OpCode::Ld_A;
  5441. case Js::OpCode::Ld_A:
  5442. {
  5443. IR::Opnd * dst = instr->GetDst();
  5444. if (dst->IsRegOpnd() && dst->AsRegOpnd()->m_sym->IsSingleDef())
  5445. {
  5446. dst->AsRegOpnd()->m_sym->SetIsIntConst((int)intConstantValue);
  5447. }
  5448. break;
  5449. }
  5450. case Js::OpCode::ArgOut_A:
  5451. case Js::OpCode::ArgOut_A_Inline:
  5452. case Js::OpCode::ArgOut_A_FixupForStackArgs:
  5453. case Js::OpCode::ArgOut_A_InlineBuiltIn:
  5454. if (instr->GetDst()->IsRegOpnd())
  5455. {
  5456. Assert(instr->GetDst()->AsRegOpnd()->m_sym->m_isSingleDef);
  5457. instr->GetDst()->AsRegOpnd()->m_sym->AsStackSym()->SetIsIntConst((int)intConstantValue);
  5458. }
  5459. else
  5460. {
  5461. instr->GetDst()->AsSymOpnd()->m_sym->AsStackSym()->SetIsIntConst((int)intConstantValue);
  5462. }
  5463. break;
  5464. case Js::OpCode::TypeofElem:
  5465. instr->m_opcode = Js::OpCode::Typeof;
  5466. break;
  5467. case Js::OpCode::StSlotChkUndecl:
  5468. if (instr->GetSrc2() == opnd)
  5469. {
  5470. // Src2 here should refer to the same location as the Dst operand, which we need to keep live
  5471. // due to the implicit read for ChkUndecl.
  5472. instr->m_opcode = Js::OpCode::StSlot;
  5473. instr->FreeSrc2();
  5474. opnd = nullptr;
  5475. }
  5476. break;
  5477. }
  5478. return opnd;
  5479. }
  5480. Sym *opndSym = nullptr;
  5481. if (opnd->IsRegOpnd())
  5482. {
  5483. IR::RegOpnd *regOpnd = opnd->AsRegOpnd();
  5484. opndSym = regOpnd->m_sym;
  5485. }
  5486. else if (opnd->IsSymOpnd())
  5487. {
  5488. IR::SymOpnd *symOpnd = opnd->AsSymOpnd();
  5489. opndSym = symOpnd->m_sym;
  5490. }
  5491. if (!opndSym)
  5492. {
  5493. return opnd;
  5494. }
  5495. if (PHASE_OFF(Js::CopyPropPhase, this->func))
  5496. {
  5497. valueInfo->SetSymStore(opndSym);
  5498. return opnd;
  5499. }
  5500. // We should have dealt with field hoist already
  5501. Assert(!GlobOpt::TransferSrcValue(instr) || !opndSym->IsPropertySym() ||
  5502. !this->IsHoistedPropertySym(opndSym->AsPropertySym()));
  5503. StackSym *copySym = this->GetCopyPropSym(opndSym, val);
  5504. if (copySym != nullptr)
  5505. {
  5506. // Copy prop.
  5507. return CopyPropReplaceOpnd(instr, opnd, copySym, parentIndirOpnd);
  5508. }
  5509. else
  5510. {
  5511. if (valueInfo->GetSymStore() && instr->m_opcode == Js::OpCode::Ld_A && instr->GetDst()->IsRegOpnd()
  5512. && valueInfo->GetSymStore() == instr->GetDst()->AsRegOpnd()->m_sym)
  5513. {
  5514. // Avoid resetting symStore after fieldHoisting:
  5515. // t1 = LdFld field <- set symStore to fieldHoistSym
  5516. // fieldHoistSym = Ld_A t1 <- we're looking at t1 now, but want to copy-prop fieldHoistSym forward
  5517. return opnd;
  5518. }
  5519. valueInfo->SetSymStore(opndSym);
  5520. }
  5521. return opnd;
  5522. }
  5523. IR::Opnd *
  5524. GlobOpt::CopyPropReplaceOpnd(IR::Instr * instr, IR::Opnd * opnd, StackSym * copySym, IR::IndirOpnd *parentIndirOpnd)
  5525. {
  5526. Assert(
  5527. parentIndirOpnd
  5528. ? opnd == parentIndirOpnd->GetBaseOpnd() || opnd == parentIndirOpnd->GetIndexOpnd()
  5529. : opnd == instr->GetSrc1() || opnd == instr->GetSrc2() || opnd == instr->GetDst() && opnd->IsIndirOpnd());
  5530. Assert(GlobOpt::IsLive(copySym, this->currentBlock));
  5531. IR::RegOpnd *regOpnd;
  5532. StackSym *newSym = copySym;
  5533. GOPT_TRACE_OPND(opnd, _u("Copy prop s%d\n"), newSym->m_id);
  5534. #if ENABLE_DEBUG_CONFIG_OPTIONS
  5535. //Need to update DumpFieldCopyPropTestTrace for every new opcode that is added for fieldcopyprop
  5536. if(Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::FieldCopyPropPhase))
  5537. {
  5538. instr->DumpFieldCopyPropTestTrace();
  5539. }
  5540. #endif
  5541. this->CaptureByteCodeSymUses(instr);
  5542. if (opnd->IsRegOpnd())
  5543. {
  5544. regOpnd = opnd->AsRegOpnd();
  5545. regOpnd->m_sym = newSym;
  5546. regOpnd->SetIsJITOptimizedReg(true);
  5547. // The dead bit on the opnd is specific to the sym it is referencing. Since we replaced the sym, the bit is reset.
  5548. regOpnd->SetIsDead(false);
  5549. if(parentIndirOpnd)
  5550. {
  5551. return regOpnd;
  5552. }
  5553. }
  5554. else
  5555. {
  5556. // If this is an object type specialized field load inside a loop, and it produces a type value which wasn't live
  5557. // before, make sure the type check is left in the loop, because it may be the last type check in the loop protecting
  5558. // other fields which are not hoistable and are lexically upstream in the loop. If the check is not ultimately
  5559. // needed, the dead store pass will remove it.
  5560. if (this->currentBlock->loop != nullptr && opnd->IsSymOpnd() && opnd->AsSymOpnd()->IsPropertySymOpnd())
  5561. {
  5562. IR::PropertySymOpnd* propertySymOpnd = opnd->AsPropertySymOpnd();
  5563. if (CheckIfPropOpEmitsTypeCheck(instr, propertySymOpnd))
  5564. {
  5565. // We only set guarded properties in the dead store pass, so they shouldn't be set here yet. If they were
  5566. // we would need to move them from this operand to the operand which is being copy propagated.
  5567. Assert(propertySymOpnd->GetGuardedPropOps() == nullptr);
  5568. // We're creating a copy of this operand to be reused in the same spot in the flow, so we can copy all
  5569. // flow sensitive fields. However, we will do only a type check here (no property access) and only for
  5570. // the sake of downstream instructions, so the flags pertaining to this property access are irrelevant.
  5571. IR::PropertySymOpnd* checkObjTypeOpnd = propertySymOpnd->CopyForTypeCheckOnly(instr->m_func);
  5572. IR::Instr* checkObjTypeInstr = IR::Instr::New(Js::OpCode::CheckObjType, instr->m_func);
  5573. checkObjTypeInstr->SetSrc1(checkObjTypeOpnd);
  5574. checkObjTypeInstr->SetByteCodeOffset(instr);
  5575. instr->InsertBefore(checkObjTypeInstr);
  5576. // Since we inserted this instruction before the one that is being processed in natural flow, we must process
  5577. // it for object type spec explicitly here.
  5578. FinishOptPropOp(checkObjTypeInstr, checkObjTypeOpnd);
  5579. Assert(!propertySymOpnd->IsTypeChecked());
  5580. checkObjTypeInstr = this->SetTypeCheckBailOut(checkObjTypeOpnd, checkObjTypeInstr, nullptr);
  5581. Assert(checkObjTypeInstr->HasBailOutInfo());
  5582. if (this->currentBlock->loop && !this->IsLoopPrePass())
  5583. {
  5584. // Try hoisting this checkObjType.
  5585. // But since this isn't the current instr being optimized, we need to play tricks with
  5586. // the byteCodeUse fields...
  5587. BVSparse<JitArenaAllocator> *currentBytecodeUses = this->byteCodeUses;
  5588. PropertySym * currentPropertySymUse = this->propertySymUse;
  5589. PropertySym * tempPropertySymUse = NULL;
  5590. this->byteCodeUses = NULL;
  5591. BVSparse<JitArenaAllocator> *tempByteCodeUse = JitAnew(this->tempAlloc, BVSparse<JitArenaAllocator>, this->tempAlloc);
  5592. #if DBG
  5593. BVSparse<JitArenaAllocator> *currentBytecodeUsesBeforeOpt = this->byteCodeUsesBeforeOpt;
  5594. this->byteCodeUsesBeforeOpt = tempByteCodeUse;
  5595. #endif
  5596. this->propertySymUse = NULL;
  5597. GlobOpt::TrackByteCodeSymUsed(checkObjTypeInstr, tempByteCodeUse, &tempPropertySymUse);
  5598. TryHoistInvariant(checkObjTypeInstr, this->currentBlock, NULL, this->FindValue(copySym), NULL, true);
  5599. this->byteCodeUses = currentBytecodeUses;
  5600. this->propertySymUse = currentPropertySymUse;
  5601. #if DBG
  5602. this->byteCodeUsesBeforeOpt = currentBytecodeUsesBeforeOpt;
  5603. #endif
  5604. }
  5605. }
  5606. }
  5607. if (opnd->IsSymOpnd() && opnd->GetIsDead())
  5608. {
  5609. // Take the property sym out of the live fields set
  5610. this->EndFieldLifetime(opnd->AsSymOpnd());
  5611. }
  5612. regOpnd = IR::RegOpnd::New(newSym, opnd->GetType(), instr->m_func);
  5613. regOpnd->SetIsJITOptimizedReg(true);
  5614. instr->ReplaceSrc(opnd, regOpnd);
  5615. }
  5616. switch (instr->m_opcode)
  5617. {
  5618. case Js::OpCode::Ld_A:
  5619. if (instr->GetDst()->IsRegOpnd() && instr->GetSrc1()->IsRegOpnd() &&
  5620. instr->GetDst()->AsRegOpnd()->GetStackSym() == instr->GetSrc1()->AsRegOpnd()->GetStackSym())
  5621. {
  5622. this->InsertByteCodeUses(instr, true);
  5623. instr->m_opcode = Js::OpCode::Nop;
  5624. }
  5625. break;
  5626. case Js::OpCode::LdSlot:
  5627. case Js::OpCode::LdSlotArr:
  5628. if (instr->GetDst()->IsRegOpnd() && instr->GetSrc1()->IsRegOpnd() &&
  5629. instr->GetDst()->AsRegOpnd()->GetStackSym() == instr->GetSrc1()->AsRegOpnd()->GetStackSym())
  5630. {
  5631. this->InsertByteCodeUses(instr, true);
  5632. instr->m_opcode = Js::OpCode::Nop;
  5633. }
  5634. else
  5635. {
  5636. instr->m_opcode = Js::OpCode::Ld_A;
  5637. }
  5638. break;
  5639. case Js::OpCode::StSlotChkUndecl:
  5640. if (instr->GetSrc2()->IsRegOpnd())
  5641. {
  5642. // Src2 here should refer to the same location as the Dst operand, which we need to keep live
  5643. // due to the implicit read for ChkUndecl.
  5644. instr->m_opcode = Js::OpCode::StSlot;
  5645. instr->FreeSrc2();
  5646. return nullptr;
  5647. }
  5648. break;
  5649. case Js::OpCode::LdFld:
  5650. case Js::OpCode::LdFldForTypeOf:
  5651. case Js::OpCode::LdRootFldForTypeOf:
  5652. case Js::OpCode::LdFldForCallApplyTarget:
  5653. case Js::OpCode::LdRootFld:
  5654. case Js::OpCode::LdMethodFld:
  5655. case Js::OpCode::LdRootMethodFld:
  5656. case Js::OpCode::ScopedLdMethodFld:
  5657. instr->m_opcode = Js::OpCode::Ld_A;
  5658. break;
  5659. case Js::OpCode::LdMethodFromFlags:
  5660. // The bailout is checked on the loop top and we don't need to check bailout again in loop.
  5661. instr->m_opcode = Js::OpCode::Ld_A;
  5662. instr->ClearBailOutInfo();
  5663. break;
  5664. case Js::OpCode::TypeofElem:
  5665. instr->m_opcode = Js::OpCode::Typeof;
  5666. break;
  5667. }
  5668. this->MarkTempLastUse(instr, regOpnd);
  5669. return regOpnd;
  5670. }
  5671. void
  5672. GlobOpt::MarkTempLastUse(IR::Instr *instr, IR::RegOpnd *regOpnd)
  5673. {
  5674. if (OpCodeAttr::NonTempNumberSources(instr->m_opcode))
  5675. {
  5676. // Turn off bit if opcode could cause the src to be aliased.
  5677. this->blockData.isTempSrc->Clear(regOpnd->m_sym->m_id);
  5678. }
  5679. else if (this->blockData.isTempSrc->Test(regOpnd->m_sym->m_id))
  5680. {
  5681. // We just mark things that are temp in the globopt phase.
  5682. // The backwards phase will turn this off if it is not the last use.
  5683. // The isTempSrc is freed at the end of each block, which is why the backwards phase can't
  5684. // just use it.
  5685. if (!PHASE_OFF(Js::BackwardPhase, this->func) && !this->IsLoopPrePass())
  5686. {
  5687. regOpnd->m_isTempLastUse = true;
  5688. }
  5689. }
  5690. }
  5691. ValueNumber
  5692. GlobOpt::NewValueNumber()
  5693. {
  5694. ValueNumber valueNumber = this->currentValue++;
  5695. if (valueNumber == 0)
  5696. {
  5697. Js::Throw::OutOfMemory();
  5698. }
  5699. return valueNumber;
  5700. }
  5701. Value *GlobOpt::NewValue(ValueInfo *const valueInfo)
  5702. {
  5703. return NewValue(NewValueNumber(), valueInfo);
  5704. }
  5705. Value *GlobOpt::NewValue(const ValueNumber valueNumber, ValueInfo *const valueInfo)
  5706. {
  5707. Assert(valueInfo);
  5708. return Value::New(alloc, valueNumber, valueInfo);
  5709. }
  5710. Value *GlobOpt::CopyValue(Value *const value)
  5711. {
  5712. return CopyValue(value, NewValueNumber());
  5713. }
  5714. Value *GlobOpt::CopyValue(Value *const value, const ValueNumber valueNumber)
  5715. {
  5716. Assert(value);
  5717. return value->Copy(alloc, valueNumber);
  5718. }
  5719. Value *
  5720. GlobOpt::NewGenericValue(const ValueType valueType)
  5721. {
  5722. return NewGenericValue(valueType, static_cast<IR::Opnd *>(nullptr));
  5723. }
  5724. Value *
  5725. GlobOpt::NewGenericValue(const ValueType valueType, IR::Opnd *const opnd)
  5726. {
  5727. // Shouldn't assign a likely-int value to something that is definitely not an int
  5728. Assert(!(valueType.IsLikelyInt() && opnd && opnd->IsRegOpnd() && opnd->AsRegOpnd()->m_sym->m_isNotInt));
  5729. ValueInfo *valueInfo = ValueInfo::New(this->alloc, valueType);
  5730. Value *val = NewValue(valueInfo);
  5731. TrackNewValueForKills(val);
  5732. this->InsertNewValue(val, opnd);
  5733. return val;
  5734. }
  5735. Value *
  5736. GlobOpt::NewGenericValue(const ValueType valueType, Sym *const sym)
  5737. {
  5738. ValueInfo *valueInfo = ValueInfo::New(this->alloc, valueType);
  5739. Value *val = NewValue(valueInfo);
  5740. TrackNewValueForKills(val);
  5741. this->SetValue(&this->blockData, val, sym);
  5742. return val;
  5743. }
  5744. Value *
  5745. GlobOpt::GetIntConstantValue(const int32 intConst, IR::Instr * instr, IR::Opnd *const opnd)
  5746. {
  5747. Value *value = nullptr;
  5748. Value *const cachedValue = this->intConstantToValueMap->Lookup(intConst, nullptr);
  5749. if(cachedValue)
  5750. {
  5751. // The cached value could be from a different block since this is a global (as opposed to a per-block) cache. Since
  5752. // values are cloned for each block, we can't use the same value object. We also can't have two values with the same
  5753. // number in one block, so we can't simply copy the cached value either. And finally, there is no deterministic and fast
  5754. // way to determine if a value with the same value number exists for this block. So the best we can do with a global
  5755. // cache is to check the sym-store's value in the current block to see if it has a value with the same number.
  5756. // Otherwise, we have to create a new value with a new value number.
  5757. Sym *const symStore = cachedValue->GetValueInfo()->GetSymStore();
  5758. if (symStore && IsLive(symStore, &blockData))
  5759. {
  5760. Value *const symStoreValue = FindValue(symStore);
  5761. int32 symStoreIntConstantValue;
  5762. if (symStoreValue &&
  5763. symStoreValue->GetValueNumber() == cachedValue->GetValueNumber() &&
  5764. symStoreValue->GetValueInfo()->TryGetIntConstantValue(&symStoreIntConstantValue) &&
  5765. symStoreIntConstantValue == intConst)
  5766. {
  5767. value = symStoreValue;
  5768. }
  5769. }
  5770. }
  5771. if (!value)
  5772. {
  5773. value = NewIntConstantValue(intConst, instr, !Js::TaggedInt::IsOverflow(intConst));
  5774. }
  5775. return this->InsertNewValue(value, opnd);
  5776. }
  5777. Value *
  5778. GlobOpt::NewIntConstantValue(const int32 intConst, IR::Instr * instr, bool isTaggable)
  5779. {
  5780. Value * value = NewValue(IntConstantValueInfo::New(this->alloc, intConst));
  5781. this->intConstantToValueMap->Item(intConst, value);
  5782. if (isTaggable &&
  5783. !PHASE_OFF(Js::HoistConstIntPhase, this->func))
  5784. {
  5785. // When creating a new int constant value, make sure it gets a symstore. If the int const doesn't have a symstore,
  5786. // any downstream instruction using the same int will have to create a new value (object) for the int.
  5787. // This gets in the way of CSE.
  5788. value = HoistConstantLoadAndPropagateValueBackward(Js::TaggedInt::ToVarUnchecked(intConst), instr, value);
  5789. if (!value->GetValueInfo()->GetSymStore() &&
  5790. instr->m_opcode == Js::OpCode::LdC_A_I4 || instr->m_opcode == Js::OpCode::Ld_I4)
  5791. {
  5792. StackSym * sym = instr->GetDst()->GetStackSym();
  5793. Assert(sym);
  5794. if (sym->IsTypeSpec())
  5795. {
  5796. Assert(sym->IsInt32());
  5797. StackSym * varSym = sym->GetVarEquivSym(instr->m_func);
  5798. SetValue(&this->currentBlock->globOptData, value, varSym);
  5799. this->currentBlock->globOptData.liveInt32Syms->Set(varSym->m_id);
  5800. }
  5801. else
  5802. {
  5803. SetValue(&this->currentBlock->globOptData, value, sym);
  5804. this->currentBlock->globOptData.liveVarSyms->Set(sym->m_id);
  5805. }
  5806. }
  5807. }
  5808. return value;
  5809. }
  5810. ValueInfo *
  5811. GlobOpt::NewIntRangeValueInfo(const int32 min, const int32 max, const bool wasNegativeZeroPreventedByBailout)
  5812. {
  5813. if (min == max)
  5814. {
  5815. // Since int constant values are const-propped, negative zero tracking does not track them, and so it's okay to ignore
  5816. // 'wasNegativeZeroPreventedByBailout'
  5817. return IntConstantValueInfo::New(this->alloc, max);
  5818. }
  5819. return IntRangeValueInfo::New(this->alloc, min, max, wasNegativeZeroPreventedByBailout);
  5820. }
  5821. ValueInfo *GlobOpt::NewIntRangeValueInfo(
  5822. const ValueInfo *const originalValueInfo,
  5823. const int32 min,
  5824. const int32 max) const
  5825. {
  5826. Assert(originalValueInfo);
  5827. ValueInfo *valueInfo;
  5828. if(min == max)
  5829. {
  5830. // Since int constant values are const-propped, negative zero tracking does not track them, and so it's okay to ignore
  5831. // 'wasNegativeZeroPreventedByBailout'
  5832. valueInfo = IntConstantValueInfo::New(alloc, min);
  5833. }
  5834. else
  5835. {
  5836. valueInfo =
  5837. IntRangeValueInfo::New(
  5838. alloc,
  5839. min,
  5840. max,
  5841. min <= 0 && max >= 0 && originalValueInfo->WasNegativeZeroPreventedByBailout());
  5842. }
  5843. valueInfo->SetSymStore(originalValueInfo->GetSymStore());
  5844. return valueInfo;
  5845. }
  5846. Value *
  5847. GlobOpt::NewIntRangeValue(
  5848. const int32 min,
  5849. const int32 max,
  5850. const bool wasNegativeZeroPreventedByBailout,
  5851. IR::Opnd *const opnd)
  5852. {
  5853. ValueInfo *valueInfo = this->NewIntRangeValueInfo(min, max, wasNegativeZeroPreventedByBailout);
  5854. Value *val = NewValue(valueInfo);
  5855. if (opnd)
  5856. {
  5857. GOPT_TRACE_OPND(opnd, _u("Range %d (0x%X) to %d (0x%X)\n"), min, min, max, max);
  5858. }
  5859. this->InsertNewValue(val, opnd);
  5860. return val;
  5861. }
  5862. IntBoundedValueInfo *GlobOpt::NewIntBoundedValueInfo(
  5863. const ValueInfo *const originalValueInfo,
  5864. const IntBounds *const bounds) const
  5865. {
  5866. Assert(originalValueInfo);
  5867. bounds->Verify();
  5868. IntBoundedValueInfo *const valueInfo =
  5869. IntBoundedValueInfo::New(
  5870. originalValueInfo->Type(),
  5871. bounds,
  5872. (
  5873. bounds->ConstantLowerBound() <= 0 &&
  5874. bounds->ConstantUpperBound() >= 0 &&
  5875. originalValueInfo->WasNegativeZeroPreventedByBailout()
  5876. ),
  5877. alloc);
  5878. valueInfo->SetSymStore(originalValueInfo->GetSymStore());
  5879. return valueInfo;
  5880. }
  5881. Value *GlobOpt::NewIntBoundedValue(
  5882. const ValueType valueType,
  5883. const IntBounds *const bounds,
  5884. const bool wasNegativeZeroPreventedByBailout,
  5885. IR::Opnd *const opnd)
  5886. {
  5887. Value *const value = NewValue(IntBoundedValueInfo::New(valueType, bounds, wasNegativeZeroPreventedByBailout, alloc));
  5888. InsertNewValue(value, opnd);
  5889. return value;
  5890. }
  5891. Value *
  5892. GlobOpt::NewFloatConstantValue(const FloatConstType floatValue, IR::Opnd *const opnd)
  5893. {
  5894. FloatConstantValueInfo *valueInfo = FloatConstantValueInfo::New(this->alloc, floatValue);
  5895. Value *val = NewValue(valueInfo);
  5896. this->InsertNewValue(val, opnd);
  5897. return val;
  5898. }
  5899. Value *
  5900. GlobOpt::GetVarConstantValue(IR::AddrOpnd *addrOpnd)
  5901. {
  5902. bool isVar = addrOpnd->IsVar();
  5903. bool isString = isVar && Js::JavascriptString::Is(addrOpnd->m_address);
  5904. Value *val = nullptr;
  5905. Value *cachedValue;
  5906. if(this->addrConstantToValueMap->TryGetValue(addrOpnd->m_address, &cachedValue))
  5907. {
  5908. // The cached value could be from a different block since this is a global (as opposed to a per-block) cache. Since
  5909. // values are cloned for each block, we can't use the same value object. We also can't have two values with the same
  5910. // number in one block, so we can't simply copy the cached value either. And finally, there is no deterministic and fast
  5911. // way to determine if a value with the same value number exists for this block. So the best we can do with a global
  5912. // cache is to check the sym-store's value in the current block to see if it has a value with the same number.
  5913. // Otherwise, we have to create a new value with a new value number.
  5914. Sym *symStore = cachedValue->GetValueInfo()->GetSymStore();
  5915. if(symStore && IsLive(symStore, &blockData))
  5916. {
  5917. Value *const symStoreValue = FindValue(symStore);
  5918. if(symStoreValue && symStoreValue->GetValueNumber() == cachedValue->GetValueNumber())
  5919. {
  5920. ValueInfo *const symStoreValueInfo = symStoreValue->GetValueInfo();
  5921. if(symStoreValueInfo->IsVarConstant() && symStoreValueInfo->AsVarConstant()->VarValue() == addrOpnd->m_address)
  5922. {
  5923. val = symStoreValue;
  5924. }
  5925. }
  5926. }
  5927. }
  5928. else if (isString)
  5929. {
  5930. Js::JavascriptString* jsString = Js::JavascriptString::FromVar(addrOpnd->m_address);
  5931. Js::InternalString internalString(jsString->GetString(), jsString->GetLength());
  5932. if (this->stringConstantToValueMap->TryGetValue(internalString, &cachedValue))
  5933. {
  5934. Sym *symStore = cachedValue->GetValueInfo()->GetSymStore();
  5935. if (symStore && IsLive(symStore, &blockData))
  5936. {
  5937. Value *const symStoreValue = FindValue(symStore);
  5938. if (symStoreValue && symStoreValue->GetValueNumber() == cachedValue->GetValueNumber())
  5939. {
  5940. ValueInfo *const symStoreValueInfo = symStoreValue->GetValueInfo();
  5941. if (symStoreValueInfo->IsVarConstant())
  5942. {
  5943. Js::JavascriptString * cachedString = Js::JavascriptString::FromVar(symStoreValue->GetValueInfo()->AsVarConstant()->VarValue());
  5944. Js::InternalString cachedInternalString(cachedString->GetString(), cachedString->GetLength());
  5945. if (Js::InternalStringComparer::Equals(internalString, cachedInternalString))
  5946. {
  5947. val = symStoreValue;
  5948. }
  5949. }
  5950. }
  5951. }
  5952. }
  5953. }
  5954. if(!val)
  5955. {
  5956. val = NewVarConstantValue(addrOpnd, isString);
  5957. }
  5958. addrOpnd->SetValueType(val->GetValueInfo()->Type());
  5959. return val;
  5960. }
  5961. Value *
  5962. GlobOpt::NewVarConstantValue(IR::AddrOpnd *addrOpnd, bool isString)
  5963. {
  5964. VarConstantValueInfo *valueInfo = VarConstantValueInfo::New(this->alloc, addrOpnd->m_address, addrOpnd->GetValueType());
  5965. Value * value = NewValue(valueInfo);
  5966. this->addrConstantToValueMap->Item(addrOpnd->m_address, value);
  5967. if (isString)
  5968. {
  5969. Js::JavascriptString* jsString = Js::JavascriptString::FromVar(addrOpnd->m_address);
  5970. Js::InternalString internalString(jsString->GetString(), jsString->GetLength());
  5971. this->stringConstantToValueMap->Item(internalString, value);
  5972. }
  5973. return value;
  5974. }
  5975. Value *
  5976. GlobOpt::HoistConstantLoadAndPropagateValueBackward(Js::Var varConst, IR::Instr * origInstr, Value * value)
  5977. {
  5978. if (this->IsLoopPrePass() ||
  5979. ((this->currentBlock == this->func->m_fg->blockList) &&
  5980. TransferSrcValue(origInstr)))
  5981. {
  5982. return value;
  5983. }
  5984. // Only hoisting taggable int const loads for now. Could be extended to other constants (floats, strings, addr opnds) if we see some benefit.
  5985. Assert(Js::TaggedInt::Is(varConst));
  5986. // Insert a load of the constant at the top of the function
  5987. StackSym * dstSym = StackSym::New(this->func);
  5988. IR::RegOpnd * constRegOpnd = IR::RegOpnd::New(dstSym, TyVar, this->func);
  5989. IR::Instr * loadInstr = IR::Instr::NewConstantLoad(constRegOpnd, varConst, this->func);
  5990. this->func->m_fg->blockList->GetFirstInstr()->InsertAfter(loadInstr);
  5991. // Type-spec the load (Support for floats needs to be added when we start hoisting float constants).
  5992. bool typeSpecedToInt = false;
  5993. if (Js::TaggedInt::Is(varConst) && !IsTypeSpecPhaseOff(this->func))
  5994. {
  5995. typeSpecedToInt = true;
  5996. loadInstr->m_opcode = Js::OpCode::Ld_I4;
  5997. ToInt32Dst(loadInstr, loadInstr->GetDst()->AsRegOpnd(), this->currentBlock);
  5998. loadInstr->GetDst()->GetStackSym()->SetIsConst();
  5999. }
  6000. else
  6001. {
  6002. this->currentBlock->globOptData.liveVarSyms->Set(dstSym->m_id);
  6003. }
  6004. // Add the value (object) to the current block's symToValueMap and propagate the value backward to all relevant blocks so it is available on merges.
  6005. value = this->InsertNewValue(value, constRegOpnd);
  6006. BVSparse<JitArenaAllocator>* GlobOptBlockData::*bv;
  6007. bv = typeSpecedToInt ? &GlobOptBlockData::liveInt32Syms : &GlobOptBlockData::liveVarSyms; // Will need to be expanded when we start hoisting float constants.
  6008. if (this->currentBlock != this->func->m_fg->blockList)
  6009. {
  6010. for (InvariantBlockBackwardIterator it(this, this->currentBlock, this->func->m_fg->blockList, nullptr);
  6011. it.IsValid();
  6012. it.MoveNext())
  6013. {
  6014. BasicBlock * block = it.Block();
  6015. (block->globOptData.*bv)->Set(dstSym->m_id);
  6016. Assert(!FindValue(block->globOptData.symToValueMap, dstSym));
  6017. Value *const valueCopy = CopyValue(value, value->GetValueNumber());
  6018. SetValue(&block->globOptData, valueCopy, dstSym);
  6019. }
  6020. }
  6021. return value;
  6022. }
  6023. Value *
  6024. GlobOpt::NewFixedFunctionValue(Js::JavascriptFunction *function, IR::AddrOpnd *addrOpnd)
  6025. {
  6026. Assert(function != nullptr);
  6027. Value *val = nullptr;
  6028. Value *cachedValue;
  6029. if(this->addrConstantToValueMap->TryGetValue(addrOpnd->m_address, &cachedValue))
  6030. {
  6031. // The cached value could be from a different block since this is a global (as opposed to a per-block) cache. Since
  6032. // values are cloned for each block, we can't use the same value object. We also can't have two values with the same
  6033. // number in one block, so we can't simply copy the cached value either. And finally, there is no deterministic and fast
  6034. // way to determine if a value with the same value number exists for this block. So the best we can do with a global
  6035. // cache is to check the sym-store's value in the current block to see if it has a value with the same number.
  6036. // Otherwise, we have to create a new value with a new value number.
  6037. Sym *symStore = cachedValue->GetValueInfo()->GetSymStore();
  6038. if(symStore && IsLive(symStore, &blockData))
  6039. {
  6040. Value *const symStoreValue = FindValue(symStore);
  6041. if(symStoreValue && symStoreValue->GetValueNumber() == cachedValue->GetValueNumber())
  6042. {
  6043. ValueInfo *const symStoreValueInfo = symStoreValue->GetValueInfo();
  6044. if(symStoreValueInfo->IsVarConstant())
  6045. {
  6046. VarConstantValueInfo *const symStoreVarConstantValueInfo = symStoreValueInfo->AsVarConstant();
  6047. if(symStoreVarConstantValueInfo->VarValue() == addrOpnd->m_address &&
  6048. symStoreVarConstantValueInfo->IsFunction())
  6049. {
  6050. val = symStoreValue;
  6051. }
  6052. }
  6053. }
  6054. }
  6055. }
  6056. if(!val)
  6057. {
  6058. VarConstantValueInfo *valueInfo = VarConstantValueInfo::New(this->alloc, function, addrOpnd->GetValueType(), true);
  6059. val = NewValue(valueInfo);
  6060. this->addrConstantToValueMap->AddNew(addrOpnd->m_address, val);
  6061. }
  6062. this->InsertNewValue(val, addrOpnd);
  6063. return val;
  6064. }
  6065. Value *
  6066. GlobOpt::InsertNewValue(Value *val, IR::Opnd *opnd)
  6067. {
  6068. return this->InsertNewValue(&this->blockData, val, opnd);
  6069. }
  6070. Value *
  6071. GlobOpt::InsertNewValue(GlobOptBlockData *blockData, Value *val, IR::Opnd *opnd)
  6072. {
  6073. return this->SetValue(blockData, val, opnd);
  6074. }
  6075. void
  6076. GlobOpt::SetValueToHashTable(GlobHashTable *valueNumberMap, Value *val, Sym *sym)
  6077. {
  6078. Value **pValue = valueNumberMap->FindOrInsertNew(sym);
  6079. *pValue = val;
  6080. }
  6081. StackSym *GlobOpt::GetTaggedIntConstantStackSym(const int32 intConstantValue) const
  6082. {
  6083. Assert(!Js::TaggedInt::IsOverflow(intConstantValue));
  6084. return intConstantToStackSymMap->Lookup(intConstantValue, nullptr);
  6085. }
  6086. StackSym *GlobOpt::GetOrCreateTaggedIntConstantStackSym(const int32 intConstantValue) const
  6087. {
  6088. StackSym *stackSym = GetTaggedIntConstantStackSym(intConstantValue);
  6089. if(stackSym)
  6090. {
  6091. return stackSym;
  6092. }
  6093. stackSym = StackSym::New(TyVar,func);
  6094. intConstantToStackSymMap->Add(intConstantValue, stackSym);
  6095. return stackSym;
  6096. }
  6097. Sym *
  6098. GlobOpt::SetSymStore(ValueInfo *valueInfo, Sym *sym)
  6099. {
  6100. if (sym->IsStackSym())
  6101. {
  6102. StackSym *stackSym = sym->AsStackSym();
  6103. if (stackSym->IsTypeSpec())
  6104. {
  6105. stackSym = stackSym->GetVarEquivSym(this->func);
  6106. sym = stackSym;
  6107. }
  6108. }
  6109. if (valueInfo->GetSymStore() == nullptr || valueInfo->GetSymStore()->IsPropertySym())
  6110. {
  6111. valueInfo->SetSymStore(sym);
  6112. }
  6113. return sym;
  6114. }
  6115. void
  6116. GlobOpt::SetValue(GlobOptBlockData *blockData, Value *val, Sym * sym)
  6117. {
  6118. ValueInfo *valueInfo = val->GetValueInfo();
  6119. sym = this->SetSymStore(valueInfo, sym);
  6120. if (sym->IsStackSym() && sym->AsStackSym()->IsFromByteCodeConstantTable())
  6121. {
  6122. // Put the constants in a global array. This will minimize the per-block info.
  6123. this->byteCodeConstantValueArray->Set(sym->m_id, val);
  6124. this->byteCodeConstantValueNumbersBv->Set(val->GetValueNumber());
  6125. }
  6126. else
  6127. {
  6128. SetValueToHashTable(blockData->symToValueMap, val, sym);
  6129. }
  6130. }
  6131. Value *
  6132. GlobOpt::SetValue(GlobOptBlockData *blockData, Value *val, IR::Opnd *opnd)
  6133. {
  6134. if (opnd)
  6135. {
  6136. Sym *sym;
  6137. switch (opnd->GetKind())
  6138. {
  6139. case IR::OpndKindSym:
  6140. sym = opnd->AsSymOpnd()->m_sym;
  6141. break;
  6142. case IR::OpndKindReg:
  6143. sym = opnd->AsRegOpnd()->m_sym;
  6144. break;
  6145. default:
  6146. sym = nullptr;
  6147. }
  6148. if (sym)
  6149. {
  6150. SetValue(blockData, val, sym);
  6151. }
  6152. }
  6153. return val;
  6154. }
  6155. // Figure out the Value of this dst.
  6156. Value *
  6157. GlobOpt::ValueNumberDst(IR::Instr **pInstr, Value *src1Val, Value *src2Val)
  6158. {
  6159. IR::Instr *&instr = *pInstr;
  6160. IR::Opnd *dst = instr->GetDst();
  6161. Value *dstVal = nullptr;
  6162. Sym *sym;
  6163. if (instr->CallsSetter())
  6164. {
  6165. return nullptr;
  6166. }
  6167. if (dst == nullptr)
  6168. {
  6169. return nullptr;
  6170. }
  6171. switch (dst->GetKind())
  6172. {
  6173. case IR::OpndKindSym:
  6174. sym = dst->AsSymOpnd()->m_sym;
  6175. break;
  6176. case IR::OpndKindReg:
  6177. sym = dst->AsRegOpnd()->m_sym;
  6178. if (OpCodeAttr::TempNumberProducing(instr->m_opcode))
  6179. {
  6180. this->blockData.isTempSrc->Set(sym->m_id);
  6181. }
  6182. else if (OpCodeAttr::TempNumberTransfer(instr->m_opcode))
  6183. {
  6184. IR::Opnd *src1 = instr->GetSrc1();
  6185. if (src1->IsRegOpnd() && this->blockData.isTempSrc->Test(src1->AsRegOpnd()->m_sym->m_id))
  6186. {
  6187. StackSym *src1Sym = src1->AsRegOpnd()->m_sym;
  6188. // isTempSrc is used for marking isTempLastUse, which is used to generate AddLeftDead()
  6189. // calls instead of the normal Add helpers. It tells the runtime that concats can use string
  6190. // builders.
  6191. // We need to be careful in the case where src1 points to a string builder and is getting aliased.
  6192. // Clear the bit on src and dst of the transfer instr in this case, unless we can prove src1
  6193. // isn't pointing at a string builder, like if it is single def and the def instr is not an Add,
  6194. // but TempProducing.
  6195. if (src1Sym->IsSingleDef() && src1Sym->m_instrDef->m_opcode != Js::OpCode::Add_A
  6196. && OpCodeAttr::TempNumberProducing(src1Sym->m_instrDef->m_opcode))
  6197. {
  6198. this->blockData.isTempSrc->Set(sym->m_id);
  6199. }
  6200. else
  6201. {
  6202. this->blockData.isTempSrc->Clear(src1->AsRegOpnd()->m_sym->m_id);
  6203. this->blockData.isTempSrc->Clear(sym->m_id);
  6204. }
  6205. }
  6206. else
  6207. {
  6208. this->blockData.isTempSrc->Clear(sym->m_id);
  6209. }
  6210. }
  6211. else
  6212. {
  6213. this->blockData.isTempSrc->Clear(sym->m_id);
  6214. }
  6215. break;
  6216. case IR::OpndKindIndir:
  6217. return nullptr;
  6218. default:
  6219. return nullptr;
  6220. }
  6221. int32 min1, max1, min2, max2, newMin, newMax;
  6222. ValueInfo *src1ValueInfo = (src1Val ? src1Val->GetValueInfo() : nullptr);
  6223. ValueInfo *src2ValueInfo = (src2Val ? src2Val->GetValueInfo() : nullptr);
  6224. switch (instr->m_opcode)
  6225. {
  6226. case Js::OpCode::Conv_PrimStr:
  6227. AssertMsg(instr->GetDst()->GetValueType().IsString(),
  6228. "Creator of this instruction should have set the type");
  6229. if (this->IsLoopPrePass() || src1ValueInfo == nullptr || !src1ValueInfo->IsPrimitive())
  6230. {
  6231. break;
  6232. }
  6233. instr->m_opcode = Js::OpCode::Conv_Str;
  6234. // fall-through
  6235. case Js::OpCode::Conv_Str:
  6236. // This opcode is commented out since we don't track regex information in GlobOpt now.
  6237. //case Js::OpCode::Coerse_Regex:
  6238. case Js::OpCode::Coerse_Str:
  6239. AssertMsg(instr->GetDst()->GetValueType().IsString(),
  6240. "Creator of this instruction should have set the type");
  6241. // fall-through
  6242. case Js::OpCode::Coerse_StrOrRegex:
  6243. // We don't set the ValueType of src1 for Coerse_StrOrRegex, hence skip the ASSERT
  6244. if (this->IsLoopPrePass() || src1ValueInfo == nullptr || !src1ValueInfo->IsString())
  6245. {
  6246. break;
  6247. }
  6248. instr->m_opcode = Js::OpCode::Ld_A;
  6249. // fall-through
  6250. case Js::OpCode::BytecodeArgOutCapture:
  6251. case Js::OpCode::InitConst:
  6252. case Js::OpCode::Ld_A:
  6253. case Js::OpCode::Ld_I4:
  6254. // Propagate sym attributes across the reg copy.
  6255. if (!this->IsLoopPrePass() && instr->GetSrc1()->IsRegOpnd())
  6256. {
  6257. if (dst->AsRegOpnd()->m_sym->IsSingleDef())
  6258. {
  6259. dst->AsRegOpnd()->m_sym->CopySymAttrs(instr->GetSrc1()->AsRegOpnd()->m_sym);
  6260. }
  6261. }
  6262. if (instr->IsProfiledInstr())
  6263. {
  6264. const ValueType profiledValueType(instr->AsProfiledInstr()->u.FldInfo().valueType);
  6265. if(!(
  6266. profiledValueType.IsLikelyInt() &&
  6267. (
  6268. dst->IsRegOpnd() && dst->AsRegOpnd()->m_sym->m_isNotInt ||
  6269. instr->GetSrc1()->IsRegOpnd() && instr->GetSrc1()->AsRegOpnd()->m_sym->m_isNotInt
  6270. )
  6271. ))
  6272. {
  6273. if(!src1ValueInfo)
  6274. {
  6275. dstVal = this->NewGenericValue(profiledValueType, dst);
  6276. }
  6277. else if(src1ValueInfo->IsUninitialized())
  6278. {
  6279. if(IsLoopPrePass())
  6280. {
  6281. dstVal = this->NewGenericValue(profiledValueType, dst);
  6282. }
  6283. else
  6284. {
  6285. // Assuming the profile data gives more precise value types based on the path it took at runtime, we
  6286. // can improve the original value type.
  6287. src1ValueInfo->Type() = profiledValueType;
  6288. instr->GetSrc1()->SetValueType(profiledValueType);
  6289. }
  6290. }
  6291. }
  6292. }
  6293. if (dstVal == nullptr)
  6294. {
  6295. // Ld_A is just transferring the value
  6296. dstVal = this->ValueNumberTransferDst(instr, src1Val);
  6297. }
  6298. break;
  6299. case Js::OpCode::ExtendArg_A:
  6300. {
  6301. // SIMD_JS
  6302. // We avoid transforming EAs to Lds to keep the IR shape consistent and avoid CSEing of EAs.
  6303. // CSEOptimize only assigns a Value to the EA dst, and doesn't turn it to a Ld. If this happened, we shouldn't assign a new Value here.
  6304. if (DoCSE())
  6305. {
  6306. IR::Opnd *dst = instr->GetDst();
  6307. Value *dstVal = this->FindValue(dst->GetStackSym());
  6308. if (dstVal != nullptr)
  6309. {
  6310. return dstVal;
  6311. }
  6312. }
  6313. break;
  6314. }
  6315. case Js::OpCode::CheckFixedFld:
  6316. AssertMsg(false, "CheckFixedFld doesn't have a dst, so we should never get here");
  6317. break;
  6318. case Js::OpCode::LdSlot:
  6319. case Js::OpCode::LdSlotArr:
  6320. case Js::OpCode::LdFld:
  6321. case Js::OpCode::LdFldForTypeOf:
  6322. case Js::OpCode::LdFldForCallApplyTarget:
  6323. // Do not transfer value type on ldFldForTypeOf to prevent copy-prop to LdRootFld in case the field doesn't exist since LdRootFldForTypeOf does not throw
  6324. //case Js::OpCode::LdRootFldForTypeOf:
  6325. case Js::OpCode::LdRootFld:
  6326. case Js::OpCode::LdMethodFld:
  6327. case Js::OpCode::LdRootMethodFld:
  6328. case Js::OpCode::ScopedLdMethodFld:
  6329. case Js::OpCode::LdMethodFromFlags:
  6330. if (instr->IsProfiledInstr())
  6331. {
  6332. ValueType profiledValueType(instr->AsProfiledInstr()->u.FldInfo().valueType);
  6333. if(!(profiledValueType.IsLikelyInt() && dst->IsRegOpnd() && dst->AsRegOpnd()->m_sym->m_isNotInt))
  6334. {
  6335. if(!src1ValueInfo)
  6336. {
  6337. dstVal = this->NewGenericValue(profiledValueType, dst);
  6338. }
  6339. else if(src1ValueInfo->IsUninitialized())
  6340. {
  6341. if(IsLoopPrePass() && (!dst->IsRegOpnd() || !dst->AsRegOpnd()->m_sym->IsSingleDef() || DoFieldHoisting()))
  6342. {
  6343. dstVal = this->NewGenericValue(profiledValueType, dst);
  6344. }
  6345. else
  6346. {
  6347. // Assuming the profile data gives more precise value types based on the path it took at runtime, we
  6348. // can improve the original value type.
  6349. src1ValueInfo->Type() = profiledValueType;
  6350. instr->GetSrc1()->SetValueType(profiledValueType);
  6351. }
  6352. }
  6353. }
  6354. }
  6355. if (dstVal == nullptr)
  6356. {
  6357. dstVal = this->ValueNumberTransferDst(instr, src1Val);
  6358. }
  6359. if(!this->IsLoopPrePass())
  6360. {
  6361. // We cannot transfer value if the field hasn't been copy prop'd because we don't generate
  6362. // an implicit call bailout between those values if we don't have "live fields" unless, we are hoisting the field.
  6363. PropertySym *propertySym = instr->GetSrc1()->AsSymOpnd()->m_sym->AsPropertySym();
  6364. StackSym * fieldHoistSym;
  6365. Loop * loop = this->FindFieldHoistStackSym(this->currentBlock->loop, propertySym->m_id, &fieldHoistSym, instr);
  6366. ValueInfo *dstValueInfo = (dstVal ? dstVal->GetValueInfo() : nullptr);
  6367. // Update symStore for field hoisting
  6368. if (loop != nullptr && (dstValueInfo != nullptr))
  6369. {
  6370. dstValueInfo->SetSymStore(fieldHoistSym);
  6371. }
  6372. // Update symStore if it isn't a stackSym
  6373. if (dstVal && (!dstValueInfo->GetSymStore() || !dstValueInfo->GetSymStore()->IsStackSym()))
  6374. {
  6375. Assert(dst->IsRegOpnd());
  6376. dstValueInfo->SetSymStore(dst->AsRegOpnd()->m_sym);
  6377. }
  6378. if (src1Val != dstVal)
  6379. {
  6380. this->SetValue(&this->blockData, dstVal, instr->GetSrc1());
  6381. }
  6382. }
  6383. break;
  6384. case Js::OpCode::LdC_A_R8:
  6385. case Js::OpCode::LdC_A_I4:
  6386. case Js::OpCode::ArgIn_A:
  6387. dstVal = src1Val;
  6388. break;
  6389. case Js::OpCode::LdStr:
  6390. if (src1Val == nullptr)
  6391. {
  6392. src1Val = NewGenericValue(ValueType::String, dst);
  6393. }
  6394. dstVal = src1Val;
  6395. break;
  6396. // LdElemUndef only assign undef if the field doesn't exist.
  6397. // So we don't actually know what the value is, so we can't really copy prop it.
  6398. //case Js::OpCode::LdElemUndef:
  6399. case Js::OpCode::StSlot:
  6400. case Js::OpCode::StSlotChkUndecl:
  6401. case Js::OpCode::StFld:
  6402. case Js::OpCode::StRootFld:
  6403. case Js::OpCode::StFldStrict:
  6404. case Js::OpCode::StRootFldStrict:
  6405. if (DoFieldCopyProp())
  6406. {
  6407. if (src1Val == nullptr)
  6408. {
  6409. // src1 may have no value if it's not a valid var, e.g., NULL for let/const initialization.
  6410. // Consider creating generic values for such things.
  6411. return nullptr;
  6412. }
  6413. AssertMsg(!src2Val, "Bad src Values...");
  6414. Assert(sym->IsPropertySym());
  6415. SymID symId = sym->m_id;
  6416. Assert(instr->m_opcode == Js::OpCode::StSlot || instr->m_opcode == Js::OpCode::StSlotChkUndecl || !this->blockData.liveFields->Test(symId));
  6417. if (IsHoistablePropertySym(symId))
  6418. {
  6419. // We have changed the value of a hoistable field, load afterwards shouldn't get hoisted,
  6420. // but we will still copy prop the pre-assign sym to it if we have a live value.
  6421. Assert((instr->m_opcode == Js::OpCode::StSlot || instr->m_opcode == Js::OpCode::StSlotChkUndecl) && this->blockData.liveFields->Test(symId));
  6422. this->blockData.hoistableFields->Clear(symId);
  6423. }
  6424. this->blockData.liveFields->Set(symId);
  6425. if (!this->IsLoopPrePass() && dst->GetIsDead())
  6426. {
  6427. // Take the property sym out of the live fields set (with special handling for loops).
  6428. this->EndFieldLifetime(dst->AsSymOpnd());
  6429. }
  6430. dstVal = this->ValueNumberTransferDst(instr, src1Val);
  6431. }
  6432. else
  6433. {
  6434. return nullptr;
  6435. }
  6436. break;
  6437. case Js::OpCode::Conv_Num:
  6438. if(src1ValueInfo->IsNumber())
  6439. {
  6440. dstVal = ValueNumberTransferDst(instr, src1Val);
  6441. }
  6442. else
  6443. {
  6444. return NewGenericValue(src1ValueInfo->Type().ToDefiniteAnyNumber(), dst);
  6445. }
  6446. break;
  6447. case Js::OpCode::Not_A:
  6448. {
  6449. if (!src1Val || !src1ValueInfo->GetIntValMinMax(&min1, &max1, this->DoAggressiveIntTypeSpec()))
  6450. {
  6451. min1 = INT32_MIN;
  6452. max1 = INT32_MAX;
  6453. }
  6454. this->PropagateIntRangeForNot(min1, max1, &newMin, &newMax);
  6455. return CreateDstUntransferredIntValue(newMin, newMax, instr, src1Val, src2Val);
  6456. }
  6457. case Js::OpCode::Xor_A:
  6458. case Js::OpCode::Or_A:
  6459. case Js::OpCode::And_A:
  6460. case Js::OpCode::Shl_A:
  6461. case Js::OpCode::Shr_A:
  6462. case Js::OpCode::ShrU_A:
  6463. {
  6464. if (!src1Val || !src1ValueInfo->GetIntValMinMax(&min1, &max1, this->DoAggressiveIntTypeSpec()))
  6465. {
  6466. min1 = INT32_MIN;
  6467. max1 = INT32_MAX;
  6468. }
  6469. if (!src2Val || !src2ValueInfo->GetIntValMinMax(&min2, &max2, this->DoAggressiveIntTypeSpec()))
  6470. {
  6471. min2 = INT32_MIN;
  6472. max2 = INT32_MAX;
  6473. }
  6474. if (instr->m_opcode == Js::OpCode::ShrU_A &&
  6475. min1 < 0 &&
  6476. IntConstantBounds(min2, max2).And_0x1f().Contains(0))
  6477. {
  6478. // Src1 may be too large to represent as a signed int32, and src2 may be zero.
  6479. // Since the result can therefore be too large to represent as a signed int32,
  6480. // include Number in the value type.
  6481. return CreateDstUntransferredValue(
  6482. ValueType::AnyNumber.SetCanBeTaggedValue(true), instr, src1Val, src2Val);
  6483. }
  6484. this->PropagateIntRangeBinary(instr, min1, max1, min2, max2, &newMin, &newMax);
  6485. return CreateDstUntransferredIntValue(newMin, newMax, instr, src1Val, src2Val);
  6486. }
  6487. case Js::OpCode::Incr_A:
  6488. case Js::OpCode::Decr_A:
  6489. {
  6490. ValueType valueType;
  6491. if(src1Val)
  6492. {
  6493. valueType = src1Val->GetValueInfo()->Type().ToDefiniteAnyNumber();
  6494. }
  6495. else
  6496. {
  6497. valueType = ValueType::Number;
  6498. }
  6499. return CreateDstUntransferredValue(valueType, instr, src1Val, src2Val);
  6500. }
  6501. case Js::OpCode::Add_A:
  6502. {
  6503. ValueType valueType;
  6504. if (src1Val && src1ValueInfo->IsLikelyNumber() && src2Val && src2ValueInfo->IsLikelyNumber())
  6505. {
  6506. if(src1ValueInfo->IsLikelyInt() && src2ValueInfo->IsLikelyInt())
  6507. {
  6508. // When doing aggressiveIntType, just assume the result is likely going to be int
  6509. // if both input is int.
  6510. const bool isLikelyTagged = src1ValueInfo->IsLikelyTaggedInt() && src2ValueInfo->IsLikelyTaggedInt();
  6511. if(src1ValueInfo->IsNumber() && src2ValueInfo->IsNumber())
  6512. {
  6513. // If both of them are numbers then we can definitely say that the result is a number.
  6514. valueType = ValueType::GetNumberAndLikelyInt(isLikelyTagged);
  6515. }
  6516. else
  6517. {
  6518. // This is only likely going to be int but can be a string as well.
  6519. valueType = ValueType::GetInt(isLikelyTagged).ToLikely();
  6520. }
  6521. }
  6522. else
  6523. {
  6524. // We can only be certain of any thing if both of them are numbers.
  6525. // Otherwise, the result could be string.
  6526. if (src1ValueInfo->IsNumber() && src2ValueInfo->IsNumber())
  6527. {
  6528. if (src1ValueInfo->IsFloat() || src2ValueInfo->IsFloat())
  6529. {
  6530. // If one of them is a float, the result probably is a float instead of just int
  6531. // but should always be a number.
  6532. valueType = ValueType::Float;
  6533. }
  6534. else
  6535. {
  6536. // Could be int, could be number
  6537. valueType = ValueType::Number;
  6538. }
  6539. }
  6540. else if (src1ValueInfo->IsLikelyFloat() || src2ValueInfo->IsLikelyFloat())
  6541. {
  6542. // Result is likely a float (but can be anything)
  6543. valueType = ValueType::Float.ToLikely();
  6544. }
  6545. else
  6546. {
  6547. // Otherwise it is a likely int or float (but can be anything)
  6548. valueType = ValueType::Number.ToLikely();
  6549. }
  6550. }
  6551. }
  6552. else if((src1Val && src1ValueInfo->IsString()) || (src2Val && src2ValueInfo->IsString()))
  6553. {
  6554. // String + anything should always result in a string
  6555. valueType = ValueType::String;
  6556. }
  6557. else if((src1Val && src1ValueInfo->IsNotString() && src1ValueInfo->IsPrimitive())
  6558. && (src2Val && src2ValueInfo->IsNotString() && src2ValueInfo->IsPrimitive()))
  6559. {
  6560. // If src1 and src2 are not strings and primitive, add should yield a number.
  6561. valueType = ValueType::Number;
  6562. }
  6563. else if((src1Val && src1ValueInfo->IsLikelyString()) || (src2Val && src2ValueInfo->IsLikelyString()))
  6564. {
  6565. // likelystring + anything should always result in a likelystring
  6566. valueType = ValueType::String.ToLikely();
  6567. }
  6568. else
  6569. {
  6570. // Number or string. Could make the value a merge of Number and String, but Uninitialized is more useful at the moment.
  6571. Assert(valueType.IsUninitialized());
  6572. }
  6573. return CreateDstUntransferredValue(valueType, instr, src1Val, src2Val);
  6574. }
  6575. case Js::OpCode::Div_A:
  6576. {
  6577. ValueType divValueType = GetDivValueType(instr, src1Val, src2Val, false);
  6578. if (divValueType.IsLikelyInt() || divValueType.IsFloat())
  6579. {
  6580. return CreateDstUntransferredValue(divValueType, instr, src1Val, src2Val);
  6581. }
  6582. }
  6583. // fall-through
  6584. case Js::OpCode::Sub_A:
  6585. case Js::OpCode::Mul_A:
  6586. case Js::OpCode::Rem_A:
  6587. {
  6588. ValueType valueType;
  6589. if( src1Val &&
  6590. src1ValueInfo->IsLikelyInt() &&
  6591. src2Val &&
  6592. src2ValueInfo->IsLikelyInt() &&
  6593. instr->m_opcode != Js::OpCode::Div_A)
  6594. {
  6595. const bool isLikelyTagged =
  6596. src1ValueInfo->IsLikelyTaggedInt() && (src2ValueInfo->IsLikelyTaggedInt() || instr->m_opcode == Js::OpCode::Rem_A);
  6597. if(src1ValueInfo->IsNumber() && src2ValueInfo->IsNumber())
  6598. {
  6599. valueType = ValueType::GetNumberAndLikelyInt(isLikelyTagged);
  6600. }
  6601. else
  6602. {
  6603. valueType = ValueType::GetInt(isLikelyTagged).ToLikely();
  6604. }
  6605. }
  6606. else if ((src1Val && src1ValueInfo->IsLikelyFloat()) || (src2Val && src2ValueInfo->IsLikelyFloat()))
  6607. {
  6608. // This should ideally be NewNumberAndLikelyFloatValue since we know the result is a number but not sure if it will
  6609. // be a float value. However, that Number/LikelyFloat value type doesn't exist currently and all the necessary
  6610. // checks are done for float values (tagged int checks, etc.) so it's sufficient to just create a float value here.
  6611. valueType = ValueType::Float;
  6612. }
  6613. else
  6614. {
  6615. valueType = ValueType::Number;
  6616. }
  6617. return CreateDstUntransferredValue(valueType, instr, src1Val, src2Val);
  6618. }
  6619. case Js::OpCode::CallI:
  6620. Assert(dst->IsRegOpnd());
  6621. return NewGenericValue(dst->AsRegOpnd()->GetValueType(), dst);
  6622. case Js::OpCode::LdElemI_A:
  6623. {
  6624. dstVal = ValueNumberLdElemDst(pInstr, src1Val);
  6625. const ValueType baseValueType(instr->GetSrc1()->AsIndirOpnd()->GetBaseOpnd()->GetValueType());
  6626. if( (
  6627. baseValueType.IsLikelyNativeArray() ||
  6628. #ifdef _M_IX86
  6629. (
  6630. !AutoSystemInfo::Data.SSE2Available() &&
  6631. baseValueType.IsLikelyObject() &&
  6632. (
  6633. baseValueType.GetObjectType() == ObjectType::Float32Array ||
  6634. baseValueType.GetObjectType() == ObjectType::Float64Array
  6635. )
  6636. )
  6637. #else
  6638. false
  6639. #endif
  6640. ) &&
  6641. instr->GetDst()->IsVar() &&
  6642. instr->HasBailOutInfo())
  6643. {
  6644. // The lowerer is not going to generate a fast path for this case. Remove any bailouts that require the fast
  6645. // path. Note that the removed bailouts should not be necessary for correctness.
  6646. IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  6647. if(bailOutKind & IR::BailOutOnArrayAccessHelperCall)
  6648. {
  6649. bailOutKind -= IR::BailOutOnArrayAccessHelperCall;
  6650. }
  6651. if(bailOutKind == IR::BailOutOnImplicitCallsPreOp)
  6652. {
  6653. bailOutKind -= IR::BailOutOnImplicitCallsPreOp;
  6654. }
  6655. if(bailOutKind)
  6656. {
  6657. instr->SetBailOutKind(bailOutKind);
  6658. }
  6659. else
  6660. {
  6661. instr->ClearBailOutInfo();
  6662. }
  6663. }
  6664. return dstVal;
  6665. }
  6666. case Js::OpCode::LdMethodElem:
  6667. // Not worth profiling this, just assume it's likely object (should be likely function but ValueType does not track
  6668. // functions currently, so using ObjectType::Object instead)
  6669. dstVal = NewGenericValue(ValueType::GetObject(ObjectType::Object).ToLikely(), dst);
  6670. if(instr->GetSrc1()->AsIndirOpnd()->GetBaseOpnd()->GetValueType().IsLikelyNativeArray() && instr->HasBailOutInfo())
  6671. {
  6672. // The lowerer is not going to generate a fast path for this case. Remove any bailouts that require the fast
  6673. // path. Note that the removed bailouts should not be necessary for correctness.
  6674. IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  6675. if(bailOutKind & IR::BailOutOnArrayAccessHelperCall)
  6676. {
  6677. bailOutKind -= IR::BailOutOnArrayAccessHelperCall;
  6678. }
  6679. if(bailOutKind == IR::BailOutOnImplicitCallsPreOp)
  6680. {
  6681. bailOutKind -= IR::BailOutOnImplicitCallsPreOp;
  6682. }
  6683. if(bailOutKind)
  6684. {
  6685. instr->SetBailOutKind(bailOutKind);
  6686. }
  6687. else
  6688. {
  6689. instr->ClearBailOutInfo();
  6690. }
  6691. }
  6692. return dstVal;
  6693. case Js::OpCode::StElemI_A:
  6694. case Js::OpCode::StElemI_A_Strict:
  6695. dstVal = this->ValueNumberTransferDst(instr, src1Val);
  6696. break;
  6697. case Js::OpCode::LdLen_A:
  6698. if (instr->IsProfiledInstr())
  6699. {
  6700. const ValueType profiledValueType(instr->AsProfiledInstr()->u.ldElemInfo->GetElementType());
  6701. if(!(profiledValueType.IsLikelyInt() && dst->AsRegOpnd()->m_sym->m_isNotInt))
  6702. {
  6703. return this->NewGenericValue(profiledValueType, dst);
  6704. }
  6705. }
  6706. break;
  6707. case Js::OpCode::BrOnEmpty:
  6708. case Js::OpCode::BrOnNotEmpty:
  6709. Assert(dst->IsRegOpnd());
  6710. Assert(dst->GetValueType().IsString());
  6711. return this->NewGenericValue(ValueType::String, dst);
  6712. case Js::OpCode::IsInst:
  6713. case Js::OpCode::LdTrue:
  6714. case Js::OpCode::LdFalse:
  6715. return this->NewGenericValue(ValueType::Boolean, dst);
  6716. case Js::OpCode::LdUndef:
  6717. return this->NewGenericValue(ValueType::Undefined, dst);
  6718. case Js::OpCode::LdC_A_Null:
  6719. return this->NewGenericValue(ValueType::Null, dst);
  6720. case Js::OpCode::LdThis:
  6721. if (!PHASE_OFF(Js::OptTagChecksPhase, this->func) &&
  6722. (src1ValueInfo == nullptr || src1ValueInfo->IsUninitialized()))
  6723. {
  6724. return this->NewGenericValue(ValueType::GetObject(ObjectType::Object), dst);
  6725. }
  6726. break;
  6727. }
  6728. // SIMD_JS
  6729. if (Js::IsSimd128Opcode(instr->m_opcode) && !func->m_workItem->GetFunctionBody()->GetIsAsmjsMode())
  6730. {
  6731. ThreadContext::SimdFuncSignature simdFuncSignature;
  6732. instr->m_func->GetScriptContext()->GetThreadContext()->GetSimdFuncSignatureFromOpcode(instr->m_opcode, simdFuncSignature);
  6733. return this->NewGenericValue(simdFuncSignature.returnType, dst);
  6734. }
  6735. if (dstVal == nullptr)
  6736. {
  6737. return this->NewGenericValue(dst->GetValueType(), dst);
  6738. }
  6739. return this->SetValue(&this->blockData, dstVal, dst);
  6740. }
  6741. Value *
  6742. GlobOpt::ValueNumberLdElemDst(IR::Instr **pInstr, Value *srcVal)
  6743. {
  6744. IR::Instr *&instr = *pInstr;
  6745. IR::Opnd *dst = instr->GetDst();
  6746. Value *dstVal = nullptr;
  6747. int32 newMin, newMax;
  6748. ValueInfo *srcValueInfo = (srcVal ? srcVal->GetValueInfo() : nullptr);
  6749. ValueType profiledElementType;
  6750. if (instr->IsProfiledInstr())
  6751. {
  6752. profiledElementType = instr->AsProfiledInstr()->u.ldElemInfo->GetElementType();
  6753. if(!(profiledElementType.IsLikelyInt() && dst->IsRegOpnd() && dst->AsRegOpnd()->m_sym->m_isNotInt) &&
  6754. srcVal &&
  6755. srcValueInfo->IsUninitialized())
  6756. {
  6757. if(IsLoopPrePass())
  6758. {
  6759. dstVal = NewGenericValue(profiledElementType, dst);
  6760. }
  6761. else
  6762. {
  6763. // Assuming the profile data gives more precise value types based on the path it took at runtime, we
  6764. // can improve the original value type.
  6765. srcValueInfo->Type() = profiledElementType;
  6766. instr->GetSrc1()->SetValueType(profiledElementType);
  6767. }
  6768. }
  6769. }
  6770. IR::IndirOpnd *src = instr->GetSrc1()->AsIndirOpnd();
  6771. const ValueType baseValueType(src->GetBaseOpnd()->GetValueType());
  6772. if (instr->DoStackArgsOpt(this->func) ||
  6773. !(
  6774. baseValueType.IsLikelyOptimizedTypedArray() ||
  6775. baseValueType.IsLikelyNativeArray() && instr->IsProfiledInstr() // Specialized native array lowering for LdElem requires that it is profiled.
  6776. ) ||
  6777. (!this->DoTypedArrayTypeSpec() && baseValueType.IsLikelyOptimizedTypedArray()) ||
  6778. // Don't do type spec on native array with a history of accessing gaps, as this is a bailout
  6779. (!this->DoNativeArrayTypeSpec() && baseValueType.IsLikelyNativeArray()) ||
  6780. !ShouldExpectConventionalArrayIndexValue(src))
  6781. {
  6782. if(DoTypedArrayTypeSpec() && !IsLoopPrePass())
  6783. {
  6784. GOPT_TRACE_INSTR(instr, _u("Didn't specialize array access.\n"));
  6785. if (PHASE_TRACE(Js::TypedArrayTypeSpecPhase, this->func->GetJnFunction()))
  6786. {
  6787. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  6788. char baseValueTypeStr[VALUE_TYPE_MAX_STRING_SIZE];
  6789. baseValueType.ToString(baseValueTypeStr);
  6790. Output::Print(_u("Typed Array Optimization: function: %s (%s): instr: %s, base value type: %S, did not type specialize, because %s.\n"),
  6791. this->func->GetJnFunction()->GetDisplayName(),
  6792. this->func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  6793. Js::OpCodeUtil::GetOpCodeName(instr->m_opcode),
  6794. baseValueTypeStr,
  6795. instr->DoStackArgsOpt(this->func) ? _u("instruction uses the arguments object") :
  6796. baseValueType.IsLikelyOptimizedTypedArray() ? _u("index is negative or likely not int") : _u("of array type"));
  6797. Output::Flush();
  6798. }
  6799. }
  6800. if(!dstVal)
  6801. {
  6802. if(srcVal)
  6803. {
  6804. dstVal = this->ValueNumberTransferDst(instr, srcVal);
  6805. }
  6806. else
  6807. {
  6808. dstVal = NewGenericValue(profiledElementType, dst);
  6809. }
  6810. }
  6811. return dstVal;
  6812. }
  6813. Assert(instr->GetSrc1()->IsIndirOpnd());
  6814. IRType toType = TyVar;
  6815. IR::BailOutKind bailOutKind = IR::BailOutConventionalTypedArrayAccessOnly;
  6816. switch(baseValueType.GetObjectType())
  6817. {
  6818. case ObjectType::Int8Array:
  6819. case ObjectType::Int8VirtualArray:
  6820. case ObjectType::Int8MixedArray:
  6821. newMin = Int8ConstMin;
  6822. newMax = Int8ConstMax;
  6823. goto IntArrayCommon;
  6824. case ObjectType::Uint8Array:
  6825. case ObjectType::Uint8VirtualArray:
  6826. case ObjectType::Uint8MixedArray:
  6827. case ObjectType::Uint8ClampedArray:
  6828. case ObjectType::Uint8ClampedVirtualArray:
  6829. case ObjectType::Uint8ClampedMixedArray:
  6830. newMin = Uint8ConstMin;
  6831. newMax = Uint8ConstMax;
  6832. goto IntArrayCommon;
  6833. case ObjectType::Int16Array:
  6834. case ObjectType::Int16VirtualArray:
  6835. case ObjectType::Int16MixedArray:
  6836. newMin = Int16ConstMin;
  6837. newMax = Int16ConstMax;
  6838. goto IntArrayCommon;
  6839. case ObjectType::Uint16Array:
  6840. case ObjectType::Uint16VirtualArray:
  6841. case ObjectType::Uint16MixedArray:
  6842. newMin = Uint16ConstMin;
  6843. newMax = Uint16ConstMax;
  6844. goto IntArrayCommon;
  6845. case ObjectType::Int32Array:
  6846. case ObjectType::Int32VirtualArray:
  6847. case ObjectType::Int32MixedArray:
  6848. case ObjectType::Uint32Array: // int-specialized loads from uint32 arrays will bail out on values that don't fit in an int32
  6849. case ObjectType::Uint32VirtualArray:
  6850. case ObjectType::Uint32MixedArray:
  6851. Int32Array:
  6852. newMin = Int32ConstMin;
  6853. newMax = Int32ConstMax;
  6854. goto IntArrayCommon;
  6855. IntArrayCommon:
  6856. Assert(dst->IsRegOpnd());
  6857. TypeSpecializeIntDst(instr, instr->m_opcode, nullptr, nullptr, nullptr, bailOutKind, newMin, newMax, &dstVal);
  6858. toType = TyInt32;
  6859. break;
  6860. case ObjectType::Float32Array:
  6861. case ObjectType::Float32VirtualArray:
  6862. case ObjectType::Float32MixedArray:
  6863. case ObjectType::Float64Array:
  6864. case ObjectType::Float64VirtualArray:
  6865. case ObjectType::Float64MixedArray:
  6866. Float64Array:
  6867. Assert(dst->IsRegOpnd());
  6868. TypeSpecializeFloatDst(instr, nullptr, nullptr, nullptr, &dstVal);
  6869. toType = TyFloat64;
  6870. break;
  6871. default:
  6872. Assert(baseValueType.IsLikelyNativeArray());
  6873. bailOutKind = IR::BailOutConventionalNativeArrayAccessOnly;
  6874. if(baseValueType.HasIntElements())
  6875. {
  6876. goto Int32Array;
  6877. }
  6878. Assert(baseValueType.HasFloatElements());
  6879. goto Float64Array;
  6880. }
  6881. if(!dstVal)
  6882. {
  6883. dstVal = NewGenericValue(profiledElementType, dst);
  6884. }
  6885. Assert(toType != TyVar);
  6886. GOPT_TRACE_INSTR(instr, _u("Type specialized array access.\n"));
  6887. if (PHASE_TRACE(Js::TypedArrayTypeSpecPhase, this->func->GetJnFunction()))
  6888. {
  6889. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  6890. char baseValueTypeStr[VALUE_TYPE_MAX_STRING_SIZE];
  6891. baseValueType.ToString(baseValueTypeStr);
  6892. char dstValTypeStr[VALUE_TYPE_MAX_STRING_SIZE];
  6893. dstVal->GetValueInfo()->Type().ToString(dstValTypeStr);
  6894. Output::Print(_u("Typed Array Optimization: function: %s (%s): instr: %s, base value type: %S, type specialized to %s producing %S"),
  6895. this->func->GetJnFunction()->GetDisplayName(),
  6896. this->func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  6897. Js::OpCodeUtil::GetOpCodeName(instr->m_opcode),
  6898. baseValueTypeStr,
  6899. toType == TyInt32 ? _u("int32") : _u("float64"),
  6900. dstValTypeStr);
  6901. #if DBG_DUMP
  6902. Output::Print(_u(" ("));
  6903. dstVal->Dump();
  6904. Output::Print(_u(").\n"));
  6905. #else
  6906. Output::Print(_u(".\n"));
  6907. #endif
  6908. Output::Flush();
  6909. }
  6910. if(!this->IsLoopPrePass())
  6911. {
  6912. if(instr->HasBailOutInfo())
  6913. {
  6914. const IR::BailOutKind oldBailOutKind = instr->GetBailOutKind();
  6915. Assert(
  6916. (
  6917. !(oldBailOutKind & ~IR::BailOutKindBits) ||
  6918. (oldBailOutKind & ~IR::BailOutKindBits) == IR::BailOutOnImplicitCallsPreOp
  6919. ) &&
  6920. !(oldBailOutKind & IR::BailOutKindBits & ~(IR::BailOutOnArrayAccessHelperCall | IR::BailOutMarkTempObject)));
  6921. if(bailOutKind == IR::BailOutConventionalTypedArrayAccessOnly)
  6922. {
  6923. // BailOutConventionalTypedArrayAccessOnly also bails out if the array access is outside the head
  6924. // segment bounds, and guarantees no implicit calls. Override the bailout kind so that the instruction
  6925. // bails out for the right reason.
  6926. instr->SetBailOutKind(
  6927. bailOutKind | (oldBailOutKind & (IR::BailOutKindBits - IR::BailOutOnArrayAccessHelperCall)));
  6928. }
  6929. else
  6930. {
  6931. // BailOutConventionalNativeArrayAccessOnly by itself may generate a helper call, and may cause implicit
  6932. // calls to occur, so it must be merged in to eliminate generating the helper call
  6933. Assert(bailOutKind == IR::BailOutConventionalNativeArrayAccessOnly);
  6934. instr->SetBailOutKind(oldBailOutKind | bailOutKind);
  6935. }
  6936. }
  6937. else
  6938. {
  6939. GenerateBailAtOperation(&instr, bailOutKind);
  6940. }
  6941. }
  6942. return dstVal;
  6943. }
  6944. ValueType
  6945. GlobOpt::GetPrepassValueTypeForDst(
  6946. const ValueType desiredValueType,
  6947. IR::Instr *const instr,
  6948. Value *const src1Value,
  6949. Value *const src2Value,
  6950. bool *const isValueInfoPreciseRef) const
  6951. {
  6952. // Values with definite types can be created in the loop prepass only when it is guaranteed that the value type will be the
  6953. // same on any iteration of the loop. The heuristics currently used are:
  6954. // - If the source sym is not live on the back-edge, then it acquires a new value for each iteration of the loop, so
  6955. // that value type can be definite
  6956. // - Consider: A better solution for this is to track values that originate in this loop, which can have definite value
  6957. // types. That catches more cases, should look into that in the future.
  6958. // - If the source sym has a constant value that doesn't change for the duration of the function
  6959. // - The operation always results in a definite value type. For instance, signed bitwise operations always result in an
  6960. // int32, conv_num and ++ always result in a number, etc.
  6961. // - For operations that always result in an int32, the resulting int range is precise only if the source syms pass
  6962. // the above heuristics. Otherwise, the range must be expanded to the full int32 range.
  6963. Assert(IsLoopPrePass());
  6964. Assert(instr);
  6965. if(isValueInfoPreciseRef)
  6966. {
  6967. *isValueInfoPreciseRef = false;
  6968. }
  6969. if(!desiredValueType.IsDefinite())
  6970. {
  6971. return desiredValueType;
  6972. }
  6973. if(instr->GetSrc1() && !IsPrepassSrcValueInfoPrecise(instr->GetSrc1(), src1Value) ||
  6974. instr->GetSrc2() && !IsPrepassSrcValueInfoPrecise(instr->GetSrc2(), src2Value))
  6975. {
  6976. // If the desired value type is not precise, the value type of the destination is derived from the value types of the
  6977. // sources. Since the value type of a source sym is not definite, the destination value type also cannot be definite.
  6978. if(desiredValueType.IsInt() && OpCodeAttr::IsInt32(instr->m_opcode))
  6979. {
  6980. // The op always produces an int32, but not always a tagged int
  6981. return ValueType::GetInt(desiredValueType.IsLikelyTaggedInt());
  6982. }
  6983. if(desiredValueType.IsNumber() && OpCodeAttr::ProducesNumber(instr->m_opcode, func->GetScriptContext()))
  6984. {
  6985. // The op always produces a number, but not always an int
  6986. return desiredValueType.ToDefiniteAnyNumber();
  6987. }
  6988. return desiredValueType.ToLikely();
  6989. }
  6990. if(isValueInfoPreciseRef)
  6991. {
  6992. // The produced value info is derived from the sources, which have precise value infos
  6993. *isValueInfoPreciseRef = true;
  6994. }
  6995. return desiredValueType;
  6996. }
  6997. bool
  6998. GlobOpt::IsPrepassSrcValueInfoPrecise(IR::Opnd *const src, Value *const srcValue) const
  6999. {
  7000. Assert(IsLoopPrePass());
  7001. Assert(src);
  7002. if(!src->IsRegOpnd() || !srcValue)
  7003. {
  7004. return false;
  7005. }
  7006. ValueInfo *const srcValueInfo = srcValue->GetValueInfo();
  7007. if(!srcValueInfo->IsDefinite())
  7008. {
  7009. return false;
  7010. }
  7011. StackSym *srcSym = src->AsRegOpnd()->m_sym;
  7012. Assert(!srcSym->IsTypeSpec());
  7013. int32 intConstantValue;
  7014. return
  7015. srcSym->IsFromByteCodeConstantTable() ||
  7016. (
  7017. srcValueInfo->TryGetIntConstantValue(&intConstantValue) &&
  7018. !Js::TaggedInt::IsOverflow(intConstantValue) &&
  7019. GetTaggedIntConstantStackSym(intConstantValue) == srcSym
  7020. ) ||
  7021. this->IsDefinedInCurrentLoopIteration(this->currentBlock->loop, srcValue) ||
  7022. !currentBlock->loop->regAlloc.liveOnBackEdgeSyms->Test(srcSym->m_id);
  7023. }
  7024. Value *GlobOpt::CreateDstUntransferredIntValue(
  7025. const int32 min,
  7026. const int32 max,
  7027. IR::Instr *const instr,
  7028. Value *const src1Value,
  7029. Value *const src2Value)
  7030. {
  7031. Assert(instr);
  7032. Assert(instr->GetDst());
  7033. Assert(OpCodeAttr::ProducesNumber(instr->m_opcode, this->func->GetScriptContext())
  7034. || (instr->m_opcode == Js::OpCode::Add_A && src1Value->GetValueInfo()->IsNumber()
  7035. && src2Value->GetValueInfo()->IsNumber()));
  7036. ValueType valueType(ValueType::GetInt(IntConstantBounds(min, max).IsLikelyTaggable()));
  7037. Assert(valueType.IsInt());
  7038. bool isValueInfoPrecise;
  7039. if(IsLoopPrePass())
  7040. {
  7041. valueType = GetPrepassValueTypeForDst(valueType, instr, src1Value, src2Value, &isValueInfoPrecise);
  7042. }
  7043. else
  7044. {
  7045. isValueInfoPrecise = true;
  7046. }
  7047. IR::Opnd *const dst = instr->GetDst();
  7048. if(isValueInfoPrecise)
  7049. {
  7050. Assert(valueType == ValueType::GetInt(IntConstantBounds(min, max).IsLikelyTaggable()));
  7051. Assert(!(dst->IsRegOpnd() && dst->AsRegOpnd()->m_sym->IsTypeSpec()));
  7052. return NewIntRangeValue(min, max, false, dst);
  7053. }
  7054. return NewGenericValue(valueType, dst);
  7055. }
  7056. Value *
  7057. GlobOpt::CreateDstUntransferredValue(
  7058. const ValueType desiredValueType,
  7059. IR::Instr *const instr,
  7060. Value *const src1Value,
  7061. Value *const src2Value)
  7062. {
  7063. Assert(instr);
  7064. Assert(instr->GetDst());
  7065. Assert(!desiredValueType.IsInt()); // use CreateDstUntransferredIntValue instead
  7066. ValueType valueType(desiredValueType);
  7067. if(IsLoopPrePass())
  7068. {
  7069. valueType = GetPrepassValueTypeForDst(valueType, instr, src1Value, src2Value);
  7070. }
  7071. return NewGenericValue(valueType, instr->GetDst());
  7072. }
  7073. Value *
  7074. GlobOpt::ValueNumberTransferDst(IR::Instr *const instr, Value * src1Val)
  7075. {
  7076. Value *dstVal = this->IsLoopPrePass() ? this->ValueNumberTransferDstInPrepass(instr, src1Val) : src1Val;
  7077. // Don't copy-prop a temp over a user symbol. This is likely to extend the temp's lifetime, as the user symbol
  7078. // is more likely to already have later references.
  7079. // REVIEW: Enabling this does cause perf issues...
  7080. #if 0
  7081. if (dstVal != src1Val)
  7082. {
  7083. return dstVal;
  7084. }
  7085. Sym *dstSym = dst->GetStackSym();
  7086. if (dstVal && dstSym && dstSym->IsStackSym() && !dstSym->AsStackSym()->m_isBytecodeTmp)
  7087. {
  7088. Sym *dstValSym = dstVal->GetValueInfo()->GetSymStore();
  7089. if (dstValSym && dstValSym->AsStackSym()->m_isBytecodeTmp /* src->GetIsDead()*/)
  7090. {
  7091. dstVal->GetValueInfo()->SetSymStore(dstSym);
  7092. }
  7093. }
  7094. #endif
  7095. return dstVal;
  7096. }
  7097. bool
  7098. GlobOpt::IsSafeToTransferInPrePass(IR::Opnd *src, Value *srcValue)
  7099. {
  7100. if (this->DoFieldHoisting())
  7101. {
  7102. return false;
  7103. }
  7104. if (this->IsDefinedInCurrentLoopIteration(this->prePassLoop, srcValue))
  7105. {
  7106. return true;
  7107. }
  7108. if (src->IsRegOpnd())
  7109. {
  7110. StackSym *srcSym = src->AsRegOpnd()->m_sym;
  7111. if (srcSym->IsFromByteCodeConstantTable())
  7112. {
  7113. return true;
  7114. }
  7115. ValueInfo *srcValueInfo = srcValue->GetValueInfo();
  7116. int32 srcIntConstantValue;
  7117. if (srcValueInfo->TryGetIntConstantValue(&srcIntConstantValue) && !Js::TaggedInt::IsOverflow(srcIntConstantValue)
  7118. && GetTaggedIntConstantStackSym(srcIntConstantValue) == srcSym)
  7119. {
  7120. return true;
  7121. }
  7122. }
  7123. return false;
  7124. }
  7125. Value *
  7126. GlobOpt::ValueNumberTransferDstInPrepass(IR::Instr *const instr, Value *const src1Val)
  7127. {
  7128. Value *dstVal = nullptr;
  7129. if (!src1Val)
  7130. {
  7131. return nullptr;
  7132. }
  7133. bool isValueInfoPrecise;
  7134. ValueInfo *const src1ValueInfo = src1Val->GetValueInfo();
  7135. // TODO: This conflicts with new values created by the type specialization code
  7136. // We should re-enable if we change that code to avoid the new values.
  7137. #if 0
  7138. if (this->IsSafeToTransferInPrePass(instr->GetSrc1(), src1Val))
  7139. {
  7140. return src1Val;
  7141. }
  7142. if (this->IsPREInstrCandidateLoad(instr->m_opcode) && instr->GetDst())
  7143. {
  7144. StackSym *dstSym = instr->GetDst()->AsRegOpnd()->m_sym;
  7145. for (Loop *curLoop = this->currentBlock->loop; curLoop; curLoop = curLoop->parent)
  7146. {
  7147. if (curLoop->fieldPRESymStore->Test(dstSym->m_id))
  7148. {
  7149. return src1Val;
  7150. }
  7151. }
  7152. }
  7153. if (!this->DoFieldHoisting())
  7154. {
  7155. if (instr->GetDst()->IsRegOpnd())
  7156. {
  7157. StackSym *stackSym = instr->GetDst()->AsRegOpnd()->m_sym;
  7158. if (stackSym->IsSingleDef() || this->IsLive(stackSym, this->prePassLoop->landingPad))
  7159. {
  7160. IntConstantBounds src1IntConstantBounds;
  7161. if (src1ValueInfo->TryGetIntConstantBounds(&src1IntConstantBounds) &&
  7162. !(
  7163. src1IntConstantBounds.LowerBound() == INT32_MIN &&
  7164. src1IntConstantBounds.UpperBound() == INT32_MAX
  7165. ))
  7166. {
  7167. const ValueType valueType(
  7168. GetPrepassValueTypeForDst(src1ValueInfo->Type(), instr, src1Val, nullptr, &isValueInfoPrecise));
  7169. if (isValueInfoPrecise)
  7170. {
  7171. return src1Val;
  7172. }
  7173. }
  7174. else
  7175. {
  7176. return src1Val;
  7177. }
  7178. }
  7179. }
  7180. }
  7181. #endif
  7182. // Src1's value could change later in the loop, so the value wouldn't be the same for each
  7183. // iteration. Since we don't iterate over loops "while (!changed)", go conservative on the
  7184. // first pass when transferring a value that is live on the back-edge.
  7185. // In prepass we are going to copy the value but with a different value number
  7186. // for aggressive int type spec.
  7187. const ValueType valueType(GetPrepassValueTypeForDst(src1ValueInfo->Type(), instr, src1Val, nullptr, &isValueInfoPrecise));
  7188. if(isValueInfoPrecise || valueType == src1ValueInfo->Type() && src1ValueInfo->IsGeneric())
  7189. {
  7190. Assert(valueType == src1ValueInfo->Type());
  7191. dstVal = CopyValue(src1Val);
  7192. TrackCopiedValueForKills(dstVal);
  7193. }
  7194. else
  7195. {
  7196. dstVal = NewGenericValue(valueType);
  7197. dstVal->GetValueInfo()->SetSymStore(src1ValueInfo->GetSymStore());
  7198. }
  7199. return dstVal;
  7200. }
  7201. void
  7202. GlobOpt::PropagateIntRangeForNot(int32 minimum, int32 maximum, int32 *pNewMin, int32* pNewMax)
  7203. {
  7204. int32 tmp;
  7205. Int32Math::Not(minimum, pNewMin);
  7206. *pNewMax = *pNewMin;
  7207. Int32Math::Not(maximum, &tmp);
  7208. *pNewMin = min(*pNewMin, tmp);
  7209. *pNewMax = max(*pNewMax, tmp);
  7210. }
  7211. void
  7212. GlobOpt::PropagateIntRangeBinary(IR::Instr *instr, int32 min1, int32 max1,
  7213. int32 min2, int32 max2, int32 *pNewMin, int32* pNewMax)
  7214. {
  7215. int32 min, max, tmp, tmp2;
  7216. min = INT32_MIN;
  7217. max = INT32_MAX;
  7218. switch (instr->m_opcode)
  7219. {
  7220. case Js::OpCode::Xor_A:
  7221. case Js::OpCode::Or_A:
  7222. // Find range with highest high order bit
  7223. tmp = ::max((uint32)min1, (uint32)max1);
  7224. tmp2 = ::max((uint32)min2, (uint32)max2);
  7225. if ((uint32)tmp > (uint32)tmp2)
  7226. {
  7227. max = tmp;
  7228. }
  7229. else
  7230. {
  7231. max = tmp2;
  7232. }
  7233. if (max < 0)
  7234. {
  7235. min = INT32_MIN; // REVIEW: conservative...
  7236. max = INT32_MAX;
  7237. }
  7238. else
  7239. {
  7240. // Turn values like 0x1010 into 0x1111
  7241. max = 1 << Math::Log2(max);
  7242. max = (max << 1) - 1;
  7243. min = 0;
  7244. }
  7245. break;
  7246. case Js::OpCode::And_A:
  7247. if (min1 == INT32_MIN && min2 == INT32_MIN)
  7248. {
  7249. // Shortcut
  7250. break;
  7251. }
  7252. // Find range with lowest higher bit
  7253. tmp = ::max((uint32)min1, (uint32)max1);
  7254. tmp2 = ::max((uint32)min2, (uint32)max2);
  7255. if ((uint32)tmp < (uint32)tmp2)
  7256. {
  7257. min = min1;
  7258. max = max1;
  7259. }
  7260. else
  7261. {
  7262. min = min2;
  7263. max = max2;
  7264. }
  7265. // To compute max, look if min has higher high bit
  7266. if ((uint32)min > (uint32)max)
  7267. {
  7268. max = min;
  7269. }
  7270. // If max is negative, max let's assume it could be -1, so result in MAX_INT
  7271. if (max < 0)
  7272. {
  7273. max = INT32_MAX;
  7274. }
  7275. // If min is positive, the resulting min is zero
  7276. if (min >= 0)
  7277. {
  7278. min = 0;
  7279. }
  7280. else
  7281. {
  7282. min = INT32_MIN;
  7283. }
  7284. break;
  7285. case Js::OpCode::Shl_A:
  7286. {
  7287. // Shift count
  7288. if (min2 != max2 && ((uint32)min2 > 0x1F || (uint32)max2 > 0x1F))
  7289. {
  7290. min2 = 0;
  7291. max2 = 0x1F;
  7292. }
  7293. else
  7294. {
  7295. min2 &= 0x1F;
  7296. max2 &= 0x1F;
  7297. }
  7298. int32 min1FreeTopBitCount = min1 ? (sizeof(int32) * 8) - (Math::Log2(min1) + 1) : (sizeof(int32) * 8);
  7299. int32 max1FreeTopBitCount = max1 ? (sizeof(int32) * 8) - (Math::Log2(max1) + 1) : (sizeof(int32) * 8);
  7300. if (min1FreeTopBitCount <= max2 || max1FreeTopBitCount <= max2)
  7301. {
  7302. // If the shift is going to touch the sign bit return the max range
  7303. min = INT32_MIN;
  7304. max = INT32_MAX;
  7305. }
  7306. else
  7307. {
  7308. // Compute max
  7309. // Turn values like 0x1010 into 0x1111
  7310. if (min1)
  7311. {
  7312. min1 = 1 << Math::Log2(min1);
  7313. min1 = (min1 << 1) - 1;
  7314. }
  7315. if (max1)
  7316. {
  7317. max1 = 1 << Math::Log2(max1);
  7318. max1 = (max1 << 1) - 1;
  7319. }
  7320. if (max1 > 0)
  7321. {
  7322. int32 nrTopBits = (sizeof(int32) * 8) - Math::Log2(max1);
  7323. if (nrTopBits < ::min(max2, 30))
  7324. max = INT32_MAX;
  7325. else
  7326. max = ::max((max1 << ::min(max2, 30)) & ~0x80000000, (min1 << min2) & ~0x80000000);
  7327. }
  7328. else
  7329. {
  7330. max = (max1 << min2) & ~0x80000000;
  7331. }
  7332. // Compute min
  7333. if (min1 < 0)
  7334. {
  7335. min = ::min(min1 << max2, max1 << max2);
  7336. }
  7337. else
  7338. {
  7339. min = ::min(min1 << min2, max1 << max2);
  7340. }
  7341. // Turn values like 0x1110 into 0x1000
  7342. if (min)
  7343. {
  7344. min = 1 << Math::Log2(min);
  7345. }
  7346. }
  7347. }
  7348. break;
  7349. case Js::OpCode::Shr_A:
  7350. // Shift count
  7351. if (min2 != max2 && ((uint32)min2 > 0x1F || (uint32)max2 > 0x1F))
  7352. {
  7353. min2 = 0;
  7354. max2 = 0x1F;
  7355. }
  7356. else
  7357. {
  7358. min2 &= 0x1F;
  7359. max2 &= 0x1F;
  7360. }
  7361. // Compute max
  7362. if (max1 < 0)
  7363. {
  7364. max = max1 >> max2;
  7365. }
  7366. else
  7367. {
  7368. max = max1 >> min2;
  7369. }
  7370. // Compute min
  7371. if (min1 < 0)
  7372. {
  7373. min = min1 >> min2;
  7374. }
  7375. else
  7376. {
  7377. min = min1 >> max2;
  7378. }
  7379. break;
  7380. case Js::OpCode::ShrU_A:
  7381. // shift count is constant zero
  7382. if ((min2 == max2) && (max2 & 0x1f) == 0)
  7383. {
  7384. // We can't encode uint32 result, so it has to be used as int32 only or the original value is positive.
  7385. Assert(instr->ignoreIntOverflow || min1 >= 0);
  7386. // We can transfer the signed int32 range.
  7387. min = min1;
  7388. max = max1;
  7389. break;
  7390. }
  7391. const IntConstantBounds src2NewBounds = IntConstantBounds(min2, max2).And_0x1f();
  7392. // Zero is only allowed if result is always a signed int32 or always used as a signed int32
  7393. Assert(min1 >= 0 || instr->ignoreIntOverflow || !src2NewBounds.Contains(0));
  7394. min2 = src2NewBounds.LowerBound();
  7395. max2 = src2NewBounds.UpperBound();
  7396. Assert(min2 <= max2);
  7397. // zero shift count is only allowed if result is used as int32 and/or value is positive
  7398. Assert(min2 > 0 || instr->ignoreIntOverflow || min1 >= 0);
  7399. uint32 umin1 = (uint32)min1;
  7400. uint32 umax1 = (uint32)max1;
  7401. if (umin1 > umax1)
  7402. {
  7403. uint32 temp = umax1;
  7404. umax1 = umin1;
  7405. umin1 = temp;
  7406. }
  7407. Assert(min2 >= 0 && max2 < 32);
  7408. // Compute max
  7409. if (min1 < 0)
  7410. {
  7411. umax1 = UINT32_MAX;
  7412. }
  7413. max = umax1 >> min2;
  7414. // Compute min
  7415. if (min1 <= 0 && max1 >=0)
  7416. {
  7417. min = 0;
  7418. }
  7419. else
  7420. {
  7421. min = umin1 >> max2;
  7422. }
  7423. // We should be able to fit uint32 range as int32
  7424. Assert(instr->ignoreIntOverflow || (min >= 0 && max >= 0) );
  7425. if (min > max)
  7426. {
  7427. // can only happen if shift count can be zero
  7428. Assert(min2 == 0 && (instr->ignoreIntOverflow || min1 >= 0));
  7429. min = Int32ConstMin;
  7430. max = Int32ConstMax;
  7431. }
  7432. break;
  7433. }
  7434. *pNewMin = min;
  7435. *pNewMax = max;
  7436. }
  7437. IR::Instr *
  7438. GlobOpt::TypeSpecialization(
  7439. IR::Instr *instr,
  7440. Value **pSrc1Val,
  7441. Value **pSrc2Val,
  7442. Value **pDstVal,
  7443. bool *redoTypeSpecRef,
  7444. bool *const forceInvariantHoistingRef)
  7445. {
  7446. Value *&src1Val = *pSrc1Val;
  7447. Value *&src2Val = *pSrc2Val;
  7448. *redoTypeSpecRef = false;
  7449. Assert(!*forceInvariantHoistingRef);
  7450. this->ignoredIntOverflowForCurrentInstr = false;
  7451. this->ignoredNegativeZeroForCurrentInstr = false;
  7452. // - Int32 values that can't be tagged are created as float constant values instead because a JavascriptNumber var is needed
  7453. // for that value at runtime. For the purposes of type specialization, recover the int32 values so that they will be
  7454. // treated as ints.
  7455. // - If int overflow does not matter for the instruction, we can additionally treat uint32 values as int32 values because
  7456. // the value resulting from the operation will eventually be converted to int32 anyway
  7457. Value *const src1OriginalVal = src1Val;
  7458. Value *const src2OriginalVal = src2Val;
  7459. // SIMD_JS
  7460. if (TypeSpecializeSimd128(instr, pSrc1Val, pSrc2Val, pDstVal))
  7461. {
  7462. return instr;
  7463. }
  7464. if(!instr->ShouldCheckForIntOverflow())
  7465. {
  7466. if(src1Val && src1Val->GetValueInfo()->IsFloatConstant())
  7467. {
  7468. int32 int32Value;
  7469. bool isInt32;
  7470. if(Js::JavascriptNumber::TryGetInt32OrUInt32Value(
  7471. src1Val->GetValueInfo()->AsFloatConstant()->FloatValue(),
  7472. &int32Value,
  7473. &isInt32))
  7474. {
  7475. src1Val = GetIntConstantValue(int32Value, instr);
  7476. if(!isInt32)
  7477. {
  7478. this->ignoredIntOverflowForCurrentInstr = true;
  7479. }
  7480. }
  7481. }
  7482. if(src2Val && src2Val->GetValueInfo()->IsFloatConstant())
  7483. {
  7484. int32 int32Value;
  7485. bool isInt32;
  7486. if(Js::JavascriptNumber::TryGetInt32OrUInt32Value(
  7487. src2Val->GetValueInfo()->AsFloatConstant()->FloatValue(),
  7488. &int32Value,
  7489. &isInt32))
  7490. {
  7491. src2Val = GetIntConstantValue(int32Value, instr);
  7492. if(!isInt32)
  7493. {
  7494. this->ignoredIntOverflowForCurrentInstr = true;
  7495. }
  7496. }
  7497. }
  7498. }
  7499. const AutoRestoreVal autoRestoreSrc1Val(src1OriginalVal, &src1Val);
  7500. const AutoRestoreVal autoRestoreSrc2Val(src2OriginalVal, &src2Val);
  7501. if (src1Val && instr->GetSrc2() == nullptr)
  7502. {
  7503. // Unary
  7504. // Note make sure that native array StElemI gets to TypeSpecializeStElem. Do this for typed arrays, too?
  7505. int32 intConstantValue;
  7506. if (!this->IsLoopPrePass() &&
  7507. !instr->IsBranchInstr() &&
  7508. src1Val->GetValueInfo()->TryGetIntConstantValue(&intConstantValue) &&
  7509. !(
  7510. // Nothing to fold for element stores. Go into type specialization to see if they can at least be specialized.
  7511. instr->m_opcode == Js::OpCode::StElemI_A ||
  7512. instr->m_opcode == Js::OpCode::StElemI_A_Strict ||
  7513. instr->m_opcode == Js::OpCode::StElemC ||
  7514. instr->m_opcode == Js::OpCode::MultiBr ||
  7515. instr->m_opcode == Js::OpCode::InlineArrayPop
  7516. ))
  7517. {
  7518. if (OptConstFoldUnary(&instr, intConstantValue, src1Val == src1OriginalVal, pDstVal))
  7519. {
  7520. return instr;
  7521. }
  7522. }
  7523. else if (
  7524. this->TypeSpecializeUnary(
  7525. &instr,
  7526. &src1Val,
  7527. pDstVal,
  7528. src1OriginalVal,
  7529. redoTypeSpecRef,
  7530. forceInvariantHoistingRef))
  7531. {
  7532. return instr;
  7533. }
  7534. else if(*redoTypeSpecRef)
  7535. {
  7536. return instr;
  7537. }
  7538. }
  7539. else if (instr->GetSrc2() && !instr->IsBranchInstr())
  7540. {
  7541. // Binary
  7542. if (!this->IsLoopPrePass())
  7543. {
  7544. // OptConstFoldBinary doesn't do type spec, so only deal with things we are sure are int (IntConstant and IntRange)
  7545. // and not just likely ints TypeSpecializeBinary will deal with type specializing them and fold them again
  7546. IntConstantBounds src1IntConstantBounds, src2IntConstantBounds;
  7547. if (src1Val && src1Val->GetValueInfo()->TryGetIntConstantBounds(&src1IntConstantBounds))
  7548. {
  7549. if (src2Val && src2Val->GetValueInfo()->TryGetIntConstantBounds(&src2IntConstantBounds))
  7550. {
  7551. if (this->OptConstFoldBinary(&instr, src1IntConstantBounds, src2IntConstantBounds, pDstVal))
  7552. {
  7553. return instr;
  7554. }
  7555. }
  7556. }
  7557. }
  7558. }
  7559. if (instr->GetSrc2() && this->TypeSpecializeBinary(&instr, pSrc1Val, pSrc2Val, pDstVal, src1OriginalVal, src2OriginalVal, redoTypeSpecRef))
  7560. {
  7561. if (!this->IsLoopPrePass() &&
  7562. instr->m_opcode != Js::OpCode::Nop &&
  7563. instr->m_opcode != Js::OpCode::Br && // We may have const fold a branch
  7564. // Cannot const-peep if the result of the operation is required for a bailout check
  7565. !(instr->HasBailOutInfo() && instr->GetBailOutKind() & IR::BailOutOnResultConditions))
  7566. {
  7567. if (src1Val && src1Val->GetValueInfo()->HasIntConstantValue())
  7568. {
  7569. if (this->OptConstPeep(instr, instr->GetSrc1(), pDstVal, src1Val->GetValueInfo()))
  7570. {
  7571. return instr;
  7572. }
  7573. }
  7574. else if (src2Val && src2Val->GetValueInfo()->HasIntConstantValue())
  7575. {
  7576. if (this->OptConstPeep(instr, instr->GetSrc2(), pDstVal, src2Val->GetValueInfo()))
  7577. {
  7578. return instr;
  7579. }
  7580. }
  7581. }
  7582. return instr;
  7583. }
  7584. else if(*redoTypeSpecRef)
  7585. {
  7586. return instr;
  7587. }
  7588. if (instr->IsBranchInstr() && !this->IsLoopPrePass())
  7589. {
  7590. if (this->OptConstFoldBranch(instr, src1Val, src2Val, pDstVal))
  7591. {
  7592. return instr;
  7593. }
  7594. }
  7595. // We didn't type specialize, make sure the srcs are unspecialized
  7596. IR::Opnd *src1 = instr->GetSrc1();
  7597. if (src1)
  7598. {
  7599. instr = this->ToVarUses(instr, src1, false, src1Val);
  7600. IR::Opnd *src2 = instr->GetSrc2();
  7601. if (src2)
  7602. {
  7603. instr = this->ToVarUses(instr, src2, false, src2Val);
  7604. }
  7605. }
  7606. IR::Opnd *dst = instr->GetDst();
  7607. if (dst)
  7608. {
  7609. instr = this->ToVarUses(instr, dst, true, nullptr);
  7610. // Handling for instructions other than built-ins that may require only dst type specialization
  7611. // should be added here.
  7612. if(OpCodeAttr::IsInlineBuiltIn(instr->m_opcode) && !GetIsAsmJSFunc()) // don't need to do typespec for asmjs
  7613. {
  7614. this->TypeSpecializeInlineBuiltInDst(&instr, pDstVal);
  7615. return instr;
  7616. }
  7617. // Clear the int specialized bit on the dst.
  7618. if (dst->IsRegOpnd())
  7619. {
  7620. IR::RegOpnd *dstRegOpnd = dst->AsRegOpnd();
  7621. if (!dstRegOpnd->m_sym->IsTypeSpec())
  7622. {
  7623. this->ToVarRegOpnd(dstRegOpnd, this->currentBlock);
  7624. }
  7625. else if (dstRegOpnd->m_sym->IsInt32())
  7626. {
  7627. this->ToInt32Dst(instr, dstRegOpnd, this->currentBlock);
  7628. }
  7629. else if (dstRegOpnd->m_sym->IsUInt32() && GetIsAsmJSFunc())
  7630. {
  7631. this->ToUInt32Dst(instr, dstRegOpnd, this->currentBlock);
  7632. }
  7633. else if (dstRegOpnd->m_sym->IsFloat64())
  7634. {
  7635. this->ToFloat64Dst(instr, dstRegOpnd, this->currentBlock);
  7636. }
  7637. }
  7638. else if (dst->IsSymOpnd() && dst->AsSymOpnd()->m_sym->IsStackSym())
  7639. {
  7640. this->ToVarStackSym(dst->AsSymOpnd()->m_sym->AsStackSym(), this->currentBlock);
  7641. }
  7642. }
  7643. return instr;
  7644. }
  7645. bool
  7646. GlobOpt::OptConstPeep(IR::Instr *instr, IR::Opnd *constSrc, Value **pDstVal, ValueInfo *valuInfo)
  7647. {
  7648. int32 value;
  7649. IR::Opnd *src;
  7650. IR::Opnd *nonConstSrc = (constSrc == instr->GetSrc1() ? instr->GetSrc2() : instr->GetSrc1());
  7651. // Try to find the value from value info first
  7652. if (valuInfo->TryGetIntConstantValue(&value))
  7653. {
  7654. }
  7655. else if (constSrc->IsAddrOpnd())
  7656. {
  7657. IR::AddrOpnd *addrOpnd = constSrc->AsAddrOpnd();
  7658. #ifdef _M_X64
  7659. Assert(addrOpnd->IsVar() || Math::FitsInDWord((size_t)addrOpnd->m_address));
  7660. #else
  7661. Assert(sizeof(value) == sizeof(addrOpnd->m_address));
  7662. #endif
  7663. if (addrOpnd->IsVar())
  7664. {
  7665. value = Js::TaggedInt::ToInt32(addrOpnd->m_address);
  7666. }
  7667. else
  7668. {
  7669. // We asserted that the address will fit in a DWORD above
  7670. value = ::Math::PointerCastToIntegral<int32>(constSrc->AsAddrOpnd()->m_address);
  7671. }
  7672. }
  7673. else if (constSrc->IsIntConstOpnd())
  7674. {
  7675. value = constSrc->AsIntConstOpnd()->AsInt32();
  7676. }
  7677. else
  7678. {
  7679. return false;
  7680. }
  7681. switch(instr->m_opcode)
  7682. {
  7683. // Can't do all Add_A because of string concats.
  7684. // Sub_A cannot be transformed to a NEG_A because 0 - 0 != -0
  7685. case Js::OpCode::Add_A:
  7686. src = nonConstSrc;
  7687. if (!src->GetValueType().IsInt())
  7688. {
  7689. // 0 + -0 != -0
  7690. // "Foo" + 0 != "Foo
  7691. return false;
  7692. }
  7693. // fall-through
  7694. case Js::OpCode::Add_Ptr:
  7695. case Js::OpCode::Add_I4:
  7696. if (value != 0)
  7697. {
  7698. return false;
  7699. }
  7700. if (constSrc == instr->GetSrc1())
  7701. {
  7702. src = instr->GetSrc2();
  7703. }
  7704. else
  7705. {
  7706. src = instr->GetSrc1();
  7707. }
  7708. break;
  7709. case Js::OpCode::Mul_A:
  7710. case Js::OpCode::Mul_I4:
  7711. if (value == 0)
  7712. {
  7713. // -0 * 0 != 0
  7714. return false;
  7715. }
  7716. else if (value == 1)
  7717. {
  7718. src = nonConstSrc;
  7719. }
  7720. else
  7721. {
  7722. return false;
  7723. }
  7724. break;
  7725. case Js::OpCode::Div_A:
  7726. if (value == 1 && constSrc == instr->GetSrc2())
  7727. {
  7728. src = instr->GetSrc1();
  7729. }
  7730. else
  7731. {
  7732. return false;
  7733. }
  7734. break;
  7735. case Js::OpCode::Or_I4:
  7736. if (value == -1)
  7737. {
  7738. src = constSrc;
  7739. }
  7740. else if (value == 0)
  7741. {
  7742. src = nonConstSrc;
  7743. }
  7744. else
  7745. {
  7746. return false;
  7747. }
  7748. break;
  7749. case Js::OpCode::And_I4:
  7750. if (value == -1)
  7751. {
  7752. src = nonConstSrc;
  7753. }
  7754. else if (value == 0)
  7755. {
  7756. src = constSrc;
  7757. }
  7758. else
  7759. {
  7760. return false;
  7761. }
  7762. break;
  7763. case Js::OpCode::Shl_I4:
  7764. case Js::OpCode::ShrU_I4:
  7765. case Js::OpCode::Shr_I4:
  7766. if (value != 0 || constSrc != instr->GetSrc2())
  7767. {
  7768. return false;
  7769. }
  7770. src = instr->GetSrc1();
  7771. break;
  7772. default:
  7773. return false;
  7774. }
  7775. this->CaptureByteCodeSymUses(instr);
  7776. if (src == instr->GetSrc1())
  7777. {
  7778. instr->FreeSrc2();
  7779. }
  7780. else
  7781. {
  7782. Assert(src == instr->GetSrc2());
  7783. instr->ReplaceSrc1(instr->UnlinkSrc2());
  7784. }
  7785. instr->m_opcode = Js::OpCode::Ld_A;
  7786. return true;
  7787. }
  7788. Js::Var
  7789. GlobOpt::GetConstantVar(IR::Opnd *opnd, Value *val)
  7790. {
  7791. ValueInfo *valueInfo = val->GetValueInfo();
  7792. if (valueInfo->IsVarConstant() && valueInfo->IsPrimitive())
  7793. {
  7794. return valueInfo->AsVarConstant()->VarValue();
  7795. }
  7796. if (opnd->IsAddrOpnd())
  7797. {
  7798. IR::AddrOpnd *addrOpnd = opnd->AsAddrOpnd();
  7799. if (addrOpnd->IsVar())
  7800. {
  7801. return addrOpnd->m_address;
  7802. }
  7803. }
  7804. else if (opnd->IsIntConstOpnd())
  7805. {
  7806. if (!Js::TaggedInt::IsOverflow(opnd->AsIntConstOpnd()->AsInt32()))
  7807. {
  7808. return Js::TaggedInt::ToVarUnchecked(opnd->AsIntConstOpnd()->AsInt32());
  7809. }
  7810. }
  7811. else if (opnd->IsRegOpnd() && opnd->AsRegOpnd()->m_sym->IsSingleDef())
  7812. {
  7813. if (valueInfo->IsBoolean())
  7814. {
  7815. IR::Instr * defInstr = opnd->AsRegOpnd()->m_sym->GetInstrDef();
  7816. if (defInstr->m_opcode != Js::OpCode::Ld_A || !defInstr->GetSrc1()->IsAddrOpnd())
  7817. {
  7818. return nullptr;
  7819. }
  7820. Assert(defInstr->GetSrc1()->AsAddrOpnd()->IsVar());
  7821. return defInstr->GetSrc1()->AsAddrOpnd()->m_address;
  7822. }
  7823. else if (valueInfo->IsUndefined())
  7824. {
  7825. return this->func->GetScriptContext()->GetLibrary()->GetUndefined();
  7826. }
  7827. else if (valueInfo->IsNull())
  7828. {
  7829. return this->func->GetScriptContext()->GetLibrary()->GetNull();
  7830. }
  7831. }
  7832. return nullptr;
  7833. }
  7834. bool
  7835. GlobOpt::OptConstFoldBranch(IR::Instr *instr, Value *src1Val, Value*src2Val, Value **pDstVal)
  7836. {
  7837. if (!src1Val)
  7838. {
  7839. return false;
  7840. }
  7841. Js::Var src1Var = this->GetConstantVar(instr->GetSrc1(), src1Val);
  7842. Js::Var src2Var = nullptr;
  7843. if (instr->GetSrc2())
  7844. {
  7845. if (!src2Val)
  7846. {
  7847. return false;
  7848. }
  7849. src2Var = this->GetConstantVar(instr->GetSrc2(), src2Val);
  7850. }
  7851. // Make sure GetConstantVar only returns primitives.
  7852. Assert(!src1Var || !Js::JavascriptOperators::IsObject(src1Var));
  7853. Assert(!src2Var || !Js::JavascriptOperators::IsObject(src2Var));
  7854. BOOL result;
  7855. int32 constVal;
  7856. switch (instr->m_opcode)
  7857. {
  7858. case Js::OpCode::BrEq_A:
  7859. case Js::OpCode::BrNotNeq_A:
  7860. if (!src1Var || !src2Var)
  7861. {
  7862. return false;
  7863. }
  7864. result = Js::JavascriptOperators::Equal(src1Var, src2Var, this->func->GetScriptContext());
  7865. break;
  7866. case Js::OpCode::BrNeq_A:
  7867. case Js::OpCode::BrNotEq_A:
  7868. if (!src1Var || !src2Var)
  7869. {
  7870. return false;
  7871. }
  7872. result = Js::JavascriptOperators::NotEqual(src1Var, src2Var, this->func->GetScriptContext());
  7873. break;
  7874. case Js::OpCode::BrSrEq_A:
  7875. case Js::OpCode::BrSrNotNeq_A:
  7876. if (!src1Var || !src2Var)
  7877. {
  7878. ValueInfo *src1ValInfo = src1Val->GetValueInfo();
  7879. ValueInfo *src2ValInfo = src2Val->GetValueInfo();
  7880. if (src1ValInfo->IsUndefined() && src2ValInfo->IsDefinite() && !src2ValInfo->HasBeenUndefined())
  7881. {
  7882. result = false;
  7883. }
  7884. else if (src1ValInfo->IsNull() && src2ValInfo->IsDefinite() && !src2ValInfo->HasBeenNull())
  7885. {
  7886. result = false;
  7887. }
  7888. else if (src2ValInfo->IsUndefined() && src1ValInfo->IsDefinite() && !src1ValInfo->HasBeenUndefined())
  7889. {
  7890. result = false;
  7891. }
  7892. else if (src2ValInfo->IsNull() && src1ValInfo->IsDefinite() && !src1ValInfo->HasBeenNull())
  7893. {
  7894. result = false;
  7895. }
  7896. else
  7897. {
  7898. return false;
  7899. }
  7900. }
  7901. else
  7902. {
  7903. result = Js::JavascriptOperators::StrictEqual(src1Var, src2Var, this->func->GetScriptContext());
  7904. }
  7905. break;
  7906. case Js::OpCode::BrSrNeq_A:
  7907. case Js::OpCode::BrSrNotEq_A:
  7908. if (!src1Var || !src2Var)
  7909. {
  7910. ValueInfo *src1ValInfo = src1Val->GetValueInfo();
  7911. ValueInfo *src2ValInfo = src2Val->GetValueInfo();
  7912. if (src1ValInfo->IsUndefined() && src2ValInfo->IsDefinite() && !src2ValInfo->HasBeenUndefined())
  7913. {
  7914. result = true;
  7915. }
  7916. else if (src1ValInfo->IsNull() && src2ValInfo->IsDefinite() && !src2ValInfo->HasBeenNull())
  7917. {
  7918. result = true;
  7919. }
  7920. else if (src2ValInfo->IsUndefined() && src1ValInfo->IsDefinite() && !src1ValInfo->HasBeenUndefined())
  7921. {
  7922. result = true;
  7923. }
  7924. else if (src2ValInfo->IsNull() && src1ValInfo->IsDefinite() && !src1ValInfo->HasBeenNull())
  7925. {
  7926. result = true;
  7927. }
  7928. else
  7929. {
  7930. return false;
  7931. }
  7932. }
  7933. else
  7934. {
  7935. result = Js::JavascriptOperators::NotStrictEqual(src1Var, src2Var, this->func->GetScriptContext());
  7936. }
  7937. break;
  7938. case Js::OpCode::BrFalse_A:
  7939. case Js::OpCode::BrTrue_A:
  7940. {
  7941. ValueInfo *const src1ValueInfo = src1Val->GetValueInfo();
  7942. if(src1ValueInfo->IsNull() || src1ValueInfo->IsUndefined())
  7943. {
  7944. result = instr->m_opcode == Js::OpCode::BrFalse_A;
  7945. break;
  7946. }
  7947. if(src1ValueInfo->IsObject() && src1ValueInfo->GetObjectType() > ObjectType::Object)
  7948. {
  7949. // Specific object types that are tracked are equivalent to 'true'
  7950. result = instr->m_opcode == Js::OpCode::BrTrue_A;
  7951. break;
  7952. }
  7953. if (!src1Var)
  7954. {
  7955. return false;
  7956. }
  7957. result = Js::JavascriptConversion::ToBoolean(src1Var, this->func->GetScriptContext());
  7958. if(instr->m_opcode == Js::OpCode::BrFalse_A)
  7959. {
  7960. result = !result;
  7961. }
  7962. break;
  7963. }
  7964. case Js::OpCode::BrFalse_I4:
  7965. // this path would probably work outside of asm.js, but we should verify that if we ever hit this scenario
  7966. Assert(GetIsAsmJSFunc());
  7967. constVal = 0;
  7968. if (src1Val->GetValueInfo()->TryGetIntConstantValue(&constVal) && constVal != 0)
  7969. {
  7970. instr->FreeSrc1();
  7971. if (instr->GetSrc2())
  7972. {
  7973. instr->FreeSrc2();
  7974. }
  7975. instr->m_opcode = Js::OpCode::Nop;
  7976. return true;
  7977. }
  7978. return false;
  7979. default:
  7980. return false;
  7981. }
  7982. this->OptConstFoldBr(!!result, instr);
  7983. return true;
  7984. }
  7985. bool
  7986. GlobOpt::OptConstFoldUnary(
  7987. IR::Instr * *pInstr,
  7988. const int32 intConstantValue,
  7989. const bool isUsingOriginalSrc1Value,
  7990. Value **pDstVal)
  7991. {
  7992. IR::Instr * &instr = *pInstr;
  7993. int32 value = 0;
  7994. IR::Opnd *constOpnd;
  7995. bool isInt = true;
  7996. bool doSetDstVal = true;
  7997. FloatConstType fValue = 0.0;
  7998. if (!DoConstFold())
  7999. {
  8000. return false;
  8001. }
  8002. if (instr->GetDst() && !instr->GetDst()->IsRegOpnd())
  8003. {
  8004. return false;
  8005. }
  8006. switch(instr->m_opcode)
  8007. {
  8008. case Js::OpCode::Neg_A:
  8009. if (intConstantValue == 0)
  8010. {
  8011. // Could fold to -0.0
  8012. return false;
  8013. }
  8014. if (Int32Math::Neg(intConstantValue, &value))
  8015. {
  8016. return false;
  8017. }
  8018. break;
  8019. case Js::OpCode::Not_A:
  8020. Int32Math::Not(intConstantValue, &value);
  8021. break;
  8022. case Js::OpCode::Ld_A:
  8023. if (instr->HasBailOutInfo())
  8024. {
  8025. //The profile data for switch expr can be string and in GlobOpt we realize it is an int.
  8026. if(instr->GetBailOutKind() == IR::BailOutExpectingString)
  8027. {
  8028. throw Js::RejitException(RejitReason::DisableSwitchOptExpectingString);
  8029. }
  8030. Assert(instr->GetBailOutKind() == IR::BailOutExpectingInteger);
  8031. instr->ClearBailOutInfo();
  8032. }
  8033. value = intConstantValue;
  8034. if(isUsingOriginalSrc1Value)
  8035. {
  8036. doSetDstVal = false; // Let OptDst do it by copying src1Val
  8037. }
  8038. break;
  8039. case Js::OpCode::Conv_Num:
  8040. case Js::OpCode::LdC_A_I4:
  8041. value = intConstantValue;
  8042. if(isUsingOriginalSrc1Value)
  8043. {
  8044. doSetDstVal = false; // Let OptDst do it by copying src1Val
  8045. }
  8046. break;
  8047. case Js::OpCode::Incr_A:
  8048. if (Int32Math::Inc(intConstantValue, &value))
  8049. {
  8050. return false;
  8051. }
  8052. break;
  8053. case Js::OpCode::Decr_A:
  8054. if (Int32Math::Dec(intConstantValue, &value))
  8055. {
  8056. return false;
  8057. }
  8058. break;
  8059. case Js::OpCode::InlineMathAcos:
  8060. fValue = Js::Math::Acos((double)intConstantValue);
  8061. isInt = false;
  8062. break;
  8063. case Js::OpCode::InlineMathAsin:
  8064. fValue = Js::Math::Asin((double)intConstantValue);
  8065. isInt = false;
  8066. break;
  8067. case Js::OpCode::InlineMathAtan:
  8068. fValue = Js::Math::Atan((double)intConstantValue);
  8069. isInt = false;
  8070. break;
  8071. case Js::OpCode::InlineMathCos:
  8072. fValue = Js::Math::Cos((double)intConstantValue);
  8073. isInt = false;
  8074. break;
  8075. case Js::OpCode::InlineMathExp:
  8076. fValue = Js::Math::Exp((double)intConstantValue);
  8077. isInt = false;
  8078. break;
  8079. case Js::OpCode::InlineMathLog:
  8080. fValue = Js::Math::Log((double)intConstantValue);
  8081. isInt = false;
  8082. break;
  8083. case Js::OpCode::InlineMathSin:
  8084. fValue = Js::Math::Sin((double)intConstantValue);
  8085. isInt = false;
  8086. break;
  8087. case Js::OpCode::InlineMathSqrt:
  8088. fValue = ::sqrt((double)intConstantValue);
  8089. isInt = false;
  8090. break;
  8091. case Js::OpCode::InlineMathTan:
  8092. fValue = ::tan((double)intConstantValue);
  8093. isInt = false;
  8094. break;
  8095. case Js::OpCode::InlineMathFround:
  8096. fValue = (double) (float) intConstantValue;
  8097. isInt = false;
  8098. break;
  8099. case Js::OpCode::InlineMathAbs:
  8100. if (intConstantValue == INT32_MIN)
  8101. {
  8102. if (instr->GetDst()->IsInt32())
  8103. {
  8104. // if dst is an int (e.g. in asm.js), we should coerce it, not convert to float
  8105. value = static_cast<int32>(2147483648U);
  8106. }
  8107. else
  8108. {
  8109. isInt = false;
  8110. fValue = -(FloatConstType)INT32_MIN;
  8111. }
  8112. }
  8113. else
  8114. {
  8115. value = ::abs(intConstantValue);
  8116. }
  8117. break;
  8118. case Js::OpCode::InlineMathClz32:
  8119. DWORD clz;
  8120. if (_BitScanReverse(&clz, intConstantValue))
  8121. {
  8122. value = 31 - clz;
  8123. }
  8124. else
  8125. {
  8126. value = 32;
  8127. }
  8128. instr->ClearBailOutInfo();
  8129. break;
  8130. case Js::OpCode::InlineMathFloor:
  8131. value = intConstantValue;
  8132. instr->ClearBailOutInfo();
  8133. break;
  8134. case Js::OpCode::InlineMathCeil:
  8135. value = intConstantValue;
  8136. instr->ClearBailOutInfo();
  8137. break;
  8138. case Js::OpCode::InlineMathRound:
  8139. value = intConstantValue;
  8140. instr->ClearBailOutInfo();
  8141. break;
  8142. case Js::OpCode::ToVar:
  8143. if (Js::TaggedInt::IsOverflow(intConstantValue))
  8144. {
  8145. return false;
  8146. }
  8147. else
  8148. {
  8149. value = intConstantValue;
  8150. instr->ClearBailOutInfo();
  8151. break;
  8152. }
  8153. default:
  8154. return false;
  8155. }
  8156. this->CaptureByteCodeSymUses(instr);
  8157. Assert(!instr->HasBailOutInfo()); // If we are, in fact, successful in constant folding the instruction, there is no point in having the bailoutinfo around anymore.
  8158. // Make sure that it is cleared if it was initially present.
  8159. if (!isInt)
  8160. {
  8161. value = (int32)fValue;
  8162. if (fValue == (double)value)
  8163. {
  8164. isInt = true;
  8165. }
  8166. }
  8167. if (isInt)
  8168. {
  8169. constOpnd = IR::IntConstOpnd::New(value, TyInt32, instr->m_func);
  8170. GOPT_TRACE(_u("Constant folding to %d\n"), value);
  8171. }
  8172. else
  8173. {
  8174. constOpnd = IR::FloatConstOpnd::New(fValue, TyFloat64, instr->m_func);
  8175. GOPT_TRACE(_u("Constant folding to %f\n"), fValue);
  8176. }
  8177. instr->ReplaceSrc1(constOpnd);
  8178. this->OptSrc(constOpnd, &instr);
  8179. IR::Opnd *dst = instr->GetDst();
  8180. Assert(dst->IsRegOpnd());
  8181. StackSym *dstSym = dst->AsRegOpnd()->m_sym;
  8182. if (isInt)
  8183. {
  8184. if (dstSym->IsSingleDef())
  8185. {
  8186. dstSym->SetIsIntConst(value);
  8187. }
  8188. if (doSetDstVal)
  8189. {
  8190. *pDstVal = GetIntConstantValue(value, instr, dst);
  8191. }
  8192. if (IsTypeSpecPhaseOff(this->func))
  8193. {
  8194. instr->m_opcode = Js::OpCode::LdC_A_I4;
  8195. this->ToVarRegOpnd(dst->AsRegOpnd(), this->currentBlock);
  8196. }
  8197. else
  8198. {
  8199. instr->m_opcode = Js::OpCode::Ld_I4;
  8200. this->ToInt32Dst(instr, dst->AsRegOpnd(), this->currentBlock);
  8201. StackSym *dstSym = instr->GetDst()->AsRegOpnd()->m_sym;
  8202. if (dstSym->IsSingleDef())
  8203. {
  8204. dstSym->SetIsIntConst(value);
  8205. }
  8206. }
  8207. }
  8208. else
  8209. {
  8210. *pDstVal = NewFloatConstantValue(fValue, dst);
  8211. if (IsTypeSpecPhaseOff(this->func))
  8212. {
  8213. instr->m_opcode = Js::OpCode::LdC_A_R8;
  8214. this->ToVarRegOpnd(dst->AsRegOpnd(), this->currentBlock);
  8215. }
  8216. else
  8217. {
  8218. instr->m_opcode = Js::OpCode::LdC_F8_R8;
  8219. this->ToFloat64Dst(instr, dst->AsRegOpnd(), this->currentBlock);
  8220. }
  8221. }
  8222. return true;
  8223. }
  8224. //------------------------------------------------------------------------------------------------------
  8225. // Type specialization
  8226. //------------------------------------------------------------------------------------------------------
  8227. bool
  8228. GlobOpt::IsWorthSpecializingToInt32DueToSrc(IR::Opnd *const src, Value *const val)
  8229. {
  8230. Assert(src);
  8231. Assert(val);
  8232. ValueInfo *valueInfo = val->GetValueInfo();
  8233. Assert(valueInfo->IsLikelyInt());
  8234. // If it is not known that the operand is definitely an int, the operand is not already type-specialized, and it's not live
  8235. // in the loop landing pad (if we're in a loop), it's probably not worth type-specializing this instruction. The common case
  8236. // where type-specializing this would be bad is where the operations are entirely on properties or array elements, where the
  8237. // ratio of FromVars and ToVars to the number of actual operations is high, and the conversions would dominate the time
  8238. // spent. On the other hand, if we're using a function formal parameter more than once, it would probably be worth
  8239. // type-specializing it, hence the IsDead check on the operands.
  8240. return
  8241. valueInfo->IsInt() ||
  8242. valueInfo->HasIntConstantValue(true) ||
  8243. !src->GetIsDead() ||
  8244. !src->IsRegOpnd() ||
  8245. this->IsInt32TypeSpecialized(src->AsRegOpnd()->m_sym, this->currentBlock) ||
  8246. this->currentBlock->loop && this->IsLive(src->AsRegOpnd()->m_sym, this->currentBlock->loop->landingPad);
  8247. }
  8248. bool
  8249. GlobOpt::IsWorthSpecializingToInt32DueToDst(IR::Opnd *const dst)
  8250. {
  8251. Assert(dst);
  8252. const auto sym = dst->AsRegOpnd()->m_sym;
  8253. return
  8254. this->IsInt32TypeSpecialized(sym, this->currentBlock) ||
  8255. this->currentBlock->loop && this->IsLive(sym, this->currentBlock->loop->landingPad);
  8256. }
  8257. bool
  8258. GlobOpt::IsWorthSpecializingToInt32(IR::Instr *const instr, Value *const src1Val, Value *const src2Val)
  8259. {
  8260. Assert(instr);
  8261. const auto src1 = instr->GetSrc1();
  8262. const auto src2 = instr->GetSrc2();
  8263. // In addition to checking each operand and the destination, if for any reason we only have to do a maximum of two
  8264. // conversions instead of the worst-case 3 conversions, it's probably worth specializing.
  8265. if (IsWorthSpecializingToInt32DueToSrc(src1, src1Val) ||
  8266. src2Val && IsWorthSpecializingToInt32DueToSrc(src2, src2Val))
  8267. {
  8268. return true;
  8269. }
  8270. IR::Opnd *dst = instr->GetDst();
  8271. if (!dst || IsWorthSpecializingToInt32DueToDst(dst))
  8272. {
  8273. return true;
  8274. }
  8275. if (dst->IsEqual(src1) || src2Val && (dst->IsEqual(src2) || src1->IsEqual(src2)))
  8276. {
  8277. return true;
  8278. }
  8279. IR::Instr *instrNext = instr->GetNextRealInstrOrLabel();
  8280. // Skip useless Ld_A's
  8281. do
  8282. {
  8283. switch (instrNext->m_opcode)
  8284. {
  8285. case Js::OpCode::Ld_A:
  8286. if (!dst->IsEqual(instrNext->GetSrc1()))
  8287. {
  8288. goto done;
  8289. }
  8290. dst = instrNext->GetDst();
  8291. break;
  8292. case Js::OpCode::LdFld:
  8293. case Js::OpCode::LdRootFld:
  8294. case Js::OpCode::LdRootFldForTypeOf:
  8295. case Js::OpCode::LdFldForTypeOf:
  8296. case Js::OpCode::LdElemI_A:
  8297. case Js::OpCode::ByteCodeUses:
  8298. break;
  8299. default:
  8300. goto done;
  8301. }
  8302. instrNext = instrNext->GetNextRealInstrOrLabel();
  8303. } while (true);
  8304. done:
  8305. // If the next instr could also be type specialized, then it is probably worth it.
  8306. if ((instrNext->GetSrc1() && dst->IsEqual(instrNext->GetSrc1())) || (instrNext->GetSrc2() && dst->IsEqual(instrNext->GetSrc2())))
  8307. {
  8308. switch (instrNext->m_opcode)
  8309. {
  8310. case Js::OpCode::Add_A:
  8311. case Js::OpCode::Sub_A:
  8312. case Js::OpCode::Mul_A:
  8313. case Js::OpCode::Div_A:
  8314. case Js::OpCode::Rem_A:
  8315. case Js::OpCode::Xor_A:
  8316. case Js::OpCode::And_A:
  8317. case Js::OpCode::Or_A:
  8318. case Js::OpCode::Shl_A:
  8319. case Js::OpCode::Shr_A:
  8320. case Js::OpCode::Incr_A:
  8321. case Js::OpCode::Decr_A:
  8322. case Js::OpCode::Neg_A:
  8323. case Js::OpCode::Not_A:
  8324. case Js::OpCode::Conv_Num:
  8325. case Js::OpCode::BrEq_I4:
  8326. case Js::OpCode::BrTrue_I4:
  8327. case Js::OpCode::BrFalse_I4:
  8328. case Js::OpCode::BrGe_I4:
  8329. case Js::OpCode::BrGt_I4:
  8330. case Js::OpCode::BrLt_I4:
  8331. case Js::OpCode::BrLe_I4:
  8332. case Js::OpCode::BrNeq_I4:
  8333. return true;
  8334. }
  8335. }
  8336. return false;
  8337. }
  8338. bool
  8339. GlobOpt::TypeSpecializeNumberUnary(IR::Instr *instr, Value *src1Val, Value **pDstVal)
  8340. {
  8341. Assert(src1Val->GetValueInfo()->IsNumber());
  8342. if (this->IsLoopPrePass())
  8343. {
  8344. return false;
  8345. }
  8346. switch (instr->m_opcode)
  8347. {
  8348. case Js::OpCode::Conv_Num:
  8349. // Optimize Conv_Num away since we know this is a number
  8350. instr->m_opcode = Js::OpCode::Ld_A;
  8351. return false;
  8352. }
  8353. return false;
  8354. }
  8355. bool
  8356. GlobOpt::TypeSpecializeUnary(
  8357. IR::Instr **pInstr,
  8358. Value **pSrc1Val,
  8359. Value **pDstVal,
  8360. Value *const src1OriginalVal,
  8361. bool *redoTypeSpecRef,
  8362. bool *const forceInvariantHoistingRef)
  8363. {
  8364. Assert(pSrc1Val);
  8365. Value *&src1Val = *pSrc1Val;
  8366. Assert(src1Val);
  8367. // We don't need to do typespec for asmjs
  8368. if (IsTypeSpecPhaseOff(this->func) || GetIsAsmJSFunc())
  8369. {
  8370. return false;
  8371. }
  8372. IR::Instr *&instr = *pInstr;
  8373. int32 min, max;
  8374. // Inline built-ins explicitly specify how srcs/dst must be specialized.
  8375. if (OpCodeAttr::IsInlineBuiltIn(instr->m_opcode))
  8376. {
  8377. TypeSpecializeInlineBuiltInUnary(pInstr, &src1Val, pDstVal, src1OriginalVal, redoTypeSpecRef);
  8378. return true;
  8379. }
  8380. // Consider: If type spec wasn't completely done, make sure that we don't type-spec the dst 2nd time.
  8381. if(instr->m_opcode == Js::OpCode::LdLen_A && TypeSpecializeLdLen(&instr, &src1Val, pDstVal, forceInvariantHoistingRef))
  8382. {
  8383. return true;
  8384. }
  8385. if (!src1Val->GetValueInfo()->GetIntValMinMax(&min, &max, this->DoAggressiveIntTypeSpec()))
  8386. {
  8387. src1Val = src1OriginalVal;
  8388. if (src1Val->GetValueInfo()->IsLikelyFloat())
  8389. {
  8390. // Try to type specialize to float
  8391. return this->TypeSpecializeFloatUnary(pInstr, src1Val, pDstVal);
  8392. }
  8393. else if (src1Val->GetValueInfo()->IsNumber())
  8394. {
  8395. return TypeSpecializeNumberUnary(instr, src1Val, pDstVal);
  8396. }
  8397. return TryTypeSpecializeUnaryToFloatHelper(pInstr, &src1Val, src1OriginalVal, pDstVal);
  8398. }
  8399. return this->TypeSpecializeIntUnary(pInstr, &src1Val, pDstVal, min, max, src1OriginalVal, redoTypeSpecRef);
  8400. }
  8401. // Returns true if the built-in requested type specialization, and no further action needed,
  8402. // otherwise returns false.
  8403. void
  8404. GlobOpt::TypeSpecializeInlineBuiltInUnary(IR::Instr **pInstr, Value **pSrc1Val, Value **pDstVal, Value *const src1OriginalVal, bool *redoTypeSpecRef)
  8405. {
  8406. IR::Instr *&instr = *pInstr;
  8407. Assert(pSrc1Val);
  8408. Value *&src1Val = *pSrc1Val;
  8409. Assert(OpCodeAttr::IsInlineBuiltIn(instr->m_opcode));
  8410. Js::BuiltinFunction builtInId = Js::JavascriptLibrary::GetBuiltInInlineCandidateId(instr->m_opcode); // From actual instr, not profile based.
  8411. Assert(builtInId != Js::BuiltinFunction::None);
  8412. // Consider using different bailout for float/int FromVars, so that when the arg cannot be converted to number we don't disable
  8413. // type spec for other parts of the big function but rather just don't inline that built-in instr.
  8414. // E.g. could do that if the value is not likelyInt/likelyFloat.
  8415. Js::BuiltInFlags builtInFlags = Js::JavascriptLibrary::GetFlagsForBuiltIn(builtInId);
  8416. bool areAllArgsAlwaysFloat = (builtInFlags & Js::BuiltInFlags::BIF_Args) == Js::BuiltInFlags::BIF_TypeSpecUnaryToFloat;
  8417. if (areAllArgsAlwaysFloat)
  8418. {
  8419. // InlineMathAcos, InlineMathAsin, InlineMathAtan, InlineMathCos, InlineMathExp, InlineMathLog, InlineMathSin, InlineMathSqrt, InlineMathTan.
  8420. Assert(this->DoFloatTypeSpec());
  8421. // Type-spec the src.
  8422. src1Val = src1OriginalVal;
  8423. bool retVal = this->TypeSpecializeFloatUnary(pInstr, src1Val, pDstVal, /* skipDst = */ true);
  8424. AssertMsg(retVal, "For inline built-ins the args have to be type-specialized to float, but something failed during the process.");
  8425. // Type-spec the dst.
  8426. this->TypeSpecializeFloatDst(instr, nullptr, src1Val, nullptr, pDstVal);
  8427. }
  8428. else if (instr->m_opcode == Js::OpCode::InlineMathAbs)
  8429. {
  8430. // Consider the case when the value is unknown - because of bailout in abs we may disable type spec for the whole function which is too much.
  8431. // First, try int.
  8432. int minVal, maxVal;
  8433. bool shouldTypeSpecToInt = src1Val->GetValueInfo()->GetIntValMinMax(&minVal, &maxVal, /* doAggressiveIntTypeSpec = */ true);
  8434. if (shouldTypeSpecToInt)
  8435. {
  8436. Assert(this->DoAggressiveIntTypeSpec());
  8437. bool retVal = this->TypeSpecializeIntUnary(pInstr, &src1Val, pDstVal, minVal, maxVal, src1OriginalVal, redoTypeSpecRef, true);
  8438. AssertMsg(retVal, "For inline built-ins the args have to be type-specialized (int), but something failed during the process.");
  8439. if (!this->IsLoopPrePass())
  8440. {
  8441. // Create bailout for INT_MIN which does not have corresponding int value on the positive side.
  8442. // Check int range: if we know the range is out of overflow, we do not need the bail out at all.
  8443. if (minVal == INT32_MIN)
  8444. {
  8445. GenerateBailAtOperation(&instr, IR::BailOnIntMin);
  8446. }
  8447. }
  8448. // Account for ::abs(INT_MIN) == INT_MIN (which is less than 0).
  8449. maxVal = ::max(
  8450. ::abs(Int32Math::NearestInRangeTo(minVal, INT_MIN + 1, INT_MAX)),
  8451. ::abs(Int32Math::NearestInRangeTo(maxVal, INT_MIN + 1, INT_MAX)));
  8452. minVal = minVal >= 0 ? minVal : 0;
  8453. this->TypeSpecializeIntDst(instr, instr->m_opcode, nullptr, src1Val, nullptr, IR::BailOutInvalid, minVal, maxVal, pDstVal);
  8454. }
  8455. else
  8456. {
  8457. // If we couldn't do int, do float.
  8458. Assert(this->DoFloatTypeSpec());
  8459. src1Val = src1OriginalVal;
  8460. bool retVal = this->TypeSpecializeFloatUnary(pInstr, src1Val, pDstVal, true);
  8461. AssertMsg(retVal, "For inline built-ins the args have to be type-specialized (float), but something failed during the process.");
  8462. this->TypeSpecializeFloatDst(instr, nullptr, src1Val, nullptr, pDstVal);
  8463. }
  8464. }
  8465. else if (instr->m_opcode == Js::OpCode::InlineMathFloor || instr->m_opcode == Js::OpCode::InlineMathCeil || instr->m_opcode == Js::OpCode::InlineMathRound)
  8466. {
  8467. // Type specialize src to float
  8468. src1Val = src1OriginalVal;
  8469. bool retVal = this->TypeSpecializeFloatUnary(pInstr, src1Val, pDstVal, /* skipDst = */ true);
  8470. AssertMsg(retVal, "For inline Math.floor and Math.ceil the src has to be type-specialized to float, but something failed during the process.");
  8471. // Type specialize dst to int
  8472. this->TypeSpecializeIntDst(
  8473. instr,
  8474. instr->m_opcode,
  8475. nullptr,
  8476. src1Val,
  8477. nullptr,
  8478. IR::BailOutInvalid,
  8479. INT32_MIN,
  8480. INT32_MAX,
  8481. pDstVal);
  8482. }
  8483. else if(instr->m_opcode == Js::OpCode::InlineArrayPop)
  8484. {
  8485. IR::Opnd *const thisOpnd = instr->GetSrc1();
  8486. Assert(thisOpnd);
  8487. // Ensure src1 (Array) is a var
  8488. this->ToVarUses(instr, thisOpnd, false, src1Val);
  8489. if(!this->IsLoopPrePass() && thisOpnd->GetValueType().IsLikelyNativeArray())
  8490. {
  8491. // We bail out, if there is illegal access or a mismatch in the Native array type that is optimized for, during the run time.
  8492. GenerateBailAtOperation(&instr, IR::BailOutConventionalNativeArrayAccessOnly);
  8493. }
  8494. if(!instr->GetDst())
  8495. {
  8496. return;
  8497. }
  8498. // Try Type Specializing the element (return item from Pop) based on the array's profile data.
  8499. if(thisOpnd->GetValueType().IsLikelyNativeIntArray())
  8500. {
  8501. this->TypeSpecializeIntDst(instr, instr->m_opcode, nullptr, nullptr, nullptr, IR::BailOutInvalid, INT32_MIN, INT32_MAX, pDstVal);
  8502. }
  8503. else if(thisOpnd->GetValueType().IsLikelyNativeFloatArray())
  8504. {
  8505. this->TypeSpecializeFloatDst(instr, nullptr, nullptr, nullptr, pDstVal);
  8506. }
  8507. else
  8508. {
  8509. // We reached here so the Element is not yet type specialized. Ensure element is a var
  8510. if(instr->GetDst()->IsRegOpnd())
  8511. {
  8512. this->ToVarRegOpnd(instr->GetDst()->AsRegOpnd(), currentBlock);
  8513. }
  8514. }
  8515. }
  8516. else if (instr->m_opcode == Js::OpCode::InlineMathClz32)
  8517. {
  8518. Assert(this->DoAggressiveIntTypeSpec());
  8519. Assert(this->DoLossyIntTypeSpec());
  8520. //Type specialize to int
  8521. bool retVal = this->TypeSpecializeIntUnary(pInstr, &src1Val, pDstVal, INT32_MIN, INT32_MAX, src1OriginalVal, redoTypeSpecRef);
  8522. AssertMsg(retVal, "For clz32, the arg has to be type-specialized to int.");
  8523. }
  8524. else
  8525. {
  8526. AssertMsg(FALSE, "Unsupported built-in!");
  8527. }
  8528. }
  8529. void
  8530. GlobOpt::TypeSpecializeInlineBuiltInBinary(IR::Instr **pInstr, Value *src1Val, Value* src2Val, Value **pDstVal, Value *const src1OriginalVal, Value *const src2OriginalVal)
  8531. {
  8532. IR::Instr *&instr = *pInstr;
  8533. Assert(OpCodeAttr::IsInlineBuiltIn(instr->m_opcode));
  8534. switch(instr->m_opcode)
  8535. {
  8536. case Js::OpCode::InlineMathAtan2:
  8537. case Js::OpCode::InlineMathPow:
  8538. {
  8539. Js::BuiltinFunction builtInId = Js::JavascriptLibrary::GetBuiltInInlineCandidateId(instr->m_opcode); // From actual instr, not profile based.
  8540. Js::BuiltInFlags builtInFlags = Js::JavascriptLibrary::GetFlagsForBuiltIn(builtInId);
  8541. bool areAllArgsAlwaysFloat = (builtInFlags & Js::BuiltInFlags::BIF_TypeSpecAllToFloat) != 0;
  8542. Assert(areAllArgsAlwaysFloat);
  8543. Assert(this->DoFloatTypeSpec());
  8544. // Type-spec the src1, src2 and dst.
  8545. src1Val = src1OriginalVal;
  8546. src2Val = src2OriginalVal;
  8547. bool retVal = this->TypeSpecializeFloatBinary(instr, src1Val, src2Val, pDstVal);
  8548. AssertMsg(retVal, "For pow and atnan2 the args have to be type-specialized to float, but something failed during the process.");
  8549. break;
  8550. }
  8551. case Js::OpCode::InlineMathImul:
  8552. {
  8553. Assert(this->DoAggressiveIntTypeSpec());
  8554. Assert(this->DoLossyIntTypeSpec());
  8555. //Type specialize to int
  8556. bool retVal = this->TypeSpecializeIntBinary(pInstr, src1Val, src2Val, pDstVal, INT32_MIN, INT32_MAX, false /* skipDst */);
  8557. AssertMsg(retVal, "For imul, the args have to be type-specialized to int but something failed during the process.");
  8558. break;
  8559. }
  8560. case Js::OpCode::InlineMathMin:
  8561. case Js::OpCode::InlineMathMax:
  8562. {
  8563. if(src1Val->GetValueInfo()->IsLikelyInt() && src2Val->GetValueInfo()->IsLikelyInt())
  8564. {
  8565. // Compute resulting range info
  8566. int32 min1, max1, min2, max2, newMin, newMax;
  8567. Assert(this->DoAggressiveIntTypeSpec());
  8568. src1Val->GetValueInfo()->GetIntValMinMax(&min1, &max1, this->DoAggressiveIntTypeSpec());
  8569. src2Val->GetValueInfo()->GetIntValMinMax(&min2, &max2, this->DoAggressiveIntTypeSpec());
  8570. if (instr->m_opcode == Js::OpCode::InlineMathMin)
  8571. {
  8572. newMin = min(min1, min2);
  8573. newMax = min(max1, max2);
  8574. }
  8575. else
  8576. {
  8577. Assert(instr->m_opcode == Js::OpCode::InlineMathMax);
  8578. newMin = max(min1, min2);
  8579. newMax = max(max1, max2);
  8580. }
  8581. // Type specialize to int
  8582. bool retVal = this->TypeSpecializeIntBinary(pInstr, src1Val, src2Val, pDstVal, newMin, newMax, false /* skipDst */);
  8583. AssertMsg(retVal, "For min and max, the args have to be type-specialized to int if any one of the sources is an int, but something failed during the process.");
  8584. }
  8585. // Couldn't type specialize to int, type specialize to float
  8586. else
  8587. {
  8588. Assert(this->DoFloatTypeSpec());
  8589. src1Val = src1OriginalVal;
  8590. src2Val = src2OriginalVal;
  8591. bool retVal = this->TypeSpecializeFloatBinary(instr, src1Val, src2Val, pDstVal);
  8592. AssertMsg(retVal, "For min and max, the args have to be type-specialized to float if any one of the sources is a float, but something failed during the process.");
  8593. }
  8594. break;
  8595. }
  8596. case Js::OpCode::InlineArrayPush:
  8597. {
  8598. IR::Opnd *const thisOpnd = instr->GetSrc1();
  8599. Assert(thisOpnd);
  8600. if(instr->GetDst() && instr->GetDst()->IsRegOpnd())
  8601. {
  8602. // Set the dst as live here, as the built-ins return early from the TypeSpecialization functions - before the dst is marked as live.
  8603. // Also, we are not specializing the dst separately and we are skipping the dst to be handled when we specialize the instruction above.
  8604. this->ToVarRegOpnd(instr->GetDst()->AsRegOpnd(), currentBlock);
  8605. }
  8606. // Ensure src1 (Array) is a var
  8607. this->ToVarUses(instr, thisOpnd, false, src1Val);
  8608. if(!this->IsLoopPrePass())
  8609. {
  8610. if(thisOpnd->GetValueType().IsLikelyNativeArray())
  8611. {
  8612. // We bail out, if there is illegal access or a mismatch in the Native array type that is optimized for, during run time.
  8613. GenerateBailAtOperation(&instr, IR::BailOutConventionalNativeArrayAccessOnly);
  8614. }
  8615. else
  8616. {
  8617. GenerateBailAtOperation(&instr, IR::BailOutOnImplicitCallsPreOp);
  8618. }
  8619. }
  8620. // Try Type Specializing the element based on the array's profile data.
  8621. if(thisOpnd->GetValueType().IsLikelyNativeFloatArray())
  8622. {
  8623. src1Val = src1OriginalVal;
  8624. src2Val = src2OriginalVal;
  8625. }
  8626. if((thisOpnd->GetValueType().IsLikelyNativeIntArray() && this->TypeSpecializeIntBinary(pInstr, src1Val, src2Val, pDstVal, INT32_MIN, INT32_MAX, true))
  8627. || (thisOpnd->GetValueType().IsLikelyNativeFloatArray() && this->TypeSpecializeFloatBinary(instr, src1Val, src2Val, pDstVal)))
  8628. {
  8629. break;
  8630. }
  8631. // The Element is not yet type specialized. Ensure element is a var
  8632. this->ToVarUses(instr, instr->GetSrc2(), false, src2Val);
  8633. break;
  8634. }
  8635. }
  8636. }
  8637. void
  8638. GlobOpt::TypeSpecializeInlineBuiltInDst(IR::Instr **pInstr, Value **pDstVal)
  8639. {
  8640. IR::Instr *&instr = *pInstr;
  8641. Assert(OpCodeAttr::IsInlineBuiltIn(instr->m_opcode));
  8642. if (instr->m_opcode == Js::OpCode::InlineMathRandom)
  8643. {
  8644. Assert(this->DoFloatTypeSpec());
  8645. // Type specialize dst to float
  8646. this->TypeSpecializeFloatDst(instr, nullptr, nullptr, nullptr, pDstVal);
  8647. }
  8648. }
  8649. bool
  8650. GlobOpt::TryTypeSpecializeUnaryToFloatHelper(IR::Instr** pInstr, Value** pSrc1Val, Value* const src1OriginalVal, Value **pDstVal)
  8651. {
  8652. // It has been determined that this instruction cannot be int-specialized. We need to determine whether to attempt to
  8653. // float-specialize the instruction, or leave it unspecialized.
  8654. #if !INT32VAR
  8655. Value*& src1Val = *pSrc1Val;
  8656. if(src1Val->GetValueInfo()->IsLikelyUntaggedInt())
  8657. {
  8658. // An input range is completely outside the range of an int31. Even if the operation may overflow, it is
  8659. // unlikely to overflow on these operations, so we leave it unspecialized on 64-bit platforms. However, on
  8660. // 32-bit platforms, the value is untaggable and will be a JavascriptNumber, which is significantly slower to
  8661. // use in an unspecialized operation compared to a tagged int. So, try to float-specialize the instruction.
  8662. src1Val = src1OriginalVal;
  8663. return this->TypeSpecializeFloatUnary(pInstr, src1Val, pDstVal);
  8664. }
  8665. #endif
  8666. return false;
  8667. }
  8668. bool
  8669. GlobOpt::TypeSpecializeIntBinary(IR::Instr **pInstr, Value *src1Val, Value *src2Val, Value **pDstVal, int32 min, int32 max, bool skipDst /* = false */)
  8670. {
  8671. // Consider moving the code for int type spec-ing binary functions here.
  8672. IR::Instr *&instr = *pInstr;
  8673. bool lossy = false;
  8674. if(OpCodeAttr::IsInlineBuiltIn(instr->m_opcode))
  8675. {
  8676. if(instr->m_opcode == Js::OpCode::InlineArrayPush)
  8677. {
  8678. int32 intConstantValue;
  8679. bool isIntConstMissingItem = src2Val->GetValueInfo()->TryGetIntConstantValue(&intConstantValue);
  8680. if(isIntConstMissingItem)
  8681. {
  8682. isIntConstMissingItem = Js::SparseArraySegment<int>::IsMissingItem(&intConstantValue);
  8683. }
  8684. // Don't specialize if the element is not likelyInt or an IntConst which is a missing item value.
  8685. if(!(src2Val->GetValueInfo()->IsLikelyInt()) || isIntConstMissingItem)
  8686. {
  8687. return false;
  8688. }
  8689. // We don't want to specialize both the source operands, though it is a binary instr.
  8690. IR::Opnd * elementOpnd = instr->GetSrc2();
  8691. this->ToInt32(instr, elementOpnd, this->currentBlock, src2Val, nullptr, lossy);
  8692. }
  8693. else
  8694. {
  8695. IR::Opnd *src1 = instr->GetSrc1();
  8696. this->ToInt32(instr, src1, this->currentBlock, src1Val, nullptr, lossy);
  8697. IR::Opnd *src2 = instr->GetSrc2();
  8698. this->ToInt32(instr, src2, this->currentBlock, src2Val, nullptr, lossy);
  8699. }
  8700. if(!skipDst)
  8701. {
  8702. IR::Opnd *dst = instr->GetDst();
  8703. if (dst)
  8704. {
  8705. TypeSpecializeIntDst(instr, instr->m_opcode, nullptr, src1Val, src2Val, IR::BailOutInvalid, min, max, pDstVal);
  8706. }
  8707. }
  8708. return true;
  8709. }
  8710. else
  8711. {
  8712. AssertMsg(false, "Yet to move code for other binary functions here");
  8713. return false;
  8714. }
  8715. }
  8716. bool
  8717. GlobOpt::TypeSpecializeIntUnary(
  8718. IR::Instr **pInstr,
  8719. Value **pSrc1Val,
  8720. Value **pDstVal,
  8721. int32 min,
  8722. int32 max,
  8723. Value *const src1OriginalVal,
  8724. bool *redoTypeSpecRef,
  8725. bool skipDst /* = false */)
  8726. {
  8727. IR::Instr *&instr = *pInstr;
  8728. Assert(pSrc1Val);
  8729. Value *&src1Val = *pSrc1Val;
  8730. bool isTransfer = false;
  8731. Js::OpCode opcode;
  8732. int32 newMin, newMax;
  8733. bool lossy = false;
  8734. IR::BailOutKind bailOutKind = IR::BailOutInvalid;
  8735. bool ignoredIntOverflow = this->ignoredIntOverflowForCurrentInstr;
  8736. bool ignoredNegativeZero = false;
  8737. bool checkTypeSpecWorth = false;
  8738. if(instr->GetSrc1()->IsRegOpnd() && instr->GetSrc1()->AsRegOpnd()->m_sym->m_isNotInt)
  8739. {
  8740. return TryTypeSpecializeUnaryToFloatHelper(pInstr, &src1Val, src1OriginalVal, pDstVal);
  8741. }
  8742. AddSubConstantInfo addSubConstantInfo;
  8743. switch(instr->m_opcode)
  8744. {
  8745. case Js::OpCode::Ld_A:
  8746. if (instr->GetSrc1()->IsRegOpnd())
  8747. {
  8748. StackSym *sym = instr->GetSrc1()->AsRegOpnd()->m_sym;
  8749. if (this->IsInt32TypeSpecialized(sym, this->currentBlock) == false)
  8750. {
  8751. // Type specializing an Ld_A isn't worth it, unless the src
  8752. // is already type specialized.
  8753. return false;
  8754. }
  8755. }
  8756. newMin = min;
  8757. newMax = max;
  8758. opcode = Js::OpCode::Ld_I4;
  8759. isTransfer = true;
  8760. break;
  8761. case Js::OpCode::Conv_Num:
  8762. newMin = min;
  8763. newMax = max;
  8764. opcode = Js::OpCode::Ld_I4;
  8765. isTransfer = true;
  8766. break;
  8767. case Js::OpCode::LdC_A_I4:
  8768. newMin = newMax = instr->GetSrc1()->AsIntConstOpnd()->AsInt32();
  8769. opcode = Js::OpCode::Ld_I4;
  8770. break;
  8771. case Js::OpCode::Neg_A:
  8772. if (min <= 0 && max >= 0)
  8773. {
  8774. if(instr->ShouldCheckForNegativeZero())
  8775. {
  8776. // -0 matters since the sym is not a local, or is used in a way in which -0 would differ from +0
  8777. if(!DoAggressiveIntTypeSpec())
  8778. {
  8779. // May result in -0
  8780. // Consider adding a dynamic check for src1 == 0
  8781. return TryTypeSpecializeUnaryToFloatHelper(pInstr, &src1Val, src1OriginalVal, pDstVal);
  8782. }
  8783. if(min == 0 && max == 0)
  8784. {
  8785. // Always results in -0
  8786. return TryTypeSpecializeUnaryToFloatHelper(pInstr, &src1Val, src1OriginalVal, pDstVal);
  8787. }
  8788. bailOutKind |= IR::BailOutOnNegativeZero;
  8789. }
  8790. else
  8791. {
  8792. ignoredNegativeZero = true;
  8793. }
  8794. }
  8795. if (Int32Math::Neg(min, &newMax))
  8796. {
  8797. if(instr->ShouldCheckForIntOverflow())
  8798. {
  8799. if(!DoAggressiveIntTypeSpec())
  8800. {
  8801. // May overflow
  8802. return TryTypeSpecializeUnaryToFloatHelper(pInstr, &src1Val, src1OriginalVal, pDstVal);
  8803. }
  8804. if(min == max)
  8805. {
  8806. // Always overflows
  8807. return TryTypeSpecializeUnaryToFloatHelper(pInstr, &src1Val, src1OriginalVal, pDstVal);
  8808. }
  8809. bailOutKind |= IR::BailOutOnOverflow;
  8810. newMax = INT32_MAX;
  8811. }
  8812. else
  8813. {
  8814. ignoredIntOverflow = true;
  8815. }
  8816. }
  8817. if (Int32Math::Neg(max, &newMin))
  8818. {
  8819. if(instr->ShouldCheckForIntOverflow())
  8820. {
  8821. if(!DoAggressiveIntTypeSpec())
  8822. {
  8823. // May overflow
  8824. return TryTypeSpecializeUnaryToFloatHelper(pInstr, &src1Val, src1OriginalVal, pDstVal);
  8825. }
  8826. bailOutKind |= IR::BailOutOnOverflow;
  8827. newMin = INT32_MAX;
  8828. }
  8829. else
  8830. {
  8831. ignoredIntOverflow = true;
  8832. }
  8833. }
  8834. if(!instr->ShouldCheckForIntOverflow() && newMin > newMax)
  8835. {
  8836. // When ignoring overflow, the range needs to account for overflow. Since MIN_INT is the only int32 value that
  8837. // overflows on Neg, and the value resulting from overflow is also MIN_INT, if calculating only the new min or new
  8838. // max overflowed but not both, then the new min will be greater than the new max. In that case we need to consider
  8839. // the full range of int32s as possible resulting values.
  8840. newMin = INT32_MIN;
  8841. newMax = INT32_MAX;
  8842. }
  8843. opcode = Js::OpCode::Neg_I4;
  8844. checkTypeSpecWorth = true;
  8845. break;
  8846. case Js::OpCode::Not_A:
  8847. if(!DoLossyIntTypeSpec())
  8848. {
  8849. return false;
  8850. }
  8851. this->PropagateIntRangeForNot(min, max, &newMin, &newMax);
  8852. opcode = Js::OpCode::Not_I4;
  8853. lossy = true;
  8854. break;
  8855. case Js::OpCode::Incr_A:
  8856. do // while(false)
  8857. {
  8858. const auto CannotOverflowBasedOnRelativeBounds = [&]()
  8859. {
  8860. const ValueInfo *const src1ValueInfo = src1Val->GetValueInfo();
  8861. return
  8862. (src1ValueInfo->IsInt() || DoAggressiveIntTypeSpec()) &&
  8863. src1ValueInfo->IsIntBounded() &&
  8864. src1ValueInfo->AsIntBounded()->Bounds()->AddCannotOverflowBasedOnRelativeBounds(1);
  8865. };
  8866. if (Int32Math::Inc(min, &newMin))
  8867. {
  8868. if(CannotOverflowBasedOnRelativeBounds())
  8869. {
  8870. newMin = INT32_MAX;
  8871. }
  8872. else if(instr->ShouldCheckForIntOverflow())
  8873. {
  8874. // Always overflows
  8875. return TryTypeSpecializeUnaryToFloatHelper(pInstr, &src1Val, src1OriginalVal, pDstVal);
  8876. }
  8877. else
  8878. {
  8879. // When ignoring overflow, the range needs to account for overflow. For any Add or Sub, since overflow
  8880. // causes the value to wrap around, and we don't have a way to specify a lower and upper range of ints,
  8881. // we use the full range of int32s.
  8882. ignoredIntOverflow = true;
  8883. newMin = INT32_MIN;
  8884. newMax = INT32_MAX;
  8885. break;
  8886. }
  8887. }
  8888. if (Int32Math::Inc(max, &newMax))
  8889. {
  8890. if(CannotOverflowBasedOnRelativeBounds())
  8891. {
  8892. newMax = INT32_MAX;
  8893. }
  8894. else if(instr->ShouldCheckForIntOverflow())
  8895. {
  8896. if(!DoAggressiveIntTypeSpec())
  8897. {
  8898. // May overflow
  8899. return TryTypeSpecializeUnaryToFloatHelper(pInstr, &src1Val, src1OriginalVal, pDstVal);
  8900. }
  8901. bailOutKind |= IR::BailOutOnOverflow;
  8902. newMax = INT32_MAX;
  8903. }
  8904. else
  8905. {
  8906. // See comment about ignoring overflow above
  8907. ignoredIntOverflow = true;
  8908. newMin = INT32_MIN;
  8909. newMax = INT32_MAX;
  8910. break;
  8911. }
  8912. }
  8913. } while(false);
  8914. if(!ignoredIntOverflow && instr->GetSrc1()->IsRegOpnd())
  8915. {
  8916. addSubConstantInfo.Set(instr->GetSrc1()->AsRegOpnd()->m_sym, src1Val, min == max, 1);
  8917. }
  8918. opcode = Js::OpCode::Add_I4;
  8919. if (!this->IsLoopPrePass())
  8920. {
  8921. instr->SetSrc2(IR::IntConstOpnd::New(1, TyInt32, instr->m_func));
  8922. }
  8923. checkTypeSpecWorth = true;
  8924. break;
  8925. case Js::OpCode::Decr_A:
  8926. do // while(false)
  8927. {
  8928. const auto CannotOverflowBasedOnRelativeBounds = [&]()
  8929. {
  8930. const ValueInfo *const src1ValueInfo = src1Val->GetValueInfo();
  8931. return
  8932. (src1ValueInfo->IsInt() || DoAggressiveIntTypeSpec()) &&
  8933. src1ValueInfo->IsIntBounded() &&
  8934. src1ValueInfo->AsIntBounded()->Bounds()->SubCannotOverflowBasedOnRelativeBounds(1);
  8935. };
  8936. if (Int32Math::Dec(max, &newMax))
  8937. {
  8938. if(CannotOverflowBasedOnRelativeBounds())
  8939. {
  8940. newMax = INT32_MIN;
  8941. }
  8942. else if(instr->ShouldCheckForIntOverflow())
  8943. {
  8944. // Always overflows
  8945. return TryTypeSpecializeUnaryToFloatHelper(pInstr, &src1Val, src1OriginalVal, pDstVal);
  8946. }
  8947. else
  8948. {
  8949. // When ignoring overflow, the range needs to account for overflow. For any Add or Sub, since overflow
  8950. // causes the value to wrap around, and we don't have a way to specify a lower and upper range of ints, we
  8951. // use the full range of int32s.
  8952. ignoredIntOverflow = true;
  8953. newMin = INT32_MIN;
  8954. newMax = INT32_MAX;
  8955. break;
  8956. }
  8957. }
  8958. if (Int32Math::Dec(min, &newMin))
  8959. {
  8960. if(CannotOverflowBasedOnRelativeBounds())
  8961. {
  8962. newMin = INT32_MIN;
  8963. }
  8964. else if(instr->ShouldCheckForIntOverflow())
  8965. {
  8966. if(!DoAggressiveIntTypeSpec())
  8967. {
  8968. // May overflow
  8969. return TryTypeSpecializeUnaryToFloatHelper(pInstr, &src1Val, src1OriginalVal, pDstVal);
  8970. }
  8971. bailOutKind |= IR::BailOutOnOverflow;
  8972. newMin = INT32_MIN;
  8973. }
  8974. else
  8975. {
  8976. // See comment about ignoring overflow above
  8977. ignoredIntOverflow = true;
  8978. newMin = INT32_MIN;
  8979. newMax = INT32_MAX;
  8980. break;
  8981. }
  8982. }
  8983. } while(false);
  8984. if(!ignoredIntOverflow && instr->GetSrc1()->IsRegOpnd())
  8985. {
  8986. addSubConstantInfo.Set(instr->GetSrc1()->AsRegOpnd()->m_sym, src1Val, min == max, -1);
  8987. }
  8988. opcode = Js::OpCode::Sub_I4;
  8989. if (!this->IsLoopPrePass())
  8990. {
  8991. instr->SetSrc2(IR::IntConstOpnd::New(1, TyInt32, instr->m_func));
  8992. }
  8993. checkTypeSpecWorth = true;
  8994. break;
  8995. case Js::OpCode::BrFalse_A:
  8996. case Js::OpCode::BrTrue_A:
  8997. {
  8998. if(DoConstFold() && !IsLoopPrePass() && TryOptConstFoldBrFalse(instr, src1Val, min, max))
  8999. {
  9000. return true;
  9001. }
  9002. bool specialize = true;
  9003. if (!src1Val->GetValueInfo()->HasIntConstantValue() && instr->GetSrc1()->IsRegOpnd())
  9004. {
  9005. StackSym *sym = instr->GetSrc1()->AsRegOpnd()->m_sym;
  9006. if (this->IsInt32TypeSpecialized(sym, this->currentBlock) == false)
  9007. {
  9008. // Type specializing a BrTrue_A/BrFalse_A isn't worth it, unless the src
  9009. // is already type specialized
  9010. specialize = false;
  9011. }
  9012. }
  9013. if(instr->m_opcode == Js::OpCode::BrTrue_A)
  9014. {
  9015. UpdateIntBoundsForNotEqualBranch(src1Val, nullptr, 0);
  9016. opcode = Js::OpCode::BrTrue_I4;
  9017. }
  9018. else
  9019. {
  9020. UpdateIntBoundsForEqualBranch(src1Val, nullptr, 0);
  9021. opcode = Js::OpCode::BrFalse_I4;
  9022. }
  9023. if(!specialize)
  9024. {
  9025. return false;
  9026. }
  9027. newMin = 2; newMax = 1; // We'll assert if we make a range where min > max
  9028. break;
  9029. }
  9030. case Js::OpCode::MultiBr:
  9031. newMin = min;
  9032. newMax = max;
  9033. opcode = instr->m_opcode;
  9034. break;
  9035. case Js::OpCode::StElemI_A:
  9036. case Js::OpCode::StElemI_A_Strict:
  9037. case Js::OpCode::StElemC:
  9038. if(instr->GetDst()->AsIndirOpnd()->GetBaseOpnd()->GetValueType().IsLikelyAnyArrayWithNativeFloatValues())
  9039. {
  9040. src1Val = src1OriginalVal;
  9041. }
  9042. return TypeSpecializeStElem(pInstr, src1Val, pDstVal);
  9043. case Js::OpCode::NewScArray:
  9044. case Js::OpCode::NewScArrayWithMissingValues:
  9045. case Js::OpCode::InitFld:
  9046. case Js::OpCode::InitRootFld:
  9047. case Js::OpCode::StSlot:
  9048. case Js::OpCode::StSlotChkUndecl:
  9049. #if !FLOATVAR
  9050. case Js::OpCode::StSlotBoxTemp:
  9051. #endif
  9052. case Js::OpCode::StFld:
  9053. case Js::OpCode::StRootFld:
  9054. case Js::OpCode::StFldStrict:
  9055. case Js::OpCode::StRootFldStrict:
  9056. case Js::OpCode::ArgOut_A:
  9057. case Js::OpCode::ArgOut_A_Inline:
  9058. case Js::OpCode::ArgOut_A_FixupForStackArgs:
  9059. case Js::OpCode::ArgOut_A_Dynamic:
  9060. case Js::OpCode::ArgOut_A_FromStackArgs:
  9061. case Js::OpCode::ArgOut_A_SpreadArg:
  9062. // For this one we need to implement type specialization
  9063. //case Js::OpCode::ArgOut_A_InlineBuiltIn:
  9064. case Js::OpCode::Ret:
  9065. case Js::OpCode::LdElemUndef:
  9066. case Js::OpCode::LdElemUndefScoped:
  9067. return false;
  9068. default:
  9069. if (OpCodeAttr::IsInlineBuiltIn(instr->m_opcode))
  9070. {
  9071. newMin = min;
  9072. newMax = max;
  9073. opcode = instr->m_opcode;
  9074. break; // Note: we must keep checkTypeSpecWorth = false to make sure we never return false from this function.
  9075. }
  9076. return false;
  9077. }
  9078. // If this instruction is in a range of instructions where int overflow does not matter, we will still specialize it (won't
  9079. // leave it unspecialized based on heuristics), since it is most likely worth specializing, and the dst value needs to be
  9080. // guaranteed to be an int
  9081. if(checkTypeSpecWorth &&
  9082. !ignoredIntOverflow &&
  9083. !ignoredNegativeZero &&
  9084. instr->ShouldCheckForIntOverflow() &&
  9085. !IsWorthSpecializingToInt32(instr, src1Val))
  9086. {
  9087. // Even though type specialization is being skipped since it may not be worth it, the proper value should still be
  9088. // maintained so that the result may be type specialized later. An int value is not created for the dst in any of
  9089. // the following cases.
  9090. // - A bailout check is necessary to specialize this instruction. The bailout check is what guarantees the result to be
  9091. // an int, but since we're not going to specialize this instruction, there won't be a bailout check.
  9092. // - Aggressive int type specialization is disabled and we're in a loop prepass. We're conservative on dst values in
  9093. // that case, especially if the dst sym is live on the back-edge.
  9094. if(bailOutKind == IR::BailOutInvalid &&
  9095. instr->GetDst() &&
  9096. (DoAggressiveIntTypeSpec() || !this->IsLoopPrePass()))
  9097. {
  9098. *pDstVal = CreateDstUntransferredIntValue(newMin, newMax, instr, src1Val, nullptr);
  9099. }
  9100. if(instr->GetSrc2())
  9101. {
  9102. instr->FreeSrc2();
  9103. }
  9104. return false;
  9105. }
  9106. this->ignoredIntOverflowForCurrentInstr = ignoredIntOverflow;
  9107. this->ignoredNegativeZeroForCurrentInstr = ignoredNegativeZero;
  9108. {
  9109. // Try CSE again before modifying the IR, in case some attributes are required for successful CSE
  9110. Value *src1IndirIndexVal = nullptr;
  9111. Value *src2Val = nullptr;
  9112. if(CSEOptimize(currentBlock, &instr, &src1Val, &src2Val, &src1IndirIndexVal, true /* intMathExprOnly */))
  9113. {
  9114. *redoTypeSpecRef = true;
  9115. return false;
  9116. }
  9117. }
  9118. const Js::OpCode originalOpCode = instr->m_opcode;
  9119. if (!this->IsLoopPrePass())
  9120. {
  9121. // No re-write on prepass
  9122. instr->m_opcode = opcode;
  9123. }
  9124. Value *src1ValueToSpecialize = src1Val;
  9125. if(lossy)
  9126. {
  9127. // Lossy conversions to int32 must be done based on the original source values. For instance, if one of the values is a
  9128. // float constant with a value that fits in a uint32 but not an int32, and the instruction can ignore int overflow, the
  9129. // source value for the purposes of int specialization would have been changed to an int constant value by ignoring
  9130. // overflow. If we were to specialize the sym using the int constant value, it would be treated as a lossless
  9131. // conversion, but since there may be subsequent uses of the same float constant value that may not ignore overflow,
  9132. // this must be treated as a lossy conversion by specializing the sym using the original float constant value.
  9133. src1ValueToSpecialize = src1OriginalVal;
  9134. }
  9135. // Make sure the srcs are specialized
  9136. IR::Opnd *src1 = instr->GetSrc1();
  9137. this->ToInt32(instr, src1, this->currentBlock, src1ValueToSpecialize, nullptr, lossy);
  9138. if(bailOutKind != IR::BailOutInvalid && !this->IsLoopPrePass())
  9139. {
  9140. GenerateBailAtOperation(&instr, bailOutKind);
  9141. }
  9142. if (!skipDst)
  9143. {
  9144. IR::Opnd *dst = instr->GetDst();
  9145. if (dst)
  9146. {
  9147. AssertMsg(!(isTransfer && !this->IsLoopPrePass()) || min == newMin && max == newMax, "If this is just a copy, old/new min/max should be the same");
  9148. TypeSpecializeIntDst(
  9149. instr,
  9150. originalOpCode,
  9151. isTransfer ? src1Val : nullptr,
  9152. src1Val,
  9153. nullptr,
  9154. bailOutKind,
  9155. newMin,
  9156. newMax,
  9157. pDstVal,
  9158. addSubConstantInfo.HasInfo() ? &addSubConstantInfo : nullptr);
  9159. }
  9160. }
  9161. if(bailOutKind == IR::BailOutInvalid)
  9162. {
  9163. GOPT_TRACE(_u("Type specialized to INT\n"));
  9164. #if ENABLE_DEBUG_CONFIG_OPTIONS
  9165. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::AggressiveIntTypeSpecPhase))
  9166. {
  9167. Output::Print(_u("Type specialized to INT: "));
  9168. Output::Print(_u("%s \n"), Js::OpCodeUtil::GetOpCodeName(instr->m_opcode));
  9169. }
  9170. #endif
  9171. }
  9172. else
  9173. {
  9174. GOPT_TRACE(_u("Type specialized to INT with bailout on:\n"));
  9175. if(bailOutKind & IR::BailOutOnOverflow)
  9176. {
  9177. GOPT_TRACE(_u(" Overflow\n"));
  9178. #if ENABLE_DEBUG_CONFIG_OPTIONS
  9179. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::AggressiveIntTypeSpecPhase))
  9180. {
  9181. Output::Print(_u("Type specialized to INT with bailout (%S): "), "Overflow");
  9182. Output::Print(_u("%s \n"), Js::OpCodeUtil::GetOpCodeName(instr->m_opcode));
  9183. }
  9184. #endif
  9185. }
  9186. if(bailOutKind & IR::BailOutOnNegativeZero)
  9187. {
  9188. GOPT_TRACE(_u(" Zero\n"));
  9189. #if ENABLE_DEBUG_CONFIG_OPTIONS
  9190. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::AggressiveIntTypeSpecPhase))
  9191. {
  9192. Output::Print(_u("Type specialized to INT with bailout (%S): "), "Zero");
  9193. Output::Print(_u("%s \n"), Js::OpCodeUtil::GetOpCodeName(instr->m_opcode));
  9194. }
  9195. #endif
  9196. }
  9197. }
  9198. return true;
  9199. }
  9200. void
  9201. GlobOpt::TypeSpecializeIntDst(IR::Instr* instr, Js::OpCode originalOpCode, Value* valToTransfer, Value *const src1Value, Value *const src2Value, const IR::BailOutKind bailOutKind, int32 newMin, int32 newMax, Value** pDstVal, const AddSubConstantInfo *const addSubConstantInfo)
  9202. {
  9203. this->TypeSpecializeIntDst(instr, originalOpCode, valToTransfer, src1Value, src2Value, bailOutKind, ValueType::GetInt(IntConstantBounds(newMin, newMax).IsLikelyTaggable()), newMin, newMax, pDstVal, addSubConstantInfo);
  9204. }
  9205. void
  9206. GlobOpt::TypeSpecializeIntDst(IR::Instr* instr, Js::OpCode originalOpCode, Value* valToTransfer, Value *const src1Value, Value *const src2Value, const IR::BailOutKind bailOutKind, ValueType valueType, Value** pDstVal, const AddSubConstantInfo *const addSubConstantInfo)
  9207. {
  9208. this->TypeSpecializeIntDst(instr, originalOpCode, valToTransfer, src1Value, src2Value, bailOutKind, valueType, 0, 0, pDstVal, addSubConstantInfo);
  9209. }
  9210. void
  9211. GlobOpt::TypeSpecializeIntDst(IR::Instr* instr, Js::OpCode originalOpCode, Value* valToTransfer, Value *const src1Value, Value *const src2Value, const IR::BailOutKind bailOutKind, ValueType valueType, int32 newMin, int32 newMax, Value** pDstVal, const AddSubConstantInfo *const addSubConstantInfo)
  9212. {
  9213. Assert(valueType.IsInt() || (valueType.IsNumber() && valueType.IsLikelyInt() && newMin == 0 && newMax == 0));
  9214. Assert(!valToTransfer || valToTransfer == src1Value);
  9215. Assert(!addSubConstantInfo || addSubConstantInfo->HasInfo());
  9216. IR::Opnd *dst = instr->GetDst();
  9217. Assert(dst);
  9218. bool isValueInfoPrecise;
  9219. if(IsLoopPrePass())
  9220. {
  9221. valueType = GetPrepassValueTypeForDst(valueType, instr, src1Value, src2Value, &isValueInfoPrecise);
  9222. }
  9223. else
  9224. {
  9225. isValueInfoPrecise = true;
  9226. }
  9227. // If dst has a circular reference in a loop, it probably won't get specialized. Don't mark the dst as type-specialized on
  9228. // the pre-pass. With aggressive int spec though, it will take care of bailing out if necessary so there's no need to assume
  9229. // that the dst will be a var even if it's live on the back-edge. Also if the op always produces an int32, then there's no
  9230. // ambiguity in the dst's value type even in the prepass.
  9231. if (!DoAggressiveIntTypeSpec() && this->IsLoopPrePass() && !valueType.IsInt())
  9232. {
  9233. if (dst->IsRegOpnd())
  9234. {
  9235. this->ToVarRegOpnd(dst->AsRegOpnd(), this->currentBlock);
  9236. }
  9237. return;
  9238. }
  9239. const IntBounds *dstBounds = nullptr;
  9240. if(addSubConstantInfo && !addSubConstantInfo->SrcValueIsLikelyConstant() && DoTrackRelativeIntBounds())
  9241. {
  9242. Assert(!ignoredIntOverflowForCurrentInstr);
  9243. // Track bounds for add or sub with a constant. For instance, consider (b = a + 2). The value of 'b' should track that
  9244. // it is equal to (the value of 'a') + 2. Additionally, the value of 'b' should inherit the bounds of 'a', offset by
  9245. // the constant value.
  9246. if(!valueType.IsInt() || !isValueInfoPrecise)
  9247. {
  9248. newMin = INT32_MIN;
  9249. newMax = INT32_MAX;
  9250. }
  9251. dstBounds =
  9252. IntBounds::Add(
  9253. addSubConstantInfo->SrcValue(),
  9254. addSubConstantInfo->Offset(),
  9255. isValueInfoPrecise,
  9256. IntConstantBounds(newMin, newMax),
  9257. alloc);
  9258. }
  9259. // Src1's value could change later in the loop, so the value wouldn't be the same for each
  9260. // iteration. Since we don't iterate over loops "while (!changed)", go conservative on the
  9261. // pre-pass.
  9262. if (valToTransfer)
  9263. {
  9264. // If this is just a copy, no need for creating a new value.
  9265. Assert(!addSubConstantInfo);
  9266. *pDstVal = this->ValueNumberTransferDst(instr, valToTransfer);
  9267. this->InsertNewValue(*pDstVal, dst);
  9268. }
  9269. else if (valueType.IsInt() && isValueInfoPrecise)
  9270. {
  9271. bool wasNegativeZeroPreventedByBailout = false;
  9272. if(newMin <= 0 && newMax >= 0)
  9273. {
  9274. switch(originalOpCode)
  9275. {
  9276. case Js::OpCode::Add_A:
  9277. // -0 + -0 == -0
  9278. Assert(src1Value);
  9279. Assert(src2Value);
  9280. wasNegativeZeroPreventedByBailout =
  9281. src1Value->GetValueInfo()->WasNegativeZeroPreventedByBailout() &&
  9282. src2Value->GetValueInfo()->WasNegativeZeroPreventedByBailout();
  9283. break;
  9284. case Js::OpCode::Sub_A:
  9285. // -0 - 0 == -0
  9286. Assert(src1Value);
  9287. wasNegativeZeroPreventedByBailout = src1Value->GetValueInfo()->WasNegativeZeroPreventedByBailout();
  9288. break;
  9289. case Js::OpCode::Neg_A:
  9290. case Js::OpCode::Mul_A:
  9291. case Js::OpCode::Div_A:
  9292. case Js::OpCode::Rem_A:
  9293. wasNegativeZeroPreventedByBailout = !!(bailOutKind & IR::BailOutOnNegativeZero);
  9294. break;
  9295. }
  9296. }
  9297. *pDstVal =
  9298. dstBounds
  9299. ? NewIntBoundedValue(valueType, dstBounds, wasNegativeZeroPreventedByBailout, nullptr)
  9300. : NewIntRangeValue(newMin, newMax, wasNegativeZeroPreventedByBailout, nullptr);
  9301. }
  9302. else
  9303. {
  9304. *pDstVal = dstBounds ? NewIntBoundedValue(valueType, dstBounds, false, nullptr) : NewGenericValue(valueType);
  9305. }
  9306. if(addSubConstantInfo || updateInductionVariableValueNumber)
  9307. {
  9308. TrackIntSpecializedAddSubConstant(instr, addSubConstantInfo, *pDstVal, !!dstBounds);
  9309. }
  9310. SetValue(&blockData, *pDstVal, dst);
  9311. AssertMsg(dst->IsRegOpnd(), "What else?");
  9312. this->ToInt32Dst(instr, dst->AsRegOpnd(), this->currentBlock);
  9313. }
  9314. bool
  9315. GlobOpt::TypeSpecializeBinary(IR::Instr **pInstr, Value **pSrc1Val, Value **pSrc2Val, Value **pDstVal, Value *const src1OriginalVal, Value *const src2OriginalVal, bool *redoTypeSpecRef)
  9316. {
  9317. IR::Instr *&instr = *pInstr;
  9318. int32 min1 = INT32_MIN, max1 = INT32_MAX, min2 = INT32_MIN, max2 = INT32_MAX, newMin, newMax, tmp;
  9319. Js::OpCode opcode;
  9320. IR::Opnd *src1, *src2;
  9321. Value *&src1Val = *pSrc1Val;
  9322. Value *&src2Val = *pSrc2Val;
  9323. // We don't need to do typespec for asmjs
  9324. if (IsTypeSpecPhaseOff(this->func) || GetIsAsmJSFunc())
  9325. {
  9326. return false;
  9327. }
  9328. if (OpCodeAttr::IsInlineBuiltIn(instr->m_opcode))
  9329. {
  9330. this->TypeSpecializeInlineBuiltInBinary(pInstr, src1Val, src2Val, pDstVal, src1OriginalVal, src2OriginalVal);
  9331. return true;
  9332. }
  9333. if (src1Val)
  9334. {
  9335. src1Val->GetValueInfo()->GetIntValMinMax(&min1, &max1, this->DoAggressiveIntTypeSpec());
  9336. }
  9337. if (src2Val)
  9338. {
  9339. src2Val->GetValueInfo()->GetIntValMinMax(&min2, &max2, this->DoAggressiveIntTypeSpec());
  9340. }
  9341. // Type specialize binary operators to int32
  9342. bool src1Lossy = true;
  9343. bool src2Lossy = true;
  9344. IR::BailOutKind bailOutKind = IR::BailOutInvalid;
  9345. bool ignoredIntOverflow = this->ignoredIntOverflowForCurrentInstr;
  9346. bool ignoredNegativeZero = false;
  9347. bool skipSrc2 = false;
  9348. bool skipDst = false;
  9349. bool needsBoolConv = false;
  9350. AddSubConstantInfo addSubConstantInfo;
  9351. switch (instr->m_opcode)
  9352. {
  9353. case Js::OpCode::Or_A:
  9354. if (!DoLossyIntTypeSpec())
  9355. {
  9356. return false;
  9357. }
  9358. this->PropagateIntRangeBinary(instr, min1, max1, min2, max2, &newMin, &newMax);
  9359. opcode = Js::OpCode::Or_I4;
  9360. break;
  9361. case Js::OpCode::And_A:
  9362. if (!DoLossyIntTypeSpec())
  9363. {
  9364. return false;
  9365. }
  9366. this->PropagateIntRangeBinary(instr, min1, max1, min2, max2, &newMin, &newMax);
  9367. opcode = Js::OpCode::And_I4;
  9368. break;
  9369. case Js::OpCode::Xor_A:
  9370. if (!DoLossyIntTypeSpec())
  9371. {
  9372. return false;
  9373. }
  9374. this->PropagateIntRangeBinary(instr, min1, max1, min2, max2, &newMin, &newMax);
  9375. opcode = Js::OpCode::Xor_I4;
  9376. break;
  9377. case Js::OpCode::Shl_A:
  9378. if (!DoLossyIntTypeSpec())
  9379. {
  9380. return false;
  9381. }
  9382. this->PropagateIntRangeBinary(instr, min1, max1, min2, max2, &newMin, &newMax);
  9383. opcode = Js::OpCode::Shl_I4;
  9384. break;
  9385. case Js::OpCode::Shr_A:
  9386. if (!DoLossyIntTypeSpec())
  9387. {
  9388. return false;
  9389. }
  9390. this->PropagateIntRangeBinary(instr, min1, max1, min2, max2, &newMin, &newMax);
  9391. opcode = Js::OpCode::Shr_I4;
  9392. break;
  9393. case Js::OpCode::ShrU_A:
  9394. if (!DoLossyIntTypeSpec())
  9395. {
  9396. return false;
  9397. }
  9398. if (min1 < 0 && IntConstantBounds(min2, max2).And_0x1f().Contains(0))
  9399. {
  9400. // Src1 may be too large to represent as a signed int32, and src2 may be zero. Unless the resulting value is only
  9401. // used as a signed int32 (hence allowing us to ignore the result's sign), don't specialize the instruction.
  9402. if (!instr->ignoreIntOverflow)
  9403. return false;
  9404. ignoredIntOverflow = true;
  9405. }
  9406. this->PropagateIntRangeBinary(instr, min1, max1, min2, max2, &newMin, &newMax);
  9407. opcode = Js::OpCode::ShrU_I4;
  9408. break;
  9409. case Js::OpCode::BrUnLe_A:
  9410. // Folding the branch based on bounds will attempt a lossless int32 conversion of the sources if they are not definitely
  9411. // int already, so require that both sources are likely int for folding.
  9412. if (DoConstFold() &&
  9413. !IsLoopPrePass() &&
  9414. TryOptConstFoldBrUnsignedGreaterThan(instr, false, src1Val, min1, max1, src2Val, min2, max2))
  9415. {
  9416. return true;
  9417. }
  9418. if (min1 >= 0 && min2 >= 0)
  9419. {
  9420. // Only handle positive values since this is unsigned...
  9421. // Bounds are tracked only for likely int values. Only likely int values may have bounds that are not the defaults
  9422. // (INT32_MIN, INT32_MAX), so we're good.
  9423. Assert(src1Val);
  9424. Assert(src1Val->GetValueInfo()->IsLikelyInt());
  9425. Assert(src2Val);
  9426. Assert(src2Val->GetValueInfo()->IsLikelyInt());
  9427. UpdateIntBoundsForLessThanOrEqualBranch(src1Val, src2Val);
  9428. }
  9429. if (!DoLossyIntTypeSpec())
  9430. {
  9431. return false;
  9432. }
  9433. newMin = newMax = 0;
  9434. opcode = Js::OpCode::BrUnLe_I4;
  9435. break;
  9436. case Js::OpCode::BrUnLt_A:
  9437. // Folding the branch based on bounds will attempt a lossless int32 conversion of the sources if they are not definitely
  9438. // int already, so require that both sources are likely int for folding.
  9439. if (DoConstFold() &&
  9440. !IsLoopPrePass() &&
  9441. TryOptConstFoldBrUnsignedLessThan(instr, true, src1Val, min1, max1, src2Val, min2, max2))
  9442. {
  9443. return true;
  9444. }
  9445. if (min1 >= 0 && min2 >= 0)
  9446. {
  9447. // Only handle positive values since this is unsigned...
  9448. // Bounds are tracked only for likely int values. Only likely int values may have bounds that are not the defaults
  9449. // (INT32_MIN, INT32_MAX), so we're good.
  9450. Assert(src1Val);
  9451. Assert(src1Val->GetValueInfo()->IsLikelyInt());
  9452. Assert(src2Val);
  9453. Assert(src2Val->GetValueInfo()->IsLikelyInt());
  9454. UpdateIntBoundsForLessThanBranch(src1Val, src2Val);
  9455. }
  9456. if (!DoLossyIntTypeSpec())
  9457. {
  9458. return false;
  9459. }
  9460. newMin = newMax = 0;
  9461. opcode = Js::OpCode::BrUnLt_I4;
  9462. break;
  9463. case Js::OpCode::BrUnGe_A:
  9464. // Folding the branch based on bounds will attempt a lossless int32 conversion of the sources if they are not definitely
  9465. // int already, so require that both sources are likely int for folding.
  9466. if (DoConstFold() &&
  9467. !IsLoopPrePass() &&
  9468. TryOptConstFoldBrUnsignedLessThan(instr, false, src1Val, min1, max1, src2Val, min2, max2))
  9469. {
  9470. return true;
  9471. }
  9472. if (min1 >= 0 && min2 >= 0)
  9473. {
  9474. // Only handle positive values since this is unsigned...
  9475. // Bounds are tracked only for likely int values. Only likely int values may have bounds that are not the defaults
  9476. // (INT32_MIN, INT32_MAX), so we're good.
  9477. Assert(src1Val);
  9478. Assert(src1Val->GetValueInfo()->IsLikelyInt());
  9479. Assert(src2Val);
  9480. Assert(src2Val->GetValueInfo()->IsLikelyInt());
  9481. UpdateIntBoundsForGreaterThanOrEqualBranch(src1Val, src2Val);
  9482. }
  9483. if (!DoLossyIntTypeSpec())
  9484. {
  9485. return false;
  9486. }
  9487. newMin = newMax = 0;
  9488. opcode = Js::OpCode::BrUnGe_I4;
  9489. break;
  9490. case Js::OpCode::BrUnGt_A:
  9491. // Folding the branch based on bounds will attempt a lossless int32 conversion of the sources if they are not definitely
  9492. // int already, so require that both sources are likely int for folding.
  9493. if (DoConstFold() &&
  9494. !IsLoopPrePass() &&
  9495. TryOptConstFoldBrUnsignedGreaterThan(instr, true, src1Val, min1, max1, src2Val, min2, max2))
  9496. {
  9497. return true;
  9498. }
  9499. if (min1 >= 0 && min2 >= 0)
  9500. {
  9501. // Only handle positive values since this is unsigned...
  9502. // Bounds are tracked only for likely int values. Only likely int values may have bounds that are not the defaults
  9503. // (INT32_MIN, INT32_MAX), so we're good.
  9504. Assert(src1Val);
  9505. Assert(src1Val->GetValueInfo()->IsLikelyInt());
  9506. Assert(src2Val);
  9507. Assert(src2Val->GetValueInfo()->IsLikelyInt());
  9508. UpdateIntBoundsForGreaterThanBranch(src1Val, src2Val);
  9509. }
  9510. if (!DoLossyIntTypeSpec())
  9511. {
  9512. return false;
  9513. }
  9514. newMin = newMax = 0;
  9515. opcode = Js::OpCode::BrUnGt_I4;
  9516. break;
  9517. case Js::OpCode::CmUnLe_A:
  9518. if (!DoLossyIntTypeSpec())
  9519. {
  9520. return false;
  9521. }
  9522. newMin = 0;
  9523. newMax = 1;
  9524. opcode = Js::OpCode::CmUnLe_I4;
  9525. needsBoolConv = true;
  9526. break;
  9527. case Js::OpCode::CmUnLt_A:
  9528. if (!DoLossyIntTypeSpec())
  9529. {
  9530. return false;
  9531. }
  9532. newMin = 0;
  9533. newMax = 1;
  9534. opcode = Js::OpCode::CmUnLt_I4;
  9535. needsBoolConv = true;
  9536. break;
  9537. case Js::OpCode::CmUnGe_A:
  9538. if (!DoLossyIntTypeSpec())
  9539. {
  9540. return false;
  9541. }
  9542. newMin = 0;
  9543. newMax = 1;
  9544. opcode = Js::OpCode::CmUnGe_I4;
  9545. needsBoolConv = true;
  9546. break;
  9547. case Js::OpCode::CmUnGt_A:
  9548. if (!DoLossyIntTypeSpec())
  9549. {
  9550. return false;
  9551. }
  9552. newMin = 0;
  9553. newMax = 1;
  9554. opcode = Js::OpCode::CmUnGt_I4;
  9555. needsBoolConv = true;
  9556. break;
  9557. case Js::OpCode::Expo_A:
  9558. {
  9559. src1Val = src1OriginalVal;
  9560. src2Val = src2OriginalVal;
  9561. return this->TypeSpecializeFloatBinary(instr, src1Val, src2Val, pDstVal);
  9562. }
  9563. case Js::OpCode::Div_A:
  9564. {
  9565. ValueType specializedValueType = GetDivValueType(instr, src1Val, src2Val, true);
  9566. if (specializedValueType.IsFloat())
  9567. {
  9568. // Either result is float or 1/x or cst1/cst2 where cst1%cst2 != 0
  9569. // Note: We should really constant fold cst1%cst2...
  9570. src1Val = src1OriginalVal;
  9571. src2Val = src2OriginalVal;
  9572. return this->TypeSpecializeFloatBinary(instr, src1Val, src2Val, pDstVal);
  9573. }
  9574. #ifdef _M_ARM
  9575. if (!AutoSystemInfo::Data.ArmDivAvailable())
  9576. {
  9577. return false;
  9578. }
  9579. #endif
  9580. if (specializedValueType.IsInt())
  9581. {
  9582. if (max2 == 0x80000000 || (min2 == 0 && max2 == 00))
  9583. {
  9584. return false;
  9585. }
  9586. if (min1 == 0x80000000 && min2 <= -1 && max2 >= -1)
  9587. {
  9588. // Prevent integer overflow, as div by zero or MIN_INT / -1 will throw an exception
  9589. // Or we know we are dividing by zero (which is weird to have because the profile data
  9590. // say we got an int)
  9591. bailOutKind = IR::BailOutOnDivOfMinInt;
  9592. }
  9593. src1Lossy = false; // Detect -0 on the sources
  9594. src2Lossy = false;
  9595. opcode = Js::OpCode::Div_I4;
  9596. bailOutKind |= IR::BailOnDivResultNotInt;
  9597. if (max2 >= 0 && min2 <= 0)
  9598. {
  9599. // Need to check for divide by zero if the denominator range includes 0
  9600. bailOutKind |= IR::BailOutOnDivByZero;
  9601. }
  9602. if (max1 >= 0 && min1 <= 0)
  9603. {
  9604. // Numerator contains 0 so the result contains 0
  9605. newMin = 0;
  9606. newMax = 0;
  9607. if (min2 < 0)
  9608. {
  9609. // Denominator may be negative, so the result could be negative 0
  9610. if (instr->ShouldCheckForNegativeZero())
  9611. {
  9612. bailOutKind |= IR::BailOutOnNegativeZero;
  9613. }
  9614. else
  9615. {
  9616. ignoredNegativeZero = true;
  9617. }
  9618. }
  9619. }
  9620. else
  9621. {
  9622. // Initialize to invalid value, one of the condition below will update it correctly
  9623. newMin = INT_MAX;
  9624. newMax = INT_MIN;
  9625. }
  9626. // Deal with the positive and negative range separately for both the numerator and the denominator,
  9627. // and integrate to the overall min and max.
  9628. // If the result is positive (positive/positive or negative/negative):
  9629. // The min should be the smallest magnitude numerator (positive_Min1 | negative_Max1)
  9630. // divided by ---------------------------------------------------------------
  9631. // largest magnitude denominator (positive_Max2 | negative_Min2)
  9632. //
  9633. // The max should be the largest magnitude numerator (positive_Max1 | negative_Max1)
  9634. // divided by ---------------------------------------------------------------
  9635. // smallest magnitude denominator (positive_Min2 | negative_Max2)
  9636. // If the result is negative (positive/negative or positive/negative):
  9637. // The min should be the largest magnitude numerator (positive_Max1 | negative_Min1)
  9638. // divided by ---------------------------------------------------------------
  9639. // smallest magnitude denominator (negative_Max2 | positive_Min2)
  9640. //
  9641. // The max should be the smallest magnitude numerator (positive_Min1 | negative_Max1)
  9642. // divided by ---------------------------------------------------------------
  9643. // largest magnitude denominator (negative_Min2 | positive_Max2)
  9644. // Consider: The range can be slightly more precise if we take care of the rounding
  9645. if (max1 > 0)
  9646. {
  9647. // Take only the positive numerator range
  9648. int32 positive_Min1 = max(1, min1);
  9649. int32 positive_Max1 = max1;
  9650. if (max2 > 0)
  9651. {
  9652. // Take only the positive denominator range
  9653. int32 positive_Min2 = max(1, min2);
  9654. int32 positive_Max2 = max2;
  9655. // Positive / Positive
  9656. int32 quadrant1_Min = positive_Min1 <= positive_Max2? 1 : positive_Min1 / positive_Max2;
  9657. int32 quadrant1_Max = positive_Max1 <= positive_Min2? 1 : positive_Max1 / positive_Min2;
  9658. Assert(1 <= quadrant1_Min && quadrant1_Min <= quadrant1_Max);
  9659. // The result should positive
  9660. newMin = min(newMin, quadrant1_Min);
  9661. newMax = max(newMax, quadrant1_Max);
  9662. }
  9663. if (min2 < 0)
  9664. {
  9665. // Take only the negative denominator range
  9666. int32 negative_Min2 = min2;
  9667. int32 negative_Max2 = min(-1, max2);
  9668. // Positive / Negative
  9669. int32 quadrant2_Min = -positive_Max1 >= negative_Max2? -1 : positive_Max1 / negative_Max2;
  9670. int32 quadrant2_Max = -positive_Min1 >= negative_Min2? -1 : positive_Min1 / negative_Min2;
  9671. // The result should negative
  9672. Assert(quadrant2_Min <= quadrant2_Max && quadrant2_Max <= -1);
  9673. newMin = min(newMin, quadrant2_Min);
  9674. newMax = max(newMax, quadrant2_Max);
  9675. }
  9676. }
  9677. if (min1 < 0)
  9678. {
  9679. // Take only the native numerator range
  9680. int32 negative_Min1 = min1;
  9681. int32 negative_Max1 = min(-1, max1);
  9682. if (max2 > 0)
  9683. {
  9684. // Take only the positive denominator range
  9685. int32 positive_Min2 = max(1, min2);
  9686. int32 positive_Max2 = max2;
  9687. // Negative / Positive
  9688. int32 quadrant4_Min = negative_Min1 >= -positive_Min2? -1 : negative_Min1 / positive_Min2;
  9689. int32 quadrant4_Max = negative_Max1 >= -positive_Max2? -1 : negative_Max1 / positive_Max2;
  9690. // The result should negative
  9691. Assert(quadrant4_Min <= quadrant4_Max && quadrant4_Max <= -1);
  9692. newMin = min(newMin, quadrant4_Min);
  9693. newMax = max(newMax, quadrant4_Max);
  9694. }
  9695. if (min2 < 0)
  9696. {
  9697. // Take only the negative denominator range
  9698. int32 negative_Min2 = min2;
  9699. int32 negative_Max2 = min(-1, max2);
  9700. int32 quadrant3_Min;
  9701. int32 quadrant3_Max;
  9702. // Negative / Negative
  9703. if (negative_Max1 == 0x80000000 && negative_Min2 == -1)
  9704. {
  9705. quadrant3_Min = negative_Max1 >= negative_Min2? 1 : (negative_Max1+1) / negative_Min2;
  9706. }
  9707. else
  9708. {
  9709. quadrant3_Min = negative_Max1 >= negative_Min2? 1 : negative_Max1 / negative_Min2;
  9710. }
  9711. if (negative_Min1 == 0x80000000 && negative_Max2 == -1)
  9712. {
  9713. quadrant3_Max = negative_Min1 >= negative_Max2? 1 : (negative_Min1+1) / negative_Max2;
  9714. }
  9715. else
  9716. {
  9717. quadrant3_Max = negative_Min1 >= negative_Max2? 1 : negative_Min1 / negative_Max2;
  9718. }
  9719. // The result should positive
  9720. Assert(1 <= quadrant3_Min && quadrant3_Min <= quadrant3_Max);
  9721. newMin = min(newMin, quadrant3_Min);
  9722. newMax = max(newMax, quadrant3_Max);
  9723. }
  9724. }
  9725. Assert(newMin <= newMax);
  9726. // Continue to int type spec
  9727. break;
  9728. }
  9729. }
  9730. // fall-through
  9731. default:
  9732. {
  9733. const bool involesLargeInt32 =
  9734. src1Val && src1Val->GetValueInfo()->IsLikelyUntaggedInt() ||
  9735. src2Val && src2Val->GetValueInfo()->IsLikelyUntaggedInt();
  9736. const auto trySpecializeToFloat =
  9737. [&](const bool mayOverflow) -> bool
  9738. {
  9739. // It has been determined that this instruction cannot be int-specialized. Need to determine whether to attempt
  9740. // to float-specialize the instruction, or leave it unspecialized.
  9741. if(involesLargeInt32
  9742. #if INT32VAR
  9743. && mayOverflow
  9744. #endif
  9745. || (instr->m_opcode == Js::OpCode::Mul_A && !this->DoAggressiveMulIntTypeSpec())
  9746. )
  9747. {
  9748. // An input range is completely outside the range of an int31 and the operation is likely to overflow.
  9749. // Additionally, on 32-bit platforms, the value is untaggable and will be a JavascriptNumber, which is
  9750. // significantly slower to use in an unspecialized operation compared to a tagged int. So, try to
  9751. // float-specialize the instruction.
  9752. src1Val = src1OriginalVal;
  9753. src2Val = src2OriginalVal;
  9754. return TypeSpecializeFloatBinary(instr, src1Val, src2Val, pDstVal);
  9755. }
  9756. return false;
  9757. };
  9758. if (instr->m_opcode != Js::OpCode::ArgOut_A_InlineBuiltIn)
  9759. {
  9760. if ((src1Val && src1Val->GetValueInfo()->IsLikelyFloat()) || (src2Val && src2Val->GetValueInfo()->IsLikelyFloat()))
  9761. {
  9762. // Try to type specialize to float
  9763. src1Val = src1OriginalVal;
  9764. src2Val = src2OriginalVal;
  9765. return this->TypeSpecializeFloatBinary(instr, src1Val, src2Val, pDstVal);
  9766. }
  9767. if (src1Val == nullptr ||
  9768. src2Val == nullptr ||
  9769. !src1Val->GetValueInfo()->IsLikelyInt() ||
  9770. !src2Val->GetValueInfo()->IsLikelyInt() ||
  9771. (
  9772. !DoAggressiveIntTypeSpec() &&
  9773. (
  9774. !(src1Val->GetValueInfo()->IsInt() || IsSwitchInt32TypeSpecialized(instr, currentBlock)) ||
  9775. !src2Val->GetValueInfo()->IsInt()
  9776. )
  9777. ) ||
  9778. instr->GetSrc1()->IsRegOpnd() && instr->GetSrc1()->AsRegOpnd()->m_sym->m_isNotInt ||
  9779. instr->GetSrc2()->IsRegOpnd() && instr->GetSrc2()->AsRegOpnd()->m_sym->m_isNotInt)
  9780. {
  9781. return trySpecializeToFloat(true);
  9782. }
  9783. }
  9784. // Try to type specialize to int32
  9785. // If one of the values is a float constant with a value that fits in a uint32 but not an int32,
  9786. // and the instruction can ignore int overflow, the source value for the purposes of int specialization
  9787. // would have been changed to an int constant value by ignoring overflow. But, the conversion is still lossy.
  9788. if (!(src1OriginalVal && src1OriginalVal->GetValueInfo()->IsFloatConstant() && src1Val && src1Val->GetValueInfo()->HasIntConstantValue()))
  9789. {
  9790. src1Lossy = false;
  9791. }
  9792. if (!(src2OriginalVal && src2OriginalVal->GetValueInfo()->IsFloatConstant() && src2Val && src2Val->GetValueInfo()->HasIntConstantValue()))
  9793. {
  9794. src2Lossy = false;
  9795. }
  9796. switch(instr->m_opcode)
  9797. {
  9798. case Js::OpCode::ArgOut_A_InlineBuiltIn:
  9799. // If the src is already type-specialized, if we don't type-specialize ArgOut_A_InlineBuiltIn instr, we'll get additional ToVar.
  9800. // So, to avoid that, type-specialize the ArgOut_A_InlineBuiltIn instr.
  9801. // Else we don't need to type-specialize the instr, we are fine with src being Var.
  9802. if (instr->GetSrc1()->IsRegOpnd())
  9803. {
  9804. StackSym *sym = instr->GetSrc1()->AsRegOpnd()->m_sym;
  9805. if (this->IsInt32TypeSpecialized(sym, this->currentBlock))
  9806. {
  9807. opcode = instr->m_opcode;
  9808. skipDst = true; // We should keep dst as is, otherwise the link opnd for next ArgOut/InlineBuiltInStart would be broken.
  9809. skipSrc2 = true; // src2 is linkOpnd. We don't need to type-specialize it.
  9810. newMin = min1; newMax = max1; // Values don't matter, these are unused.
  9811. goto LOutsideSwitch; // Continue to int-type-specialize.
  9812. }
  9813. else if (this->IsFloat64TypeSpecialized(sym, this->currentBlock))
  9814. {
  9815. src1Val = src1OriginalVal;
  9816. src2Val = src2OriginalVal;
  9817. return this->TypeSpecializeFloatBinary(instr, src1Val, src2Val, pDstVal);
  9818. }
  9819. else if (this->IsSimd128F4TypeSpecialized(sym, this->currentBlock))
  9820. {
  9821. // SIMD_JS
  9822. // We should be already using the SIMD type-spec sym. See TypeSpecializeSimd128.
  9823. Assert(IRType_IsSimd128(instr->GetSrc1()->GetType()));
  9824. }
  9825. }
  9826. return false;
  9827. case Js::OpCode::Add_A:
  9828. do // while(false)
  9829. {
  9830. const auto CannotOverflowBasedOnRelativeBounds = [&](int32 *const constantValueRef)
  9831. {
  9832. Assert(constantValueRef);
  9833. if(min2 == max2 &&
  9834. src1Val->GetValueInfo()->IsIntBounded() &&
  9835. src1Val->GetValueInfo()->AsIntBounded()->Bounds()->AddCannotOverflowBasedOnRelativeBounds(min2))
  9836. {
  9837. *constantValueRef = min2;
  9838. return true;
  9839. }
  9840. else if(
  9841. min1 == max1 &&
  9842. src2Val->GetValueInfo()->IsIntBounded() &&
  9843. src2Val->GetValueInfo()->AsIntBounded()->Bounds()->AddCannotOverflowBasedOnRelativeBounds(min1))
  9844. {
  9845. *constantValueRef = min1;
  9846. return true;
  9847. }
  9848. return false;
  9849. };
  9850. if (Int32Math::Add(min1, min2, &newMin))
  9851. {
  9852. int32 constantSrcValue;
  9853. if(CannotOverflowBasedOnRelativeBounds(&constantSrcValue))
  9854. {
  9855. newMin = constantSrcValue >= 0 ? INT32_MAX : INT32_MIN;
  9856. }
  9857. else if(instr->ShouldCheckForIntOverflow())
  9858. {
  9859. if(involesLargeInt32 || !DoAggressiveIntTypeSpec())
  9860. {
  9861. // May overflow
  9862. return trySpecializeToFloat(true);
  9863. }
  9864. bailOutKind |= IR::BailOutOnOverflow;
  9865. newMin = min1 < 0 ? INT32_MIN : INT32_MAX;
  9866. }
  9867. else
  9868. {
  9869. // When ignoring overflow, the range needs to account for overflow. For any Add or Sub, since
  9870. // overflow causes the value to wrap around, and we don't have a way to specify a lower and upper
  9871. // range of ints, we use the full range of int32s.
  9872. ignoredIntOverflow = true;
  9873. newMin = INT32_MIN;
  9874. newMax = INT32_MAX;
  9875. break;
  9876. }
  9877. }
  9878. if (Int32Math::Add(max1, max2, &newMax))
  9879. {
  9880. int32 constantSrcValue;
  9881. if(CannotOverflowBasedOnRelativeBounds(&constantSrcValue))
  9882. {
  9883. newMax = constantSrcValue >= 0 ? INT32_MAX : INT32_MIN;
  9884. }
  9885. else if(instr->ShouldCheckForIntOverflow())
  9886. {
  9887. if(involesLargeInt32 || !DoAggressiveIntTypeSpec())
  9888. {
  9889. // May overflow
  9890. return trySpecializeToFloat(true);
  9891. }
  9892. bailOutKind |= IR::BailOutOnOverflow;
  9893. newMax = max1 < 0 ? INT32_MIN : INT32_MAX;
  9894. }
  9895. else
  9896. {
  9897. // See comment about ignoring overflow above
  9898. ignoredIntOverflow = true;
  9899. newMin = INT32_MIN;
  9900. newMax = INT32_MAX;
  9901. break;
  9902. }
  9903. }
  9904. if(bailOutKind & IR::BailOutOnOverflow)
  9905. {
  9906. Assert(bailOutKind == IR::BailOutOnOverflow);
  9907. Assert(instr->ShouldCheckForIntOverflow());
  9908. int32 temp;
  9909. if(Int32Math::Add(
  9910. Int32Math::NearestInRangeTo(0, min1, max1),
  9911. Int32Math::NearestInRangeTo(0, min2, max2),
  9912. &temp))
  9913. {
  9914. // Always overflows
  9915. return trySpecializeToFloat(true);
  9916. }
  9917. }
  9918. } while(false);
  9919. if (!this->IsLoopPrePass() && newMin == newMax && bailOutKind == IR::BailOutInvalid)
  9920. {
  9921. // Take care of Add with zero here, since we know we're dealing with 2 numbers.
  9922. this->CaptureByteCodeSymUses(instr);
  9923. IR::Opnd *src;
  9924. bool isAddZero = true;
  9925. int32 intConstantValue;
  9926. if (src1Val->GetValueInfo()->TryGetIntConstantValue(&intConstantValue) && intConstantValue == 0)
  9927. {
  9928. src = instr->UnlinkSrc2();
  9929. instr->FreeSrc1();
  9930. }
  9931. else if (src2Val->GetValueInfo()->TryGetIntConstantValue(&intConstantValue) && intConstantValue == 0)
  9932. {
  9933. src = instr->UnlinkSrc1();
  9934. instr->FreeSrc2();
  9935. }
  9936. else
  9937. {
  9938. // This should have been handled by const folding, unless:
  9939. // - A source's value was substituted with a different value here, which is after const folding happened
  9940. // - A value is not definitely int, but once converted to definite int, it would be zero due to a
  9941. // condition in the source code such as if(a === 0). Ideally, we would specialize the sources and
  9942. // remove the add, but doesn't seem too important for now.
  9943. Assert(
  9944. !DoConstFold() ||
  9945. src1Val != src1OriginalVal ||
  9946. src2Val != src2OriginalVal ||
  9947. !src1Val->GetValueInfo()->IsInt() ||
  9948. !src2Val->GetValueInfo()->IsInt());
  9949. isAddZero = false;
  9950. src = nullptr;
  9951. }
  9952. if (isAddZero)
  9953. {
  9954. IR::Instr *newInstr = IR::Instr::New(Js::OpCode::Ld_A, instr->UnlinkDst(), src, instr->m_func);
  9955. newInstr->SetByteCodeOffset(instr);
  9956. instr->m_opcode = Js::OpCode::Nop;
  9957. this->currentBlock->InsertInstrAfter(newInstr, instr);
  9958. return true;
  9959. }
  9960. }
  9961. if(!ignoredIntOverflow)
  9962. {
  9963. if(min2 == max2 &&
  9964. (!IsLoopPrePass() || IsPrepassSrcValueInfoPrecise(instr->GetSrc2(), src2Val)) &&
  9965. instr->GetSrc1()->IsRegOpnd())
  9966. {
  9967. addSubConstantInfo.Set(instr->GetSrc1()->AsRegOpnd()->m_sym, src1Val, min1 == max1, min2);
  9968. }
  9969. else if(
  9970. min1 == max1 &&
  9971. (!IsLoopPrePass() || IsPrepassSrcValueInfoPrecise(instr->GetSrc1(), src1Val)) &&
  9972. instr->GetSrc2()->IsRegOpnd())
  9973. {
  9974. addSubConstantInfo.Set(instr->GetSrc2()->AsRegOpnd()->m_sym, src2Val, min2 == max2, min1);
  9975. }
  9976. }
  9977. opcode = Js::OpCode::Add_I4;
  9978. break;
  9979. case Js::OpCode::Sub_A:
  9980. do // while(false)
  9981. {
  9982. const auto CannotOverflowBasedOnRelativeBounds = [&]()
  9983. {
  9984. return
  9985. min2 == max2 &&
  9986. src1Val->GetValueInfo()->IsIntBounded() &&
  9987. src1Val->GetValueInfo()->AsIntBounded()->Bounds()->SubCannotOverflowBasedOnRelativeBounds(min2);
  9988. };
  9989. if (Int32Math::Sub(min1, max2, &newMin))
  9990. {
  9991. if(CannotOverflowBasedOnRelativeBounds())
  9992. {
  9993. Assert(min2 == max2);
  9994. newMin = min2 >= 0 ? INT32_MIN : INT32_MAX;
  9995. }
  9996. else if(instr->ShouldCheckForIntOverflow())
  9997. {
  9998. if(involesLargeInt32 || !DoAggressiveIntTypeSpec())
  9999. {
  10000. // May overflow
  10001. return trySpecializeToFloat(true);
  10002. }
  10003. bailOutKind |= IR::BailOutOnOverflow;
  10004. newMin = min1 < 0 ? INT32_MIN : INT32_MAX;
  10005. }
  10006. else
  10007. {
  10008. // When ignoring overflow, the range needs to account for overflow. For any Add or Sub, since overflow
  10009. // causes the value to wrap around, and we don't have a way to specify a lower and upper range of ints,
  10010. // we use the full range of int32s.
  10011. ignoredIntOverflow = true;
  10012. newMin = INT32_MIN;
  10013. newMax = INT32_MAX;
  10014. break;
  10015. }
  10016. }
  10017. if (Int32Math::Sub(max1, min2, &newMax))
  10018. {
  10019. if(CannotOverflowBasedOnRelativeBounds())
  10020. {
  10021. Assert(min2 == max2);
  10022. newMax = min2 >= 0 ? INT32_MIN: INT32_MAX;
  10023. }
  10024. else if(instr->ShouldCheckForIntOverflow())
  10025. {
  10026. if(involesLargeInt32 || !DoAggressiveIntTypeSpec())
  10027. {
  10028. // May overflow
  10029. return trySpecializeToFloat(true);
  10030. }
  10031. bailOutKind |= IR::BailOutOnOverflow;
  10032. newMax = max1 < 0 ? INT32_MIN : INT32_MAX;
  10033. }
  10034. else
  10035. {
  10036. // See comment about ignoring overflow above
  10037. ignoredIntOverflow = true;
  10038. newMin = INT32_MIN;
  10039. newMax = INT32_MAX;
  10040. break;
  10041. }
  10042. }
  10043. if(bailOutKind & IR::BailOutOnOverflow)
  10044. {
  10045. Assert(bailOutKind == IR::BailOutOnOverflow);
  10046. Assert(instr->ShouldCheckForIntOverflow());
  10047. int32 temp;
  10048. if(Int32Math::Sub(
  10049. Int32Math::NearestInRangeTo(-1, min1, max1),
  10050. Int32Math::NearestInRangeTo(0, min2, max2),
  10051. &temp))
  10052. {
  10053. // Always overflows
  10054. return trySpecializeToFloat(true);
  10055. }
  10056. }
  10057. } while(false);
  10058. if(!ignoredIntOverflow &&
  10059. min2 == max2 &&
  10060. min2 != INT32_MIN &&
  10061. (!IsLoopPrePass() || IsPrepassSrcValueInfoPrecise(instr->GetSrc2(), src2Val)) &&
  10062. instr->GetSrc1()->IsRegOpnd())
  10063. {
  10064. addSubConstantInfo.Set(instr->GetSrc1()->AsRegOpnd()->m_sym, src1Val, min1 == max1, -min2);
  10065. }
  10066. opcode = Js::OpCode::Sub_I4;
  10067. break;
  10068. case Js::OpCode::Mul_A:
  10069. {
  10070. if (Int32Math::Mul(min1, min2, &newMin))
  10071. {
  10072. if (involesLargeInt32 || !DoAggressiveMulIntTypeSpec() || !DoAggressiveIntTypeSpec())
  10073. {
  10074. // May overflow
  10075. return trySpecializeToFloat(true);
  10076. }
  10077. bailOutKind |= IR::BailOutOnMulOverflow;
  10078. newMin = (min1 < 0) ^ (min2 < 0) ? INT32_MIN : INT32_MAX;
  10079. }
  10080. newMax = newMin;
  10081. if (Int32Math::Mul(max1, max2, &tmp))
  10082. {
  10083. if (involesLargeInt32 || !DoAggressiveMulIntTypeSpec() || !DoAggressiveIntTypeSpec())
  10084. {
  10085. // May overflow
  10086. return trySpecializeToFloat(true);
  10087. }
  10088. bailOutKind |= IR::BailOutOnMulOverflow;
  10089. tmp = (max1 < 0) ^ (max2 < 0) ? INT32_MIN : INT32_MAX;
  10090. }
  10091. newMin = min(newMin, tmp);
  10092. newMax = max(newMax, tmp);
  10093. if (Int32Math::Mul(min1, max2, &tmp))
  10094. {
  10095. if (involesLargeInt32 || !DoAggressiveMulIntTypeSpec() || !DoAggressiveIntTypeSpec())
  10096. {
  10097. // May overflow
  10098. return trySpecializeToFloat(true);
  10099. }
  10100. bailOutKind |= IR::BailOutOnMulOverflow;
  10101. tmp = (min1 < 0) ^ (max2 < 0) ? INT32_MIN : INT32_MAX;
  10102. }
  10103. newMin = min(newMin, tmp);
  10104. newMax = max(newMax, tmp);
  10105. if (Int32Math::Mul(max1, min2, &tmp))
  10106. {
  10107. if (involesLargeInt32 || !DoAggressiveMulIntTypeSpec() || !DoAggressiveIntTypeSpec())
  10108. {
  10109. // May overflow
  10110. return trySpecializeToFloat(true);
  10111. }
  10112. bailOutKind |= IR::BailOutOnMulOverflow;
  10113. tmp = (max1 < 0) ^ (min2 < 0) ? INT32_MIN : INT32_MAX;
  10114. }
  10115. newMin = min(newMin, tmp);
  10116. newMax = max(newMax, tmp);
  10117. if (bailOutKind & IR::BailOutOnMulOverflow)
  10118. {
  10119. // CSE only if two MULs have the same overflow check behavior.
  10120. // Currently this is set to be ignore int32 overflow, but not 53-bit, or int32 overflow matters.
  10121. if (!instr->ShouldCheckFor32BitOverflow() && instr->ShouldCheckForNon32BitOverflow())
  10122. {
  10123. // If we allow int to overflow then there can be anything in the resulting int
  10124. newMin = IntConstMin;
  10125. newMax = IntConstMax;
  10126. ignoredIntOverflow = true;
  10127. }
  10128. int32 temp, overflowValue;
  10129. if (Int32Math::Mul(
  10130. Int32Math::NearestInRangeTo(0, min1, max1),
  10131. Int32Math::NearestInRangeTo(0, min2, max2),
  10132. &temp,
  10133. &overflowValue))
  10134. {
  10135. Assert(instr->ignoreOverflowBitCount >= 32);
  10136. int overflowMatters = 64 - instr->ignoreOverflowBitCount;
  10137. if (!ignoredIntOverflow ||
  10138. // Use shift to check high bits in case its negative
  10139. ((overflowValue << overflowMatters) >> overflowMatters) != overflowValue
  10140. )
  10141. {
  10142. // Always overflows
  10143. return trySpecializeToFloat(true);
  10144. }
  10145. }
  10146. }
  10147. if (newMin <= 0 && newMax >= 0 && // New range crosses zero
  10148. (min1 < 0 || min2 < 0) && // An operand's range contains a negative integer
  10149. !(min1 > 0 || min2 > 0) && // Neither operand's range contains only positive integers
  10150. !instr->GetSrc1()->IsEqual(instr->GetSrc2())) // The operands don't have the same value
  10151. {
  10152. if (instr->ShouldCheckForNegativeZero())
  10153. {
  10154. // -0 matters since the sym is not a local, or is used in a way in which -0 would differ from +0
  10155. if (!DoAggressiveIntTypeSpec())
  10156. {
  10157. // May result in -0
  10158. return trySpecializeToFloat(false);
  10159. }
  10160. if ((min1 == 0 && max1 == 0 || min2 == 0 && max2 == 0) && (max1 < 0 || max2 < 0))
  10161. {
  10162. // Always results in -0
  10163. return trySpecializeToFloat(false);
  10164. }
  10165. bailOutKind |= IR::BailOutOnNegativeZero;
  10166. }
  10167. else
  10168. {
  10169. ignoredNegativeZero = true;
  10170. }
  10171. }
  10172. opcode = Js::OpCode::Mul_I4;
  10173. break;
  10174. }
  10175. case Js::OpCode::Rem_A:
  10176. {
  10177. src2 = instr->GetSrc2();
  10178. if (!this->IsLoopPrePass() && min2 == max2 && min1 >= 0)
  10179. {
  10180. int32 value = min2;
  10181. if (value == (1 << Math::Log2(value)) && src2->IsAddrOpnd())
  10182. {
  10183. Assert(src2->AsAddrOpnd()->IsVar());
  10184. instr->m_opcode = Js::OpCode::And_A;
  10185. src2->AsAddrOpnd()->SetAddress(Js::TaggedInt::ToVarUnchecked(value - 1),
  10186. IR::AddrOpndKindConstantVar);
  10187. *pSrc2Val = GetIntConstantValue(value - 1, instr);
  10188. src2Val = *pSrc2Val;
  10189. return this->TypeSpecializeBinary(&instr, pSrc1Val, pSrc2Val, pDstVal, src1OriginalVal, src2Val, redoTypeSpecRef);
  10190. }
  10191. }
  10192. #ifdef _M_ARM
  10193. if (!AutoSystemInfo::Data.ArmDivAvailable())
  10194. {
  10195. return false;
  10196. }
  10197. #endif
  10198. if (min1 < 0)
  10199. {
  10200. // The most negative it can be is min1, unless limited by min2/max2
  10201. int32 negMaxAbs2;
  10202. if (min2 == INT32_MIN)
  10203. {
  10204. negMaxAbs2 = INT32_MIN;
  10205. }
  10206. else
  10207. {
  10208. negMaxAbs2 = -max(abs(min2), abs(max2)) + 1;
  10209. }
  10210. newMin = max(min1, negMaxAbs2);
  10211. }
  10212. else
  10213. {
  10214. newMin = 0;
  10215. }
  10216. bool isModByPowerOf2 = (instr->IsProfiledInstr() && instr->m_func->HasProfileInfo() &&
  10217. instr->m_func->GetProfileInfo()->IsModulusOpByPowerOf2(instr->m_func->GetJnFunction(), static_cast<Js::ProfileId>(instr->AsProfiledInstr()->u.profileId)));
  10218. if(isModByPowerOf2)
  10219. {
  10220. Assert(bailOutKind == IR::BailOutInvalid);
  10221. bailOutKind = IR::BailOnModByPowerOf2;
  10222. newMin = 0;
  10223. }
  10224. else
  10225. {
  10226. if (min2 <= 0 && max2 >= 0)
  10227. {
  10228. // Consider: We could handle the zero case with a check and bailout...
  10229. return false;
  10230. }
  10231. if (min1 == 0x80000000 && (min2 <= -1 && max2 >= -1))
  10232. {
  10233. // Prevent integer overflow, as div by zero or MIN_INT / -1 will throw an exception
  10234. return false;
  10235. }
  10236. if (min1 < 0)
  10237. {
  10238. if(instr->ShouldCheckForNegativeZero())
  10239. {
  10240. if (!DoAggressiveIntTypeSpec())
  10241. {
  10242. return false;
  10243. }
  10244. bailOutKind |= IR::BailOutOnNegativeZero;
  10245. }
  10246. else
  10247. {
  10248. ignoredNegativeZero = true;
  10249. }
  10250. }
  10251. }
  10252. {
  10253. int32 absMax2;
  10254. if (min2 == INT32_MIN)
  10255. {
  10256. // abs(INT32_MIN) == INT32_MAX because of overflow
  10257. absMax2 = INT32_MAX;
  10258. }
  10259. else
  10260. {
  10261. absMax2 = max(abs(min2), abs(max2)) - 1;
  10262. }
  10263. newMax = min(absMax2, max(max1, 0));
  10264. newMax = max(newMin, newMax);
  10265. }
  10266. opcode = Js::OpCode::Rem_I4;
  10267. break;
  10268. }
  10269. case Js::OpCode::CmEq_A:
  10270. case Js::OpCode::CmSrEq_A:
  10271. if (!IsWorthSpecializingToInt32Branch(instr, src1Val, src2Val))
  10272. {
  10273. return false;
  10274. }
  10275. newMin = 0;
  10276. newMax = 1;
  10277. opcode = Js::OpCode::CmEq_I4;
  10278. needsBoolConv = true;
  10279. break;
  10280. case Js::OpCode::CmNeq_A:
  10281. case Js::OpCode::CmSrNeq_A:
  10282. if (!IsWorthSpecializingToInt32Branch(instr, src1Val, src2Val))
  10283. {
  10284. return false;
  10285. }
  10286. newMin = 0;
  10287. newMax = 1;
  10288. opcode = Js::OpCode::CmNeq_I4;
  10289. needsBoolConv = true;
  10290. break;
  10291. case Js::OpCode::CmLe_A:
  10292. if (!IsWorthSpecializingToInt32Branch(instr, src1Val, src2Val))
  10293. {
  10294. return false;
  10295. }
  10296. newMin = 0;
  10297. newMax = 1;
  10298. opcode = Js::OpCode::CmLe_I4;
  10299. needsBoolConv = true;
  10300. break;
  10301. case Js::OpCode::CmLt_A:
  10302. if (!IsWorthSpecializingToInt32Branch(instr, src1Val, src2Val))
  10303. {
  10304. return false;
  10305. }
  10306. newMin = 0;
  10307. newMax = 1;
  10308. opcode = Js::OpCode::CmLt_I4;
  10309. needsBoolConv = true;
  10310. break;
  10311. case Js::OpCode::CmGe_A:
  10312. if (!IsWorthSpecializingToInt32Branch(instr, src1Val, src2Val))
  10313. {
  10314. return false;
  10315. }
  10316. newMin = 0;
  10317. newMax = 1;
  10318. opcode = Js::OpCode::CmGe_I4;
  10319. needsBoolConv = true;
  10320. break;
  10321. case Js::OpCode::CmGt_A:
  10322. if (!IsWorthSpecializingToInt32Branch(instr, src1Val, src2Val))
  10323. {
  10324. return false;
  10325. }
  10326. newMin = 0;
  10327. newMax = 1;
  10328. opcode = Js::OpCode::CmGt_I4;
  10329. needsBoolConv = true;
  10330. break;
  10331. case Js::OpCode::BrSrEq_A:
  10332. case Js::OpCode::BrEq_A:
  10333. case Js::OpCode::BrNotNeq_A:
  10334. case Js::OpCode::BrSrNotNeq_A:
  10335. {
  10336. if(DoConstFold() &&
  10337. !IsLoopPrePass() &&
  10338. TryOptConstFoldBrEqual(instr, true, src1Val, min1, max1, src2Val, min2, max2))
  10339. {
  10340. return true;
  10341. }
  10342. const bool specialize = IsWorthSpecializingToInt32Branch(instr, src1Val, src2Val);
  10343. UpdateIntBoundsForEqualBranch(src1Val, src2Val);
  10344. if(!specialize)
  10345. {
  10346. return false;
  10347. }
  10348. opcode = Js::OpCode::BrEq_I4;
  10349. // We'll get a warning if we don't assign a value to these...
  10350. // We'll assert if we use them and make a range where min > max
  10351. newMin = 2; newMax = 1;
  10352. break;
  10353. }
  10354. case Js::OpCode::BrSrNeq_A:
  10355. case Js::OpCode::BrNeq_A:
  10356. case Js::OpCode::BrSrNotEq_A:
  10357. case Js::OpCode::BrNotEq_A:
  10358. {
  10359. if(DoConstFold() &&
  10360. !IsLoopPrePass() &&
  10361. TryOptConstFoldBrEqual(instr, false, src1Val, min1, max1, src2Val, min2, max2))
  10362. {
  10363. return true;
  10364. }
  10365. const bool specialize = IsWorthSpecializingToInt32Branch(instr, src1Val, src2Val);
  10366. UpdateIntBoundsForNotEqualBranch(src1Val, src2Val);
  10367. if(!specialize)
  10368. {
  10369. return false;
  10370. }
  10371. opcode = Js::OpCode::BrNeq_I4;
  10372. // We'll get a warning if we don't assign a value to these...
  10373. // We'll assert if we use them and make a range where min > max
  10374. newMin = 2; newMax = 1;
  10375. break;
  10376. }
  10377. case Js::OpCode::BrGt_A:
  10378. case Js::OpCode::BrNotLe_A:
  10379. {
  10380. if(DoConstFold() &&
  10381. !IsLoopPrePass() &&
  10382. TryOptConstFoldBrGreaterThan(instr, true, src1Val, min1, max1, src2Val, min2, max2))
  10383. {
  10384. return true;
  10385. }
  10386. const bool specialize = IsWorthSpecializingToInt32Branch(instr, src1Val, src2Val);
  10387. UpdateIntBoundsForGreaterThanBranch(src1Val, src2Val);
  10388. if(!specialize)
  10389. {
  10390. return false;
  10391. }
  10392. opcode = Js::OpCode::BrGt_I4;
  10393. // We'll get a warning if we don't assign a value to these...
  10394. // We'll assert if we use them and make a range where min > max
  10395. newMin = 2; newMax = 1;
  10396. break;
  10397. }
  10398. case Js::OpCode::BrGe_A:
  10399. case Js::OpCode::BrNotLt_A:
  10400. {
  10401. if(DoConstFold() &&
  10402. !IsLoopPrePass() &&
  10403. TryOptConstFoldBrGreaterThanOrEqual(instr, true, src1Val, min1, max1, src2Val, min2, max2))
  10404. {
  10405. return true;
  10406. }
  10407. const bool specialize = IsWorthSpecializingToInt32Branch(instr, src1Val, src2Val);
  10408. UpdateIntBoundsForGreaterThanOrEqualBranch(src1Val, src2Val);
  10409. if(!specialize)
  10410. {
  10411. return false;
  10412. }
  10413. opcode = Js::OpCode::BrGe_I4;
  10414. // We'll get a warning if we don't assign a value to these...
  10415. // We'll assert if we use them and make a range where min > max
  10416. newMin = 2; newMax = 1;
  10417. break;
  10418. }
  10419. case Js::OpCode::BrLt_A:
  10420. case Js::OpCode::BrNotGe_A:
  10421. {
  10422. if(DoConstFold() &&
  10423. !IsLoopPrePass() &&
  10424. TryOptConstFoldBrGreaterThanOrEqual(instr, false, src1Val, min1, max1, src2Val, min2, max2))
  10425. {
  10426. return true;
  10427. }
  10428. const bool specialize = IsWorthSpecializingToInt32Branch(instr, src1Val, src2Val);
  10429. UpdateIntBoundsForLessThanBranch(src1Val, src2Val);
  10430. if(!specialize)
  10431. {
  10432. return false;
  10433. }
  10434. opcode = Js::OpCode::BrLt_I4;
  10435. // We'll get a warning if we don't assign a value to these...
  10436. // We'll assert if we use them and make a range where min > max
  10437. newMin = 2; newMax = 1;
  10438. break;
  10439. }
  10440. case Js::OpCode::BrLe_A:
  10441. case Js::OpCode::BrNotGt_A:
  10442. {
  10443. if(DoConstFold() &&
  10444. !IsLoopPrePass() &&
  10445. TryOptConstFoldBrGreaterThan(instr, false, src1Val, min1, max1, src2Val, min2, max2))
  10446. {
  10447. return true;
  10448. }
  10449. const bool specialize = IsWorthSpecializingToInt32Branch(instr, src1Val, src2Val);
  10450. UpdateIntBoundsForLessThanOrEqualBranch(src1Val, src2Val);
  10451. if(!specialize)
  10452. {
  10453. return false;
  10454. }
  10455. opcode = Js::OpCode::BrLe_I4;
  10456. // We'll get a warning if we don't assign a value to these...
  10457. // We'll assert if we use them and make a range where min > max
  10458. newMin = 2; newMax = 1;
  10459. break;
  10460. }
  10461. default:
  10462. return false;
  10463. }
  10464. // If this instruction is in a range of instructions where int overflow does not matter, we will still specialize it
  10465. // (won't leave it unspecialized based on heuristics), since it is most likely worth specializing, and the dst value
  10466. // needs to be guaranteed to be an int
  10467. if(!ignoredIntOverflow &&
  10468. !ignoredNegativeZero &&
  10469. !needsBoolConv &&
  10470. instr->ShouldCheckForIntOverflow() &&
  10471. !IsWorthSpecializingToInt32(instr, src1Val, src2Val))
  10472. {
  10473. // Even though type specialization is being skipped since it may not be worth it, the proper value should still be
  10474. // maintained so that the result may be type specialized later. An int value is not created for the dst in any of
  10475. // the following cases.
  10476. // - A bailout check is necessary to specialize this instruction. The bailout check is what guarantees the result to
  10477. // be an int, but since we're not going to specialize this instruction, there won't be a bailout check.
  10478. // - Aggressive int type specialization is disabled and we're in a loop prepass. We're conservative on dst values in
  10479. // that case, especially if the dst sym is live on the back-edge.
  10480. if(bailOutKind == IR::BailOutInvalid &&
  10481. instr->GetDst() &&
  10482. src1Val->GetValueInfo()->IsInt() &&
  10483. src2Val->GetValueInfo()->IsInt() &&
  10484. (DoAggressiveIntTypeSpec() || !this->IsLoopPrePass()))
  10485. {
  10486. *pDstVal = CreateDstUntransferredIntValue(newMin, newMax, instr, src1Val, src2Val);
  10487. }
  10488. return false;
  10489. }
  10490. } // case default
  10491. } // switch
  10492. LOutsideSwitch:
  10493. this->ignoredIntOverflowForCurrentInstr = ignoredIntOverflow;
  10494. this->ignoredNegativeZeroForCurrentInstr = ignoredNegativeZero;
  10495. {
  10496. // Try CSE again before modifying the IR, in case some attributes are required for successful CSE
  10497. Value *src1IndirIndexVal = nullptr;
  10498. if(CSEOptimize(currentBlock, &instr, &src1Val, &src2Val, &src1IndirIndexVal, true /* intMathExprOnly */))
  10499. {
  10500. *redoTypeSpecRef = true;
  10501. return false;
  10502. }
  10503. }
  10504. const Js::OpCode originalOpCode = instr->m_opcode;
  10505. if (!this->IsLoopPrePass())
  10506. {
  10507. // No re-write on prepass
  10508. instr->m_opcode = opcode;
  10509. }
  10510. Value *src1ValueToSpecialize = src1Val, *src2ValueToSpecialize = src2Val;
  10511. // Lossy conversions to int32 must be done based on the original source values. For instance, if one of the values is a
  10512. // float constant with a value that fits in a uint32 but not an int32, and the instruction can ignore int overflow, the
  10513. // source value for the purposes of int specialization would have been changed to an int constant value by ignoring
  10514. // overflow. If we were to specialize the sym using the int constant value, it would be treated as a lossless
  10515. // conversion, but since there may be subsequent uses of the same float constant value that may not ignore overflow,
  10516. // this must be treated as a lossy conversion by specializing the sym using the original float constant value.
  10517. if(src1Lossy)
  10518. {
  10519. src1ValueToSpecialize = src1OriginalVal;
  10520. }
  10521. if (src2Lossy)
  10522. {
  10523. src2ValueToSpecialize = src2OriginalVal;
  10524. }
  10525. // Make sure the srcs are specialized
  10526. src1 = instr->GetSrc1();
  10527. this->ToInt32(instr, src1, this->currentBlock, src1ValueToSpecialize, nullptr, src1Lossy);
  10528. if (!skipSrc2)
  10529. {
  10530. src2 = instr->GetSrc2();
  10531. this->ToInt32(instr, src2, this->currentBlock, src2ValueToSpecialize, nullptr, src2Lossy);
  10532. }
  10533. if(bailOutKind != IR::BailOutInvalid && !this->IsLoopPrePass())
  10534. {
  10535. GenerateBailAtOperation(&instr, bailOutKind);
  10536. }
  10537. if (!skipDst && instr->GetDst())
  10538. {
  10539. if (needsBoolConv)
  10540. {
  10541. IR::RegOpnd *varDst;
  10542. if (this->IsLoopPrePass())
  10543. {
  10544. varDst = instr->GetDst()->AsRegOpnd();
  10545. this->ToVarRegOpnd(varDst, this->currentBlock);
  10546. }
  10547. else
  10548. {
  10549. // Generate:
  10550. // t1.i = CmCC t2.i, t3.i
  10551. // t1.v = Conv_bool t1.i
  10552. //
  10553. // If the only uses of t1 are ints, the conv_bool will get dead-stored
  10554. TypeSpecializeIntDst(instr, originalOpCode, nullptr, src1Val, src2Val, bailOutKind, newMin, newMax, pDstVal);
  10555. IR::RegOpnd *intDst = instr->GetDst()->AsRegOpnd();
  10556. intDst->SetIsJITOptimizedReg(true);
  10557. varDst = IR::RegOpnd::New(intDst->m_sym->GetVarEquivSym(this->func), TyVar, this->func);
  10558. IR::Instr *convBoolInstr = IR::Instr::New(Js::OpCode::Conv_Bool, varDst, intDst, this->func);
  10559. instr->InsertAfter(convBoolInstr);
  10560. convBoolInstr->SetByteCodeOffset(instr);
  10561. this->ToVarRegOpnd(varDst, this->currentBlock);
  10562. this->blockData.liveInt32Syms->Set(varDst->m_sym->m_id);
  10563. this->blockData.liveLossyInt32Syms->Set(varDst->m_sym->m_id);
  10564. }
  10565. *pDstVal = this->NewGenericValue(ValueType::Boolean, varDst);
  10566. }
  10567. else
  10568. {
  10569. TypeSpecializeIntDst(
  10570. instr,
  10571. originalOpCode,
  10572. nullptr,
  10573. src1Val,
  10574. src2Val,
  10575. bailOutKind,
  10576. newMin,
  10577. newMax,
  10578. pDstVal,
  10579. addSubConstantInfo.HasInfo() ? &addSubConstantInfo : nullptr);
  10580. }
  10581. }
  10582. if(bailOutKind == IR::BailOutInvalid)
  10583. {
  10584. GOPT_TRACE(_u("Type specialized to INT\n"));
  10585. #if ENABLE_DEBUG_CONFIG_OPTIONS
  10586. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::AggressiveIntTypeSpecPhase))
  10587. {
  10588. Output::Print(_u("Type specialized to INT: "));
  10589. Output::Print(_u("%s \n"), Js::OpCodeUtil::GetOpCodeName(instr->m_opcode));
  10590. }
  10591. #endif
  10592. }
  10593. else
  10594. {
  10595. GOPT_TRACE(_u("Type specialized to INT with bailout on:\n"));
  10596. if(bailOutKind & (IR::BailOutOnOverflow | IR::BailOutOnMulOverflow) )
  10597. {
  10598. GOPT_TRACE(_u(" Overflow\n"));
  10599. #if ENABLE_DEBUG_CONFIG_OPTIONS
  10600. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::AggressiveIntTypeSpecPhase))
  10601. {
  10602. Output::Print(_u("Type specialized to INT with bailout (%S): "), "Overflow");
  10603. Output::Print(_u("%s \n"), Js::OpCodeUtil::GetOpCodeName(instr->m_opcode));
  10604. }
  10605. #endif
  10606. }
  10607. if(bailOutKind & IR::BailOutOnNegativeZero)
  10608. {
  10609. GOPT_TRACE(_u(" Zero\n"));
  10610. #if ENABLE_DEBUG_CONFIG_OPTIONS
  10611. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::AggressiveIntTypeSpecPhase))
  10612. {
  10613. Output::Print(_u("Type specialized to INT with bailout (%S): "), "Zero");
  10614. Output::Print(_u("%s \n"), Js::OpCodeUtil::GetOpCodeName(instr->m_opcode));
  10615. }
  10616. #endif
  10617. }
  10618. }
  10619. return true;
  10620. }
  10621. bool
  10622. GlobOpt::IsWorthSpecializingToInt32Branch(IR::Instr * instr, Value * src1Val, Value * src2Val)
  10623. {
  10624. if (!src1Val->GetValueInfo()->HasIntConstantValue() && instr->GetSrc1()->IsRegOpnd())
  10625. {
  10626. StackSym *sym = instr->GetSrc1()->AsRegOpnd()->m_sym;
  10627. if (this->IsInt32TypeSpecialized(sym, this->currentBlock) == false)
  10628. {
  10629. if (!src2Val->GetValueInfo()->HasIntConstantValue() && instr->GetSrc2()->IsRegOpnd())
  10630. {
  10631. StackSym *sym = instr->GetSrc2()->AsRegOpnd()->m_sym;
  10632. if (this->IsInt32TypeSpecialized(sym, this->currentBlock) == false)
  10633. {
  10634. // Type specializing a Br itself isn't worth it, unless one src
  10635. // is already type specialized
  10636. return false;
  10637. }
  10638. }
  10639. }
  10640. }
  10641. return true;
  10642. }
  10643. bool
  10644. GlobOpt::TryOptConstFoldBrFalse(
  10645. IR::Instr *const instr,
  10646. Value *const srcValue,
  10647. const int32 min,
  10648. const int32 max)
  10649. {
  10650. Assert(instr);
  10651. Assert(instr->m_opcode == Js::OpCode::BrFalse_A || instr->m_opcode == Js::OpCode::BrTrue_A);
  10652. Assert(srcValue);
  10653. if(!(DoAggressiveIntTypeSpec() ? srcValue->GetValueInfo()->IsLikelyInt() : srcValue->GetValueInfo()->IsInt()))
  10654. {
  10655. return false;
  10656. }
  10657. if(ValueInfo::IsEqualTo(srcValue, min, max, nullptr, 0, 0))
  10658. {
  10659. OptConstFoldBr(instr->m_opcode == Js::OpCode::BrFalse_A, instr, srcValue);
  10660. return true;
  10661. }
  10662. if(ValueInfo::IsNotEqualTo(srcValue, min, max, nullptr, 0, 0))
  10663. {
  10664. OptConstFoldBr(instr->m_opcode == Js::OpCode::BrTrue_A, instr, srcValue);
  10665. return true;
  10666. }
  10667. return false;
  10668. }
  10669. bool
  10670. GlobOpt::TryOptConstFoldBrEqual(
  10671. IR::Instr *const instr,
  10672. const bool branchOnEqual,
  10673. Value *const src1Value,
  10674. const int32 min1,
  10675. const int32 max1,
  10676. Value *const src2Value,
  10677. const int32 min2,
  10678. const int32 max2)
  10679. {
  10680. Assert(instr);
  10681. Assert(src1Value);
  10682. Assert(DoAggressiveIntTypeSpec() ? src1Value->GetValueInfo()->IsLikelyInt() : src1Value->GetValueInfo()->IsInt());
  10683. Assert(src2Value);
  10684. Assert(DoAggressiveIntTypeSpec() ? src2Value->GetValueInfo()->IsLikelyInt() : src2Value->GetValueInfo()->IsInt());
  10685. if(ValueInfo::IsEqualTo(src1Value, min1, max1, src2Value, min2, max2))
  10686. {
  10687. OptConstFoldBr(branchOnEqual, instr, src1Value, src2Value);
  10688. return true;
  10689. }
  10690. if(ValueInfo::IsNotEqualTo(src1Value, min1, max1, src2Value, min2, max2))
  10691. {
  10692. OptConstFoldBr(!branchOnEqual, instr, src1Value, src2Value);
  10693. return true;
  10694. }
  10695. return false;
  10696. }
  10697. bool
  10698. GlobOpt::TryOptConstFoldBrGreaterThan(
  10699. IR::Instr *const instr,
  10700. const bool branchOnGreaterThan,
  10701. Value *const src1Value,
  10702. const int32 min1,
  10703. const int32 max1,
  10704. Value *const src2Value,
  10705. const int32 min2,
  10706. const int32 max2)
  10707. {
  10708. Assert(instr);
  10709. Assert(src1Value);
  10710. Assert(DoAggressiveIntTypeSpec() ? src1Value->GetValueInfo()->IsLikelyInt() : src1Value->GetValueInfo()->IsInt());
  10711. Assert(src2Value);
  10712. Assert(DoAggressiveIntTypeSpec() ? src2Value->GetValueInfo()->IsLikelyInt() : src2Value->GetValueInfo()->IsInt());
  10713. if(ValueInfo::IsGreaterThan(src1Value, min1, max1, src2Value, min2, max2))
  10714. {
  10715. OptConstFoldBr(branchOnGreaterThan, instr, src1Value, src2Value);
  10716. return true;
  10717. }
  10718. if(ValueInfo::IsLessThanOrEqualTo(src1Value, min1, max1, src2Value, min2, max2))
  10719. {
  10720. OptConstFoldBr(!branchOnGreaterThan, instr, src1Value, src2Value);
  10721. return true;
  10722. }
  10723. return false;
  10724. }
  10725. bool
  10726. GlobOpt::TryOptConstFoldBrGreaterThanOrEqual(
  10727. IR::Instr *const instr,
  10728. const bool branchOnGreaterThanOrEqual,
  10729. Value *const src1Value,
  10730. const int32 min1,
  10731. const int32 max1,
  10732. Value *const src2Value,
  10733. const int32 min2,
  10734. const int32 max2)
  10735. {
  10736. Assert(instr);
  10737. Assert(src1Value);
  10738. Assert(DoAggressiveIntTypeSpec() ? src1Value->GetValueInfo()->IsLikelyInt() : src1Value->GetValueInfo()->IsInt());
  10739. Assert(src2Value);
  10740. Assert(DoAggressiveIntTypeSpec() ? src2Value->GetValueInfo()->IsLikelyInt() : src2Value->GetValueInfo()->IsInt());
  10741. if(ValueInfo::IsGreaterThanOrEqualTo(src1Value, min1, max1, src2Value, min2, max2))
  10742. {
  10743. OptConstFoldBr(branchOnGreaterThanOrEqual, instr, src1Value, src2Value);
  10744. return true;
  10745. }
  10746. if(ValueInfo::IsLessThan(src1Value, min1, max1, src2Value, min2, max2))
  10747. {
  10748. OptConstFoldBr(!branchOnGreaterThanOrEqual, instr, src1Value, src2Value);
  10749. return true;
  10750. }
  10751. return false;
  10752. }
  10753. bool
  10754. GlobOpt::TryOptConstFoldBrUnsignedLessThan(
  10755. IR::Instr *const instr,
  10756. const bool branchOnLessThan,
  10757. Value *const src1Value,
  10758. const int32 min1,
  10759. const int32 max1,
  10760. Value *const src2Value,
  10761. const int32 min2,
  10762. const int32 max2)
  10763. {
  10764. Assert(DoConstFold());
  10765. Assert(!IsLoopPrePass());
  10766. if(!src1Value ||
  10767. !src2Value ||
  10768. !(
  10769. DoAggressiveIntTypeSpec()
  10770. ? src1Value->GetValueInfo()->IsLikelyInt() && src2Value->GetValueInfo()->IsLikelyInt()
  10771. : src1Value->GetValueInfo()->IsInt() && src2Value->GetValueInfo()->IsInt()
  10772. ))
  10773. {
  10774. return false;
  10775. }
  10776. uint uMin1 = (min1 < 0 ? (max1 < 0 ? min((uint)min1, (uint)max1) : 0) : min1);
  10777. uint uMax1 = max((uint)min1, (uint)max1);
  10778. uint uMin2 = (min2 < 0 ? (max2 < 0 ? min((uint)min2, (uint)max2) : 0) : min2);
  10779. uint uMax2 = max((uint)min2, (uint)max2);
  10780. if (uMax1 < uMin2)
  10781. {
  10782. // Range 1 is always lesser than Range 2
  10783. OptConstFoldBr(branchOnLessThan, instr, src1Value, src2Value);
  10784. return true;
  10785. }
  10786. if (uMin1 >= uMax2)
  10787. {
  10788. // Range 2 is always lesser than Range 1
  10789. OptConstFoldBr(!branchOnLessThan, instr, src1Value, src2Value);
  10790. return true;
  10791. }
  10792. return false;
  10793. }
  10794. bool
  10795. GlobOpt::TryOptConstFoldBrUnsignedGreaterThan(
  10796. IR::Instr *const instr,
  10797. const bool branchOnGreaterThan,
  10798. Value *const src1Value,
  10799. const int32 min1,
  10800. const int32 max1,
  10801. Value *const src2Value,
  10802. const int32 min2,
  10803. const int32 max2)
  10804. {
  10805. Assert(DoConstFold());
  10806. Assert(!IsLoopPrePass());
  10807. if(!src1Value ||
  10808. !src2Value ||
  10809. !(
  10810. DoAggressiveIntTypeSpec()
  10811. ? src1Value->GetValueInfo()->IsLikelyInt() && src2Value->GetValueInfo()->IsLikelyInt()
  10812. : src1Value->GetValueInfo()->IsInt() && src2Value->GetValueInfo()->IsInt()
  10813. ))
  10814. {
  10815. return false;
  10816. }
  10817. uint uMin1 = (min1 < 0 ? (max1 < 0 ? min((uint)min1, (uint)max1) : 0) : min1);
  10818. uint uMax1 = max((uint)min1, (uint)max1);
  10819. uint uMin2 = (min2 < 0 ? (max2 < 0 ? min((uint)min2, (uint)max2) : 0) : min2);
  10820. uint uMax2 = max((uint)min2, (uint)max2);
  10821. if (uMin1 > uMax2)
  10822. {
  10823. // Range 1 is always greater than Range 2
  10824. OptConstFoldBr(branchOnGreaterThan, instr, src1Value, src2Value);
  10825. return true;
  10826. }
  10827. if (uMax1 <= uMin2)
  10828. {
  10829. // Range 2 is always greater than Range 1
  10830. OptConstFoldBr(!branchOnGreaterThan, instr, src1Value, src2Value);
  10831. return true;
  10832. }
  10833. return false;
  10834. }
  10835. void
  10836. GlobOpt::SetPathDependentInfo(const bool conditionToBranch, const PathDependentInfo &info)
  10837. {
  10838. Assert(this->currentBlock->GetSuccList()->Count() == 2);
  10839. IR::Instr * fallthrough = this->currentBlock->GetNext()->GetFirstInstr();
  10840. FOREACH_SLISTBASECOUNTED_ENTRY(FlowEdge*, edge, this->currentBlock->GetSuccList())
  10841. {
  10842. if (conditionToBranch == (edge->GetSucc()->GetFirstInstr() != fallthrough))
  10843. {
  10844. edge->SetPathDependentInfo(info, alloc);
  10845. return;
  10846. }
  10847. }
  10848. NEXT_SLISTBASECOUNTED_ENTRY;
  10849. Assert(false);
  10850. }
  10851. PathDependentInfoToRestore
  10852. GlobOpt::UpdatePathDependentInfo(PathDependentInfo *const info)
  10853. {
  10854. Assert(info);
  10855. if(!info->HasInfo())
  10856. {
  10857. return PathDependentInfoToRestore();
  10858. }
  10859. decltype(&GlobOpt::UpdateIntBoundsForEqual) UpdateIntBoundsForLeftValue, UpdateIntBoundsForRightValue;
  10860. switch(info->Relationship())
  10861. {
  10862. case PathDependentRelationship::Equal:
  10863. UpdateIntBoundsForLeftValue = &GlobOpt::UpdateIntBoundsForEqual;
  10864. UpdateIntBoundsForRightValue = &GlobOpt::UpdateIntBoundsForEqual;
  10865. break;
  10866. case PathDependentRelationship::NotEqual:
  10867. UpdateIntBoundsForLeftValue = &GlobOpt::UpdateIntBoundsForNotEqual;
  10868. UpdateIntBoundsForRightValue = &GlobOpt::UpdateIntBoundsForNotEqual;
  10869. break;
  10870. case PathDependentRelationship::GreaterThanOrEqual:
  10871. UpdateIntBoundsForLeftValue = &GlobOpt::UpdateIntBoundsForGreaterThanOrEqual;
  10872. UpdateIntBoundsForRightValue = &GlobOpt::UpdateIntBoundsForLessThanOrEqual;
  10873. break;
  10874. case PathDependentRelationship::GreaterThan:
  10875. UpdateIntBoundsForLeftValue = &GlobOpt::UpdateIntBoundsForGreaterThan;
  10876. UpdateIntBoundsForRightValue = &GlobOpt::UpdateIntBoundsForLessThan;
  10877. break;
  10878. case PathDependentRelationship::LessThanOrEqual:
  10879. UpdateIntBoundsForLeftValue = &GlobOpt::UpdateIntBoundsForLessThanOrEqual;
  10880. UpdateIntBoundsForRightValue = &GlobOpt::UpdateIntBoundsForGreaterThanOrEqual;
  10881. break;
  10882. case PathDependentRelationship::LessThan:
  10883. UpdateIntBoundsForLeftValue = &GlobOpt::UpdateIntBoundsForLessThan;
  10884. UpdateIntBoundsForRightValue = &GlobOpt::UpdateIntBoundsForGreaterThan;
  10885. break;
  10886. default:
  10887. Assert(false);
  10888. __assume(false);
  10889. }
  10890. ValueInfo *leftValueInfo = info->LeftValue()->GetValueInfo();
  10891. IntConstantBounds leftConstantBounds;
  10892. AssertVerify(leftValueInfo->TryGetIntConstantBounds(&leftConstantBounds, true));
  10893. ValueInfo *rightValueInfo;
  10894. IntConstantBounds rightConstantBounds;
  10895. if(info->RightValue())
  10896. {
  10897. rightValueInfo = info->RightValue()->GetValueInfo();
  10898. AssertVerify(rightValueInfo->TryGetIntConstantBounds(&rightConstantBounds, true));
  10899. }
  10900. else
  10901. {
  10902. rightValueInfo = nullptr;
  10903. rightConstantBounds = IntConstantBounds(info->RightConstantValue(), info->RightConstantValue());
  10904. }
  10905. ValueInfo *const newLeftValueInfo =
  10906. (this->*UpdateIntBoundsForLeftValue)(
  10907. info->LeftValue(),
  10908. leftConstantBounds,
  10909. info->RightValue(),
  10910. rightConstantBounds,
  10911. true);
  10912. if(newLeftValueInfo)
  10913. {
  10914. ChangeValueInfo(nullptr, info->LeftValue(), newLeftValueInfo);
  10915. AssertVerify(newLeftValueInfo->TryGetIntConstantBounds(&leftConstantBounds, true));
  10916. }
  10917. else
  10918. {
  10919. leftValueInfo = nullptr;
  10920. }
  10921. ValueInfo *const newRightValueInfo =
  10922. (this->*UpdateIntBoundsForRightValue)(
  10923. info->RightValue(),
  10924. rightConstantBounds,
  10925. info->LeftValue(),
  10926. leftConstantBounds,
  10927. true);
  10928. if(newRightValueInfo)
  10929. {
  10930. ChangeValueInfo(nullptr, info->RightValue(), newRightValueInfo);
  10931. }
  10932. else
  10933. {
  10934. rightValueInfo = nullptr;
  10935. }
  10936. return PathDependentInfoToRestore(leftValueInfo, rightValueInfo);
  10937. }
  10938. void
  10939. GlobOpt::RestorePathDependentInfo(PathDependentInfo *const info, const PathDependentInfoToRestore infoToRestore)
  10940. {
  10941. Assert(info);
  10942. if(infoToRestore.LeftValueInfo())
  10943. {
  10944. Assert(info->LeftValue());
  10945. ChangeValueInfo(nullptr, info->LeftValue(), infoToRestore.LeftValueInfo());
  10946. }
  10947. if(infoToRestore.RightValueInfo())
  10948. {
  10949. Assert(info->RightValue());
  10950. ChangeValueInfo(nullptr, info->RightValue(), infoToRestore.RightValueInfo());
  10951. }
  10952. }
  10953. bool
  10954. GlobOpt::TypeSpecializeFloatUnary(IR::Instr **pInstr, Value *src1Val, Value **pDstVal, bool skipDst /* = false */)
  10955. {
  10956. IR::Instr *&instr = *pInstr;
  10957. IR::Opnd *src1;
  10958. IR::Opnd *dst;
  10959. Js::OpCode opcode = instr->m_opcode;
  10960. Value *valueToTransfer = nullptr;
  10961. Assert(src1Val && src1Val->GetValueInfo()->IsLikelyNumber() || OpCodeAttr::IsInlineBuiltIn(instr->m_opcode));
  10962. if (!this->DoFloatTypeSpec())
  10963. {
  10964. return false;
  10965. }
  10966. // For inline built-ins we need to do type specialization. Check upfront to avoid duplicating same case labels.
  10967. if (!OpCodeAttr::IsInlineBuiltIn(instr->m_opcode))
  10968. {
  10969. switch (opcode)
  10970. {
  10971. case Js::OpCode::ArgOut_A_InlineBuiltIn:
  10972. skipDst = true;
  10973. // fall-through
  10974. case Js::OpCode::Ld_A:
  10975. case Js::OpCode::BrTrue_A:
  10976. case Js::OpCode::BrFalse_A:
  10977. if (instr->GetSrc1()->IsRegOpnd())
  10978. {
  10979. StackSym *sym = instr->GetSrc1()->AsRegOpnd()->m_sym;
  10980. if (this->IsFloat64TypeSpecialized(sym, this->currentBlock) == false)
  10981. {
  10982. // Type specializing an Ld_A isn't worth it, unless the src
  10983. // is already type specialized
  10984. return false;
  10985. }
  10986. }
  10987. if (instr->m_opcode == Js::OpCode::Ld_A)
  10988. {
  10989. valueToTransfer = src1Val;
  10990. }
  10991. break;
  10992. case Js::OpCode::Neg_A:
  10993. break;
  10994. case Js::OpCode::Conv_Num:
  10995. Assert(src1Val);
  10996. opcode = Js::OpCode::Ld_A;
  10997. valueToTransfer = src1Val;
  10998. if (!src1Val->GetValueInfo()->IsNumber())
  10999. {
  11000. StackSym *sym = instr->GetSrc1()->AsRegOpnd()->m_sym;
  11001. valueToTransfer = NewGenericValue(ValueType::Float, instr->GetDst()->GetStackSym());
  11002. if (this->IsFloat64TypeSpecialized(sym, this->currentBlock) == false)
  11003. {
  11004. // Set the dst as a nonDeadStore. We want to keep the Ld_A to prevent the FromVar from
  11005. // being dead-stored, as it could cause implicit calls.
  11006. dst = instr->GetDst();
  11007. dst->AsRegOpnd()->m_dontDeadStore = true;
  11008. }
  11009. }
  11010. break;
  11011. case Js::OpCode::StElemI_A:
  11012. case Js::OpCode::StElemI_A_Strict:
  11013. case Js::OpCode::StElemC:
  11014. return TypeSpecializeStElem(pInstr, src1Val, pDstVal);
  11015. default:
  11016. return false;
  11017. }
  11018. }
  11019. // Make sure the srcs are specialized
  11020. src1 = instr->GetSrc1();
  11021. // Use original val when calling toFloat64 as this is what we'll use to try hoisting the fromVar if we're in a loop.
  11022. this->ToFloat64(instr, src1, this->currentBlock, src1Val, nullptr, IR::BailOutPrimitiveButString);
  11023. if (!skipDst)
  11024. {
  11025. dst = instr->GetDst();
  11026. if (dst)
  11027. {
  11028. this->TypeSpecializeFloatDst(instr, valueToTransfer, src1Val, nullptr, pDstVal);
  11029. if (!this->IsLoopPrePass())
  11030. {
  11031. instr->m_opcode = opcode;
  11032. }
  11033. }
  11034. }
  11035. GOPT_TRACE_INSTR(instr, _u("Type specialized to FLOAT: "));
  11036. #if ENABLE_DEBUG_CONFIG_OPTIONS
  11037. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::FloatTypeSpecPhase))
  11038. {
  11039. Output::Print(_u("Type specialized to FLOAT: "));
  11040. Output::Print(_u("%s \n"), Js::OpCodeUtil::GetOpCodeName(instr->m_opcode));
  11041. }
  11042. #endif
  11043. return true;
  11044. }
  11045. // Unconditionally type-spec dst to float.
  11046. void
  11047. GlobOpt::TypeSpecializeFloatDst(IR::Instr *instr, Value *valToTransfer, Value *const src1Value, Value *const src2Value, Value **pDstVal)
  11048. {
  11049. IR::Opnd* dst = instr->GetDst();
  11050. Assert(dst);
  11051. AssertMsg(dst->IsRegOpnd(), "What else?");
  11052. this->ToFloat64Dst(instr, dst->AsRegOpnd(), this->currentBlock);
  11053. if(valToTransfer)
  11054. {
  11055. *pDstVal = this->ValueNumberTransferDst(instr, valToTransfer);
  11056. InsertNewValue(*pDstVal, dst);
  11057. }
  11058. else
  11059. {
  11060. *pDstVal = CreateDstUntransferredValue(ValueType::Float, instr, src1Value, src2Value);
  11061. }
  11062. }
  11063. void
  11064. GlobOpt::TypeSpecializeSimd128Dst(IRType type, IR::Instr *instr, Value *valToTransfer, Value *const src1Value, Value **pDstVal)
  11065. {
  11066. IR::Opnd* dst = instr->GetDst();
  11067. Assert(dst);
  11068. AssertMsg(dst->IsRegOpnd(), "What else?");
  11069. this->ToSimd128Dst(type, instr, dst->AsRegOpnd(), this->currentBlock);
  11070. if (valToTransfer)
  11071. {
  11072. *pDstVal = this->ValueNumberTransferDst(instr, valToTransfer);
  11073. InsertNewValue(*pDstVal, dst);
  11074. }
  11075. else
  11076. {
  11077. *pDstVal = NewGenericValue(GetValueTypeFromIRType(type), instr->GetDst());
  11078. }
  11079. }
  11080. bool
  11081. GlobOpt::TypeSpecializeLdLen(
  11082. IR::Instr * *const instrRef,
  11083. Value * *const src1ValueRef,
  11084. Value * *const dstValueRef,
  11085. bool *const forceInvariantHoistingRef)
  11086. {
  11087. Assert(instrRef);
  11088. IR::Instr *&instr = *instrRef;
  11089. Assert(instr);
  11090. Assert(instr->m_opcode == Js::OpCode::LdLen_A);
  11091. Assert(src1ValueRef);
  11092. Value *&src1Value = *src1ValueRef;
  11093. Assert(dstValueRef);
  11094. Value *&dstValue = *dstValueRef;
  11095. Assert(forceInvariantHoistingRef);
  11096. bool &forceInvariantHoisting = *forceInvariantHoistingRef;
  11097. if(!DoLdLenIntSpec(instr, instr->GetSrc1()->GetValueType()))
  11098. {
  11099. return false;
  11100. }
  11101. IR::BailOutKind bailOutKind = IR::BailOutOnIrregularLength;
  11102. if(!IsLoopPrePass())
  11103. {
  11104. IR::RegOpnd *const baseOpnd = instr->GetSrc1()->AsRegOpnd();
  11105. if(baseOpnd->IsArrayRegOpnd())
  11106. {
  11107. StackSym *const lengthSym = baseOpnd->AsArrayRegOpnd()->LengthSym();
  11108. if(lengthSym)
  11109. {
  11110. CaptureByteCodeSymUses(instr);
  11111. instr->m_opcode = Js::OpCode::Ld_I4;
  11112. instr->ReplaceSrc1(IR::RegOpnd::New(lengthSym, lengthSym->GetType(), func));
  11113. instr->ClearBailOutInfo();
  11114. // Find the hoisted length value
  11115. Value *const lengthValue = FindValue(lengthSym);
  11116. Assert(lengthValue);
  11117. src1Value = lengthValue;
  11118. ValueInfo *const lengthValueInfo = lengthValue->GetValueInfo();
  11119. Assert(lengthValueInfo->GetSymStore() != lengthSym);
  11120. IntConstantBounds lengthConstantBounds;
  11121. AssertVerify(lengthValueInfo->TryGetIntConstantBounds(&lengthConstantBounds));
  11122. Assert(lengthConstantBounds.LowerBound() >= 0);
  11123. // Int-specialize, and transfer the value to the dst
  11124. TypeSpecializeIntDst(
  11125. instr,
  11126. Js::OpCode::LdLen_A,
  11127. src1Value,
  11128. src1Value,
  11129. nullptr,
  11130. bailOutKind,
  11131. lengthConstantBounds.LowerBound(),
  11132. lengthConstantBounds.UpperBound(),
  11133. &dstValue);
  11134. // Try to force hoisting the Ld_I4 so that the length will have an invariant sym store that can be
  11135. // copy-propped. Invariant hoisting does not automatically hoist Ld_I4.
  11136. forceInvariantHoisting = true;
  11137. return true;
  11138. }
  11139. }
  11140. if (instr->HasBailOutInfo())
  11141. {
  11142. Assert(instr->GetBailOutKind() == IR::BailOutMarkTempObject);
  11143. bailOutKind = IR::BailOutOnIrregularLength | IR::BailOutMarkTempObject;
  11144. instr->SetBailOutKind(bailOutKind);
  11145. }
  11146. else
  11147. {
  11148. Assert(bailOutKind == IR::BailOutOnIrregularLength);
  11149. GenerateBailAtOperation(&instr, bailOutKind);
  11150. }
  11151. }
  11152. TypeSpecializeIntDst(
  11153. instr,
  11154. Js::OpCode::LdLen_A,
  11155. nullptr,
  11156. nullptr,
  11157. nullptr,
  11158. bailOutKind,
  11159. 0,
  11160. INT32_MAX,
  11161. &dstValue);
  11162. return true;
  11163. }
  11164. bool
  11165. GlobOpt::TypeSpecializeFloatBinary(IR::Instr *instr, Value *src1Val, Value *src2Val, Value **pDstVal)
  11166. {
  11167. IR::Opnd *src1;
  11168. IR::Opnd *src2;
  11169. IR::Opnd *dst;
  11170. bool allowUndefinedOrNullSrc1 = true;
  11171. bool allowUndefinedOrNullSrc2 = true;
  11172. bool skipSrc1 = false;
  11173. bool skipSrc2 = false;
  11174. bool skipDst = false;
  11175. if (!this->DoFloatTypeSpec())
  11176. {
  11177. return false;
  11178. }
  11179. // For inline built-ins we need to do type specialization. Check upfront to avoid duplicating same case labels.
  11180. if (!OpCodeAttr::IsInlineBuiltIn(instr->m_opcode))
  11181. {
  11182. switch (instr->m_opcode)
  11183. {
  11184. case Js::OpCode::Sub_A:
  11185. case Js::OpCode::Mul_A:
  11186. case Js::OpCode::Div_A:
  11187. case Js::OpCode::Expo_A:
  11188. // Avoid if one source is known not to be a number.
  11189. if (src1Val->GetValueInfo()->IsNotNumber() || src2Val->GetValueInfo()->IsNotNumber())
  11190. {
  11191. return false;
  11192. }
  11193. break;
  11194. case Js::OpCode::BrSrEq_A:
  11195. case Js::OpCode::BrSrNeq_A:
  11196. case Js::OpCode::BrEq_A:
  11197. case Js::OpCode::BrNeq_A:
  11198. case Js::OpCode::BrSrNotEq_A:
  11199. case Js::OpCode::BrNotEq_A:
  11200. case Js::OpCode::BrSrNotNeq_A:
  11201. case Js::OpCode::BrNotNeq_A:
  11202. // Avoid if one source is known not to be a number.
  11203. if (src1Val->GetValueInfo()->IsNotNumber() || src2Val->GetValueInfo()->IsNotNumber())
  11204. {
  11205. return false;
  11206. }
  11207. // Undef == Undef, but +Undef != +Undef
  11208. // 0.0 != null, but 0.0 == +null
  11209. //
  11210. // So Bailout on anything but numbers for both src1 and src2
  11211. allowUndefinedOrNullSrc1 = false;
  11212. allowUndefinedOrNullSrc2 = false;
  11213. break;
  11214. case Js::OpCode::BrGt_A:
  11215. case Js::OpCode::BrGe_A:
  11216. case Js::OpCode::BrLt_A:
  11217. case Js::OpCode::BrLe_A:
  11218. case Js::OpCode::BrNotGt_A:
  11219. case Js::OpCode::BrNotGe_A:
  11220. case Js::OpCode::BrNotLt_A:
  11221. case Js::OpCode::BrNotLe_A:
  11222. // Avoid if one source is known not to be a number.
  11223. if (src1Val->GetValueInfo()->IsNotNumber() || src2Val->GetValueInfo()->IsNotNumber())
  11224. {
  11225. return false;
  11226. }
  11227. break;
  11228. case Js::OpCode::Add_A:
  11229. // For Add, we need both sources to be Numbers, otherwise it could be a string concat
  11230. if (!src1Val || !src2Val || !(src1Val->GetValueInfo()->IsLikelyNumber() && src2Val->GetValueInfo()->IsLikelyNumber()))
  11231. {
  11232. return false;
  11233. }
  11234. break;
  11235. case Js::OpCode::ArgOut_A_InlineBuiltIn:
  11236. skipSrc2 = true;
  11237. skipDst = true;
  11238. break;
  11239. default:
  11240. return false;
  11241. }
  11242. }
  11243. else
  11244. {
  11245. switch (instr->m_opcode)
  11246. {
  11247. case Js::OpCode::InlineArrayPush:
  11248. bool isFloatConstMissingItem = src2Val->GetValueInfo()->IsFloatConstant();
  11249. if(isFloatConstMissingItem)
  11250. {
  11251. FloatConstType floatValue = src2Val->GetValueInfo()->AsFloatConstant()->FloatValue();
  11252. isFloatConstMissingItem = Js::SparseArraySegment<double>::IsMissingItem(&floatValue);
  11253. }
  11254. // Don't specialize if the element is not likelyNumber - we will surely bailout
  11255. if(!(src2Val->GetValueInfo()->IsLikelyNumber()) || isFloatConstMissingItem)
  11256. {
  11257. return false;
  11258. }
  11259. // Only specialize the Second source - element
  11260. skipSrc1 = true;
  11261. skipDst = true;
  11262. allowUndefinedOrNullSrc2 = false;
  11263. break;
  11264. }
  11265. }
  11266. // Make sure the srcs are specialized
  11267. if(!skipSrc1)
  11268. {
  11269. src1 = instr->GetSrc1();
  11270. this->ToFloat64(instr, src1, this->currentBlock, src1Val, nullptr, (allowUndefinedOrNullSrc1 ? IR::BailOutPrimitiveButString : IR::BailOutNumberOnly));
  11271. }
  11272. if (!skipSrc2)
  11273. {
  11274. src2 = instr->GetSrc2();
  11275. this->ToFloat64(instr, src2, this->currentBlock, src2Val, nullptr, (allowUndefinedOrNullSrc2 ? IR::BailOutPrimitiveButString : IR::BailOutNumberOnly));
  11276. }
  11277. if (!skipDst)
  11278. {
  11279. dst = instr->GetDst();
  11280. if (dst)
  11281. {
  11282. *pDstVal = CreateDstUntransferredValue(ValueType::Float, instr, src1Val, src2Val);
  11283. AssertMsg(dst->IsRegOpnd(), "What else?");
  11284. this->ToFloat64Dst(instr, dst->AsRegOpnd(), this->currentBlock);
  11285. }
  11286. }
  11287. GOPT_TRACE_INSTR(instr, _u("Type specialized to FLOAT: "));
  11288. #if ENABLE_DEBUG_CONFIG_OPTIONS
  11289. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::FloatTypeSpecPhase))
  11290. {
  11291. Output::Print(_u("Type specialized to FLOAT: "));
  11292. Output::Print(_u("%s \n"), Js::OpCodeUtil::GetOpCodeName(instr->m_opcode));
  11293. }
  11294. #endif
  11295. return true;
  11296. }
  11297. bool
  11298. GlobOpt::TypeSpecializeStElem(IR::Instr ** pInstr, Value *src1Val, Value **pDstVal)
  11299. {
  11300. IR::Instr *&instr = *pInstr;
  11301. IR::RegOpnd *baseOpnd = instr->GetDst()->AsIndirOpnd()->GetBaseOpnd();
  11302. ValueType baseValueType(baseOpnd->GetValueType());
  11303. if (instr->DoStackArgsOpt(this->func) ||
  11304. (!this->DoTypedArrayTypeSpec() && baseValueType.IsLikelyOptimizedTypedArray()) ||
  11305. (!this->DoNativeArrayTypeSpec() && baseValueType.IsLikelyNativeArray()) ||
  11306. !(baseValueType.IsLikelyOptimizedTypedArray() || baseValueType.IsLikelyNativeArray()))
  11307. {
  11308. GOPT_TRACE_INSTR(instr, _u("Didn't type specialize array access, because typed array type specialization is disabled, or base is not an optimized typed array.\n"));
  11309. if (PHASE_TRACE(Js::TypedArrayTypeSpecPhase, this->func->GetJnFunction()))
  11310. {
  11311. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  11312. char baseValueTypeStr[VALUE_TYPE_MAX_STRING_SIZE];
  11313. baseValueType.ToString(baseValueTypeStr);
  11314. Output::Print(_u("Typed Array Optimization: function: %s (%s): instr: %s, base value type: %S, did not specialize because %s.\n"),
  11315. this->func->GetJnFunction()->GetDisplayName(),
  11316. this->func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  11317. Js::OpCodeUtil::GetOpCodeName(instr->m_opcode),
  11318. baseValueTypeStr,
  11319. instr->DoStackArgsOpt(this->func) ?
  11320. _u("instruction uses the arguments object") :
  11321. _u("typed array type specialization is disabled, or base is not an optimized typed array"));
  11322. Output::Flush();
  11323. }
  11324. return false;
  11325. }
  11326. Assert(instr->GetSrc1()->IsRegOpnd() || (src1Val && src1Val->GetValueInfo()->HasIntConstantValue()));
  11327. StackSym *sym = instr->GetSrc1()->IsRegOpnd() ? instr->GetSrc1()->AsRegOpnd()->m_sym : nullptr;
  11328. // Only type specialize the source of store element if the source symbol is already type specialized to int or float.
  11329. if (sym)
  11330. {
  11331. if (baseValueType.IsLikelyNativeArray())
  11332. {
  11333. // Gently coerce these src's into native if it seems likely to work.
  11334. // Otherwise we can't use the fast path to store.
  11335. // But don't try to put a float-specialized number into an int array this way.
  11336. if (!(
  11337. this->IsInt32TypeSpecialized(sym, this->currentBlock) ||
  11338. (
  11339. src1Val &&
  11340. (
  11341. DoAggressiveIntTypeSpec()
  11342. ? src1Val->GetValueInfo()->IsLikelyInt()
  11343. : src1Val->GetValueInfo()->IsInt()
  11344. )
  11345. )
  11346. ))
  11347. {
  11348. if (!(
  11349. this->IsFloat64TypeSpecialized(sym, this->currentBlock) ||
  11350. (src1Val && src1Val->GetValueInfo()->IsLikelyNumber())
  11351. ) ||
  11352. baseValueType.HasIntElements())
  11353. {
  11354. return false;
  11355. }
  11356. }
  11357. }
  11358. else if (!this->IsInt32TypeSpecialized(sym, this->currentBlock) && !this->IsFloat64TypeSpecialized(sym, this->currentBlock))
  11359. {
  11360. GOPT_TRACE_INSTR(instr, _u("Didn't specialize array access, because src is not type specialized.\n"));
  11361. if (PHASE_TRACE(Js::TypedArrayTypeSpecPhase, this->func->GetJnFunction()))
  11362. {
  11363. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  11364. char baseValueTypeStr[VALUE_TYPE_MAX_STRING_SIZE];
  11365. baseValueType.ToString(baseValueTypeStr);
  11366. Output::Print(_u("Typed Array Optimization: function: %s (%s): instr: %s, base value type: %S, did not specialize because src is not specialized.\n"),
  11367. this->func->GetJnFunction()->GetDisplayName(),
  11368. this->func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  11369. Js::OpCodeUtil::GetOpCodeName(instr->m_opcode),
  11370. baseValueTypeStr);
  11371. Output::Flush();
  11372. }
  11373. return false;
  11374. }
  11375. }
  11376. int32 src1IntConstantValue;
  11377. if(baseValueType.IsLikelyNativeIntArray() && src1Val && src1Val->GetValueInfo()->TryGetIntConstantValue(&src1IntConstantValue))
  11378. {
  11379. if(Js::SparseArraySegment<int32>::IsMissingItem(&src1IntConstantValue))
  11380. {
  11381. return false;
  11382. }
  11383. }
  11384. // Note: doing ToVarUses to make sure we do get the int32 version of the index before trying to access its value in
  11385. // ShouldExpectConventionalArrayIndexValue. Not sure why that never gave us a problem before.
  11386. Assert(instr->GetDst()->IsIndirOpnd());
  11387. IR::IndirOpnd *dst = instr->GetDst()->AsIndirOpnd();
  11388. // Make sure we use the int32 version of the index operand symbol, if available. Otherwise, ensure the var symbol is live (by
  11389. // potentially inserting a ToVar).
  11390. this->ToVarUses(instr, dst, /* isDst = */ true, nullptr);
  11391. if (!ShouldExpectConventionalArrayIndexValue(dst))
  11392. {
  11393. GOPT_TRACE_INSTR(instr, _u("Didn't specialize array access, because index is negative or likely not int.\n"));
  11394. if (PHASE_TRACE(Js::TypedArrayTypeSpecPhase, this->func->GetJnFunction()))
  11395. {
  11396. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  11397. char baseValueTypeStr[VALUE_TYPE_MAX_STRING_SIZE];
  11398. baseValueType.ToString(baseValueTypeStr);
  11399. Output::Print(_u("Typed Array Optimization: function: %s (%s): instr: %s, base value type: %S, did not specialize because index is negative or likely not int.\n"),
  11400. this->func->GetJnFunction()->GetDisplayName(),
  11401. this->func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  11402. Js::OpCodeUtil::GetOpCodeName(instr->m_opcode),
  11403. baseValueTypeStr);
  11404. Output::Flush();
  11405. }
  11406. return false;
  11407. }
  11408. IRType toType = TyVar;
  11409. bool isLossyAllowed = true;
  11410. IR::BailOutKind arrayBailOutKind = IR::BailOutConventionalTypedArrayAccessOnly;
  11411. switch(baseValueType.GetObjectType())
  11412. {
  11413. case ObjectType::Int8Array:
  11414. case ObjectType::Uint8Array:
  11415. case ObjectType::Int16Array:
  11416. case ObjectType::Uint16Array:
  11417. case ObjectType::Int32Array:
  11418. case ObjectType::Int8VirtualArray:
  11419. case ObjectType::Uint8VirtualArray:
  11420. case ObjectType::Int16VirtualArray:
  11421. case ObjectType::Uint16VirtualArray:
  11422. case ObjectType::Int32VirtualArray:
  11423. case ObjectType::Int8MixedArray:
  11424. case ObjectType::Uint8MixedArray:
  11425. case ObjectType::Int16MixedArray:
  11426. case ObjectType::Uint16MixedArray:
  11427. case ObjectType::Int32MixedArray:
  11428. Int32Array:
  11429. toType = TyInt32;
  11430. break;
  11431. case ObjectType::Uint32Array:
  11432. case ObjectType::Uint32VirtualArray:
  11433. case ObjectType::Uint32MixedArray:
  11434. // Uint32Arrays may store values that overflow int32. If the value being stored comes from a symbol that's
  11435. // already losslessly type specialized to int32, we'll use it. Otherwise, if we only have a float64 specialized
  11436. // value, we don't want to force bailout if it doesn't fit in int32. Instead, we'll emit conversion in the
  11437. // lowerer, and handle overflow, if necessary.
  11438. if (!sym || this->IsInt32TypeSpecialized(sym, this->currentBlock))
  11439. {
  11440. toType = TyInt32;
  11441. }
  11442. else if (this->IsFloat64TypeSpecialized(sym, this->currentBlock))
  11443. {
  11444. toType = TyFloat64;
  11445. }
  11446. break;
  11447. case ObjectType::Float32Array:
  11448. case ObjectType::Float64Array:
  11449. case ObjectType::Float32VirtualArray:
  11450. case ObjectType::Float32MixedArray:
  11451. case ObjectType::Float64VirtualArray:
  11452. case ObjectType::Float64MixedArray:
  11453. Float64Array:
  11454. toType = TyFloat64;
  11455. break;
  11456. case ObjectType::Uint8ClampedArray:
  11457. case ObjectType::Uint8ClampedVirtualArray:
  11458. case ObjectType::Uint8ClampedMixedArray:
  11459. // Uint8ClampedArray requires rounding (as opposed to truncation) of floating point values. If source symbol is
  11460. // float type specialized, type specialize this instruction to float as well, and handle rounding in the
  11461. // lowerer.
  11462. if (!sym || this->IsInt32TypeSpecialized(sym, this->currentBlock))
  11463. {
  11464. toType = TyInt32;
  11465. isLossyAllowed = false;
  11466. }
  11467. else if (this->IsFloat64TypeSpecialized(sym, this->currentBlock))
  11468. {
  11469. toType = TyFloat64;
  11470. }
  11471. break;
  11472. default:
  11473. Assert(baseValueType.IsLikelyNativeArray());
  11474. isLossyAllowed = false;
  11475. arrayBailOutKind = IR::BailOutConventionalNativeArrayAccessOnly;
  11476. if(baseValueType.HasIntElements())
  11477. {
  11478. goto Int32Array;
  11479. }
  11480. Assert(baseValueType.HasFloatElements());
  11481. goto Float64Array;
  11482. }
  11483. if (toType != TyVar)
  11484. {
  11485. GOPT_TRACE_INSTR(instr, _u("Type specialized array access.\n"));
  11486. if (PHASE_TRACE(Js::TypedArrayTypeSpecPhase, this->func->GetJnFunction()))
  11487. {
  11488. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  11489. char baseValueTypeStr[VALUE_TYPE_MAX_STRING_SIZE];
  11490. baseValueType.ToString(baseValueTypeStr);
  11491. Output::Print(_u("Typed Array Optimization: function: %s (%s): instr: %s, base value type: %S, type specialized to %s.\n"),
  11492. this->func->GetJnFunction()->GetDisplayName(),
  11493. this->func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  11494. Js::OpCodeUtil::GetOpCodeName(instr->m_opcode),
  11495. baseValueTypeStr,
  11496. toType == TyInt32 ? _u("int32") : _u("float64"));
  11497. Output::Flush();
  11498. }
  11499. IR::BailOutKind bailOutKind = ((toType == TyInt32) ? IR::BailOutIntOnly : IR::BailOutNumberOnly);
  11500. this->ToTypeSpecUse(instr, instr->GetSrc1(), this->currentBlock, src1Val, nullptr, toType, bailOutKind, /* lossy = */ isLossyAllowed);
  11501. if (!this->IsLoopPrePass())
  11502. {
  11503. bool bConvertToBailoutInstr = true;
  11504. // Definite StElemC doesn't need bailout, because it can't fail or cause conversion.
  11505. if (instr->m_opcode == Js::OpCode::StElemC && baseValueType.IsObject())
  11506. {
  11507. if (baseValueType.HasIntElements())
  11508. {
  11509. //Native int array requires a missing element check & bailout
  11510. int32 min = INT32_MIN;
  11511. int32 max = INT32_MAX;
  11512. if (src1Val->GetValueInfo()->GetIntValMinMax(&min, &max, false))
  11513. {
  11514. bConvertToBailoutInstr = ((min <= Js::JavascriptNativeIntArray::MissingItem) && (max >= Js::JavascriptNativeIntArray::MissingItem));
  11515. }
  11516. }
  11517. else
  11518. {
  11519. bConvertToBailoutInstr = false;
  11520. }
  11521. }
  11522. if (bConvertToBailoutInstr)
  11523. {
  11524. if(instr->HasBailOutInfo())
  11525. {
  11526. const IR::BailOutKind oldBailOutKind = instr->GetBailOutKind();
  11527. Assert(
  11528. (
  11529. !(oldBailOutKind & ~IR::BailOutKindBits) ||
  11530. (oldBailOutKind & ~IR::BailOutKindBits) == IR::BailOutOnImplicitCallsPreOp
  11531. ) &&
  11532. !(oldBailOutKind & IR::BailOutKindBits & ~(IR::BailOutOnArrayAccessHelperCall | IR::BailOutMarkTempObject)));
  11533. if(arrayBailOutKind == IR::BailOutConventionalTypedArrayAccessOnly)
  11534. {
  11535. // BailOutConventionalTypedArrayAccessOnly also bails out if the array access is outside the head
  11536. // segment bounds, and guarantees no implicit calls. Override the bailout kind so that the instruction
  11537. // bails out for the right reason.
  11538. instr->SetBailOutKind(
  11539. arrayBailOutKind | (oldBailOutKind & (IR::BailOutKindBits - IR::BailOutOnArrayAccessHelperCall)));
  11540. }
  11541. else
  11542. {
  11543. // BailOutConventionalNativeArrayAccessOnly by itself may generate a helper call, and may cause implicit
  11544. // calls to occur, so it must be merged in to eliminate generating the helper call.
  11545. Assert(arrayBailOutKind == IR::BailOutConventionalNativeArrayAccessOnly);
  11546. instr->SetBailOutKind(oldBailOutKind | arrayBailOutKind);
  11547. }
  11548. }
  11549. else
  11550. {
  11551. GenerateBailAtOperation(&instr, arrayBailOutKind);
  11552. }
  11553. }
  11554. }
  11555. }
  11556. else
  11557. {
  11558. GOPT_TRACE_INSTR(instr, _u("Didn't specialize array access, because the source was not already specialized.\n"));
  11559. if (PHASE_TRACE(Js::TypedArrayTypeSpecPhase, this->func->GetJnFunction()))
  11560. {
  11561. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  11562. char baseValueTypeStr[VALUE_TYPE_MAX_STRING_SIZE];
  11563. baseValueType.ToString(baseValueTypeStr);
  11564. Output::Print(_u("Typed Array Optimization: function: %s (%s): instr: %s, base value type: %S, did not type specialize, because of array type.\n"),
  11565. this->func->GetJnFunction()->GetDisplayName(),
  11566. this->func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  11567. Js::OpCodeUtil::GetOpCodeName(instr->m_opcode),
  11568. baseValueTypeStr);
  11569. Output::Flush();
  11570. }
  11571. }
  11572. return toType != TyVar;
  11573. }
  11574. IR::Instr *
  11575. GlobOpt::ToVarUses(IR::Instr *instr, IR::Opnd *opnd, bool isDst, Value *val)
  11576. {
  11577. Sym *sym;
  11578. switch (opnd->GetKind())
  11579. {
  11580. case IR::OpndKindReg:
  11581. if (!isDst && !this->blockData.liveVarSyms->Test(opnd->AsRegOpnd()->m_sym->m_id))
  11582. {
  11583. instr = this->ToVar(instr, opnd->AsRegOpnd(), this->currentBlock, val, true);
  11584. }
  11585. break;
  11586. case IR::OpndKindSym:
  11587. sym = opnd->AsSymOpnd()->m_sym;
  11588. if (sym->IsPropertySym() && !this->blockData.liveVarSyms->Test(sym->AsPropertySym()->m_stackSym->m_id)
  11589. && sym->AsPropertySym()->m_stackSym->IsVar())
  11590. {
  11591. StackSym *propertyBase = sym->AsPropertySym()->m_stackSym;
  11592. IR::RegOpnd *newOpnd = IR::RegOpnd::New(propertyBase, TyVar, instr->m_func);
  11593. instr = this->ToVar(instr, newOpnd, this->currentBlock, this->FindValue(propertyBase), true);
  11594. }
  11595. break;
  11596. case IR::OpndKindIndir:
  11597. IR::RegOpnd *baseOpnd = opnd->AsIndirOpnd()->GetBaseOpnd();
  11598. if (!this->blockData.liveVarSyms->Test(baseOpnd->m_sym->m_id))
  11599. {
  11600. instr = this->ToVar(instr, baseOpnd, this->currentBlock, this->FindValue(baseOpnd->m_sym), true);
  11601. }
  11602. IR::RegOpnd *indexOpnd = opnd->AsIndirOpnd()->GetIndexOpnd();
  11603. if (indexOpnd && !indexOpnd->m_sym->IsTypeSpec())
  11604. {
  11605. if((indexOpnd->GetValueType().IsInt()
  11606. ? !IsTypeSpecPhaseOff(func)
  11607. : indexOpnd->GetValueType().IsLikelyInt() && DoAggressiveIntTypeSpec()) && !GetIsAsmJSFunc()) // typespec is disabled for asmjs
  11608. {
  11609. StackSym *const indexVarSym = indexOpnd->m_sym;
  11610. Value *const indexValue = FindValue(indexVarSym);
  11611. Assert(indexValue);
  11612. Assert(indexValue->GetValueInfo()->IsLikelyInt());
  11613. ToInt32(instr, indexOpnd, currentBlock, indexValue, opnd->AsIndirOpnd(), false);
  11614. Assert(indexValue->GetValueInfo()->IsInt());
  11615. if(!IsLoopPrePass())
  11616. {
  11617. indexOpnd = opnd->AsIndirOpnd()->GetIndexOpnd();
  11618. if(indexOpnd)
  11619. {
  11620. Assert(indexOpnd->m_sym->IsTypeSpec());
  11621. IntConstantBounds indexConstantBounds;
  11622. AssertVerify(indexValue->GetValueInfo()->TryGetIntConstantBounds(&indexConstantBounds));
  11623. if(ValueInfo::IsGreaterThanOrEqualTo(
  11624. indexValue,
  11625. indexConstantBounds.LowerBound(),
  11626. indexConstantBounds.UpperBound(),
  11627. nullptr,
  11628. 0,
  11629. 0))
  11630. {
  11631. indexOpnd->SetType(TyUint32);
  11632. }
  11633. }
  11634. }
  11635. }
  11636. else if (!this->blockData.liveVarSyms->Test(indexOpnd->m_sym->m_id))
  11637. {
  11638. instr = this->ToVar(instr, indexOpnd, this->currentBlock, this->FindValue(indexOpnd->m_sym), true);
  11639. }
  11640. }
  11641. break;
  11642. }
  11643. return instr;
  11644. }
  11645. IR::Instr *
  11646. GlobOpt::ToVar(IR::Instr *instr, IR::RegOpnd *regOpnd, BasicBlock *block, Value *value, bool needsUpdate)
  11647. {
  11648. IR::Instr *newInstr;
  11649. StackSym *varSym = regOpnd->m_sym;
  11650. if (IsTypeSpecPhaseOff(this->func))
  11651. {
  11652. return instr;
  11653. }
  11654. if (this->IsLoopPrePass())
  11655. {
  11656. block->globOptData.liveVarSyms->Set(varSym->m_id);
  11657. return instr;
  11658. }
  11659. if (block->globOptData.liveVarSyms->Test(varSym->m_id))
  11660. {
  11661. // Already live, nothing to do
  11662. return instr;
  11663. }
  11664. if (!varSym->IsVar())
  11665. {
  11666. Assert(!varSym->IsTypeSpec());
  11667. // Leave non-vars alone.
  11668. return instr;
  11669. }
  11670. Assert(this->IsTypeSpecialized(varSym, block));
  11671. if (!value)
  11672. {
  11673. value = this->FindValue(block->globOptData.symToValueMap, varSym);
  11674. }
  11675. ValueInfo *valueInfo = value ? value->GetValueInfo() : nullptr;
  11676. if(valueInfo && valueInfo->IsInt())
  11677. {
  11678. // If two syms have the same value, one is lossy-int-specialized, and then the other is int-specialized, the value
  11679. // would have been updated to definitely int. Upon using the lossy-int-specialized sym later, it would be flagged as
  11680. // lossy while the value is definitely int. Since the bit-vectors are based on the sym and not the value, update the
  11681. // lossy state.
  11682. block->globOptData.liveLossyInt32Syms->Clear(varSym->m_id);
  11683. }
  11684. IRType fromType;
  11685. StackSym *typeSpecSym;
  11686. if (block->globOptData.liveInt32Syms->Test(varSym->m_id) && !block->globOptData.liveLossyInt32Syms->Test(varSym->m_id))
  11687. {
  11688. fromType = TyInt32;
  11689. typeSpecSym = varSym->GetInt32EquivSym(this->func);
  11690. Assert(valueInfo);
  11691. Assert(valueInfo->IsInt());
  11692. }
  11693. else if (block->globOptData.liveFloat64Syms->Test(varSym->m_id))
  11694. {
  11695. fromType = TyFloat64;
  11696. typeSpecSym = varSym->GetFloat64EquivSym(this->func);
  11697. // Ensure that all bailout FromVars that generate a value for this type-specialized sym will bail out on any non-number
  11698. // value, even ones that have already been generated before. Float-specialized non-number values cannot be converted
  11699. // back to Var since they will not go back to the original non-number value. The dead-store pass will update the bailout
  11700. // kind on already-generated FromVars based on this bit.
  11701. typeSpecSym->m_requiresBailOnNotNumber = true;
  11702. // A previous float conversion may have used BailOutPrimitiveButString, which does not change the value type to say
  11703. // definitely float, since it can also be a non-string primitive. The convert back to Var though, will cause that
  11704. // bailout kind to be changed to BailOutNumberOnly in the dead-store phase, so from the point of the initial conversion
  11705. // to float, that the value is definitely number. Since we don't know where the FromVar is, change the value type here.
  11706. if(valueInfo)
  11707. {
  11708. if(!valueInfo->IsNumber())
  11709. {
  11710. valueInfo = valueInfo->SpecializeToFloat64(alloc);
  11711. ChangeValueInfo(block, value, valueInfo);
  11712. regOpnd->SetValueType(valueInfo->Type());
  11713. }
  11714. }
  11715. else
  11716. {
  11717. value = NewGenericValue(ValueType::Float);
  11718. valueInfo = value->GetValueInfo();
  11719. SetValue(&block->globOptData, value, varSym);
  11720. regOpnd->SetValueType(valueInfo->Type());
  11721. }
  11722. }
  11723. else
  11724. {
  11725. // SIMD_JS
  11726. Assert(IsLiveAsSimd128(varSym, &block->globOptData));
  11727. if (IsLiveAsSimd128F4(varSym, &block->globOptData))
  11728. {
  11729. fromType = TySimd128F4;
  11730. }
  11731. else
  11732. {
  11733. Assert(IsLiveAsSimd128I4(varSym, &block->globOptData));
  11734. fromType = TySimd128I4;
  11735. }
  11736. if (valueInfo)
  11737. {
  11738. if (fromType == TySimd128F4 && !valueInfo->Type().IsSimd128Float32x4())
  11739. {
  11740. valueInfo = valueInfo->SpecializeToSimd128F4(alloc);
  11741. ChangeValueInfo(block, value, valueInfo);
  11742. regOpnd->SetValueType(valueInfo->Type());
  11743. }
  11744. else if (fromType == TySimd128I4 && !valueInfo->Type().IsSimd128Int32x4())
  11745. {
  11746. if (!valueInfo->Type().IsSimd128Int32x4())
  11747. {
  11748. valueInfo = valueInfo->SpecializeToSimd128I4(alloc);
  11749. ChangeValueInfo(block, value, valueInfo);
  11750. regOpnd->SetValueType(valueInfo->Type());
  11751. }
  11752. }
  11753. }
  11754. else
  11755. {
  11756. ValueType valueType = fromType == TySimd128F4 ? ValueType::GetSimd128(ObjectType::Simd128Float32x4) : ValueType::GetSimd128(ObjectType::Simd128Int32x4);
  11757. value = NewGenericValue(valueType);
  11758. valueInfo = value->GetValueInfo();
  11759. SetValue(&block->globOptData, value, varSym);
  11760. regOpnd->SetValueType(valueInfo->Type());
  11761. }
  11762. ValueType valueType = valueInfo->Type();
  11763. // Should be definite if type-specialized
  11764. Assert(valueType.IsSimd128());
  11765. typeSpecSym = varSym->GetSimd128EquivSym(fromType, this->func);
  11766. }
  11767. Assert(valueInfo);
  11768. int32 intConstantValue;
  11769. if (valueInfo->TryGetIntConstantValue(&intConstantValue))
  11770. {
  11771. // Lower will tag or create a number directly
  11772. newInstr = IR::Instr::New(Js::OpCode::LdC_A_I4, regOpnd,
  11773. IR::IntConstOpnd::New(intConstantValue, TyInt32, instr->m_func), instr->m_func);
  11774. }
  11775. else
  11776. {
  11777. IR::RegOpnd * regNew = IR::RegOpnd::New(typeSpecSym, fromType, instr->m_func);
  11778. Js::OpCode opcode = Js::OpCode::ToVar;
  11779. regNew->SetIsJITOptimizedReg(true);
  11780. newInstr = IR::Instr::New(opcode, regOpnd, regNew, instr->m_func);
  11781. }
  11782. newInstr->SetByteCodeOffset(instr);
  11783. newInstr->GetDst()->AsRegOpnd()->SetIsJITOptimizedReg(true);
  11784. ValueType valueType = valueInfo->Type();
  11785. if(fromType == TyInt32)
  11786. {
  11787. #if !INT32VAR // All 32-bit ints are taggable on 64-bit architectures
  11788. IntConstantBounds constantBounds;
  11789. AssertVerify(valueInfo->TryGetIntConstantBounds(&constantBounds));
  11790. if(constantBounds.IsTaggable())
  11791. #endif
  11792. {
  11793. // The value is within the taggable range, so set the opnd value types to TaggedInt to avoid the overflow check
  11794. valueType = ValueType::GetTaggedInt();
  11795. }
  11796. }
  11797. newInstr->GetDst()->SetValueType(valueType);
  11798. newInstr->GetSrc1()->SetValueType(valueType);
  11799. IR::Instr *insertAfterInstr = instr->m_prev;
  11800. if (instr == block->GetLastInstr() &&
  11801. (instr->IsBranchInstr() || instr->m_opcode == Js::OpCode::BailTarget))
  11802. {
  11803. // Don't insert code between the branch and the preceding ByteCodeUses instrs...
  11804. while(insertAfterInstr->m_opcode == Js::OpCode::ByteCodeUses)
  11805. {
  11806. insertAfterInstr = insertAfterInstr->m_prev;
  11807. }
  11808. }
  11809. block->InsertInstrAfter(newInstr, insertAfterInstr);
  11810. block->globOptData.liveVarSyms->Set(varSym->m_id);
  11811. GOPT_TRACE_OPND(regOpnd, _u("Converting to var\n"));
  11812. if (block->loop)
  11813. {
  11814. Assert(!this->IsLoopPrePass());
  11815. this->TryHoistInvariant(newInstr, block, value, value, nullptr, false);
  11816. }
  11817. if (needsUpdate)
  11818. {
  11819. // Make sure that the kill effect of the ToVar instruction is tracked and that the kill of a property
  11820. // type is reflected in the current instruction.
  11821. this->ProcessKills(newInstr);
  11822. this->ValueNumberObjectType(newInstr->GetDst(), newInstr);
  11823. if (instr->GetSrc1() && instr->GetSrc1()->IsSymOpnd() && instr->GetSrc1()->AsSymOpnd()->IsPropertySymOpnd())
  11824. {
  11825. // Reprocess the load source. We need to reset the PropertySymOpnd fields first.
  11826. IR::PropertySymOpnd *propertySymOpnd = instr->GetSrc1()->AsPropertySymOpnd();
  11827. if (propertySymOpnd->IsTypeCheckSeqCandidate())
  11828. {
  11829. propertySymOpnd->SetTypeChecked(false);
  11830. propertySymOpnd->SetTypeAvailable(false);
  11831. propertySymOpnd->SetWriteGuardChecked(false);
  11832. }
  11833. this->FinishOptPropOp(instr, propertySymOpnd);
  11834. instr = this->SetTypeCheckBailOut(instr->GetSrc1(), instr, nullptr);
  11835. }
  11836. }
  11837. return instr;
  11838. }
  11839. IR::Instr *
  11840. GlobOpt::ToInt32(IR::Instr *instr, IR::Opnd *opnd, BasicBlock *block, Value *val, IR::IndirOpnd *indir, bool lossy)
  11841. {
  11842. return this->ToTypeSpecUse(instr, opnd, block, val, indir, TyInt32, IR::BailOutIntOnly, lossy);
  11843. }
  11844. IR::Instr *
  11845. GlobOpt::ToFloat64(IR::Instr *instr, IR::Opnd *opnd, BasicBlock *block, Value *val, IR::IndirOpnd *indir, IR::BailOutKind bailOutKind)
  11846. {
  11847. return this->ToTypeSpecUse(instr, opnd, block, val, indir, TyFloat64, bailOutKind);
  11848. }
  11849. IR::Instr *
  11850. GlobOpt::ToTypeSpecUse(IR::Instr *instr, IR::Opnd *opnd, BasicBlock *block, Value *val, IR::IndirOpnd *indir, IRType toType, IR::BailOutKind bailOutKind, bool lossy, IR::Instr *insertBeforeInstr)
  11851. {
  11852. Assert(bailOutKind != IR::BailOutInvalid);
  11853. IR::Instr *newInstr;
  11854. if (!val && opnd->IsRegOpnd())
  11855. {
  11856. val = this->FindValue(block->globOptData.symToValueMap, opnd->AsRegOpnd()->m_sym);
  11857. }
  11858. ValueInfo *valueInfo = val ? val->GetValueInfo() : nullptr;
  11859. bool needReplaceSrc = false;
  11860. bool updateBlockLastInstr = false;
  11861. if (instr)
  11862. {
  11863. needReplaceSrc = true;
  11864. if (!insertBeforeInstr)
  11865. {
  11866. insertBeforeInstr = instr;
  11867. }
  11868. }
  11869. else if (!insertBeforeInstr)
  11870. {
  11871. // Insert it at the end of the block
  11872. insertBeforeInstr = block->GetLastInstr();
  11873. if (insertBeforeInstr->IsBranchInstr() || insertBeforeInstr->m_opcode == Js::OpCode::BailTarget)
  11874. {
  11875. // Don't insert code between the branch and the preceding ByteCodeUses instrs...
  11876. while(insertBeforeInstr->m_prev->m_opcode == Js::OpCode::ByteCodeUses)
  11877. {
  11878. insertBeforeInstr = insertBeforeInstr->m_prev;
  11879. }
  11880. }
  11881. else
  11882. {
  11883. insertBeforeInstr = insertBeforeInstr->m_next;
  11884. updateBlockLastInstr = true;
  11885. }
  11886. }
  11887. // Int constant values will be propagated into the instruction. For ArgOut_A_InlineBuiltIn, there's no benefit from
  11888. // const-propping, so those are excluded.
  11889. if (opnd->IsRegOpnd() &&
  11890. !(
  11891. valueInfo &&
  11892. (valueInfo->HasIntConstantValue() || valueInfo->IsFloatConstant()) &&
  11893. (!instr || instr->m_opcode != Js::OpCode::ArgOut_A_InlineBuiltIn)
  11894. ))
  11895. {
  11896. IR::RegOpnd *regSrc = opnd->AsRegOpnd();
  11897. StackSym *varSym = regSrc->m_sym;
  11898. Js::OpCode opcode = Js::OpCode::FromVar;
  11899. if (varSym->IsTypeSpec() || !block->globOptData.liveVarSyms->Test(varSym->m_id))
  11900. {
  11901. // Conversion between int32 and float64
  11902. if (varSym->IsTypeSpec())
  11903. {
  11904. varSym = varSym->GetVarEquivSym(this->func);
  11905. }
  11906. opcode = Js::OpCode::Conv_Prim;
  11907. }
  11908. Assert(block->globOptData.liveVarSyms->Test(varSym->m_id) || this->IsTypeSpecialized(varSym, block));
  11909. StackSym *typeSpecSym;
  11910. BOOL isLive;
  11911. BVSparse<JitArenaAllocator> *livenessBv;
  11912. if(valueInfo && valueInfo->IsInt())
  11913. {
  11914. // If two syms have the same value, one is lossy-int-specialized, and then the other is int-specialized, the value
  11915. // would have been updated to definitely int. Upon using the lossy-int-specialized sym later, it would be flagged as
  11916. // lossy while the value is definitely int. Since the bit-vectors are based on the sym and not the value, update the
  11917. // lossy state.
  11918. block->globOptData.liveLossyInt32Syms->Clear(varSym->m_id);
  11919. }
  11920. if (toType == TyInt32)
  11921. {
  11922. // Need to determine whether the conversion is actually lossy or lossless. If the value is an int, then it's a
  11923. // lossless conversion despite the type of conversion requested. The liveness of the converted int32 sym needs to be
  11924. // set to reflect the actual type of conversion done. Also, a lossless conversion needs the value to determine
  11925. // whether the conversion may need to bail out.
  11926. Assert(valueInfo);
  11927. if(valueInfo->IsInt())
  11928. {
  11929. lossy = false;
  11930. }
  11931. else
  11932. {
  11933. Assert(IsLoopPrePass() || !IsInt32TypeSpecialized(varSym, block));
  11934. }
  11935. livenessBv = block->globOptData.liveInt32Syms;
  11936. isLive = livenessBv->Test(varSym->m_id) && (lossy || !block->globOptData.liveLossyInt32Syms->Test(varSym->m_id));
  11937. if (this->IsLoopPrePass())
  11938. {
  11939. if(!isLive)
  11940. {
  11941. livenessBv->Set(varSym->m_id);
  11942. if(lossy)
  11943. {
  11944. block->globOptData.liveLossyInt32Syms->Set(varSym->m_id);
  11945. }
  11946. else
  11947. {
  11948. block->globOptData.liveLossyInt32Syms->Clear(varSym->m_id);
  11949. }
  11950. }
  11951. if(!lossy)
  11952. {
  11953. Assert(bailOutKind == IR::BailOutIntOnly || bailOutKind == IR::BailOutExpectingInteger);
  11954. valueInfo = valueInfo->SpecializeToInt32(alloc);
  11955. ChangeValueInfo(nullptr, val, valueInfo);
  11956. if(needReplaceSrc)
  11957. {
  11958. opnd->SetValueType(valueInfo->Type());
  11959. }
  11960. }
  11961. return instr;
  11962. }
  11963. typeSpecSym = varSym->GetInt32EquivSym(this->func);
  11964. if (!isLive)
  11965. {
  11966. if (!opnd->IsVar() ||
  11967. !block->globOptData.liveVarSyms->Test(varSym->m_id) ||
  11968. (block->globOptData.liveFloat64Syms->Test(varSym->m_id) && valueInfo && valueInfo->IsLikelyFloat()))
  11969. {
  11970. Assert(block->globOptData.liveFloat64Syms->Test(varSym->m_id));
  11971. if(!lossy && !valueInfo->IsInt())
  11972. {
  11973. // Shouldn't try to do a lossless conversion from float64 to int32 when the value is not known to be an
  11974. // int. There are cases where we need more than two passes over loops to flush out all dependencies.
  11975. // It's possible for the loop prepass to think that a sym s1 remains an int because it acquires the
  11976. // value of another sym s2 that is an int in the prepass at that time. However, s2 can become a float
  11977. // later in the loop body, in which case s1 would become a float on the second iteration of the loop. By
  11978. // that time, we would have already committed to having s1 live as a lossless int on entry into the
  11979. // loop, and we end up having to compensate by doing a lossless conversion from float to int, which will
  11980. // need a bailout and will most likely bail out.
  11981. //
  11982. // If s2 becomes a var instead of a float, then the compensation is legal although not ideal. After
  11983. // enough bailouts, rejit would be triggered with aggressive int type spec turned off. For the
  11984. // float-to-int conversion though, there's no point in emitting a bailout because we already know that
  11985. // the value is a float and has high probability of bailing out (whereas a var has a chance to be a
  11986. // tagged int), and so currently lossless conversion from float to int with bailout is not supported.
  11987. //
  11988. // So, treating this case as a compile-time bailout. The exception will trigger the jit work item to be
  11989. // restarted with aggressive int type specialization disabled.
  11990. if(bailOutKind == IR::BailOutExpectingInteger)
  11991. {
  11992. Assert(IsSwitchOptEnabled());
  11993. throw Js::RejitException(RejitReason::DisableSwitchOptExpectingInteger);
  11994. }
  11995. else
  11996. {
  11997. Assert(DoAggressiveIntTypeSpec());
  11998. if(PHASE_TRACE(Js::BailOutPhase, this->func->GetJnFunction()))
  11999. {
  12000. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  12001. Output::Print(
  12002. _u("BailOut (compile-time): function: %s (%s) varSym: "),
  12003. this->func->GetJnFunction()->GetDisplayName(),
  12004. this->func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  12005. varSym->m_id);
  12006. #if DBG_DUMP
  12007. varSym->Dump();
  12008. #else
  12009. Output::Print(_u("s%u"), varSym->m_id);
  12010. #endif
  12011. if(varSym->HasByteCodeRegSlot())
  12012. {
  12013. Output::Print(_u(" byteCodeReg: R%u"), varSym->GetByteCodeRegSlot());
  12014. }
  12015. Output::Print(_u(" (lossless conversion from float64 to int32)\n"));
  12016. Output::Flush();
  12017. }
  12018. if(!DoAggressiveIntTypeSpec())
  12019. {
  12020. // Aggressive int type specialization is already off for some reason. Prevent trying to rejit again
  12021. // because it won't help and the same thing will happen again. Just abort jitting this function.
  12022. if(PHASE_TRACE(Js::BailOutPhase, this->func->GetJnFunction()))
  12023. {
  12024. Output::Print(_u(" Aborting JIT because AggressiveIntTypeSpec is already off\n"));
  12025. Output::Flush();
  12026. }
  12027. throw Js::OperationAbortedException();
  12028. }
  12029. throw Js::RejitException(RejitReason::AggressiveIntTypeSpecDisabled);
  12030. }
  12031. }
  12032. if(opnd->IsVar())
  12033. {
  12034. regSrc->SetType(TyFloat64);
  12035. regSrc->m_sym = varSym->GetFloat64EquivSym(this->func);
  12036. opcode = Js::OpCode::Conv_Prim;
  12037. }
  12038. else
  12039. {
  12040. Assert(regSrc->IsFloat64());
  12041. Assert(regSrc->m_sym->IsFloat64());
  12042. Assert(opcode == Js::OpCode::Conv_Prim);
  12043. }
  12044. }
  12045. }
  12046. GOPT_TRACE_OPND(regSrc, _u("Converting to int32\n"));
  12047. }
  12048. else if (toType == TyFloat64)
  12049. {
  12050. // float64
  12051. typeSpecSym = varSym->GetFloat64EquivSym(this->func);
  12052. if(!IsLoopPrePass() && typeSpecSym->m_requiresBailOnNotNumber && IsFloat64TypeSpecialized(varSym, block))
  12053. {
  12054. // This conversion is already protected by a BailOutNumberOnly bailout (or at least it will be after the
  12055. // dead-store phase). Since 'requiresBailOnNotNumber' is not flow-based, change the value to definitely float.
  12056. if(valueInfo)
  12057. {
  12058. if(!valueInfo->IsNumber())
  12059. {
  12060. valueInfo = valueInfo->SpecializeToFloat64(alloc);
  12061. ChangeValueInfo(block, val, valueInfo);
  12062. opnd->SetValueType(valueInfo->Type());
  12063. }
  12064. }
  12065. else
  12066. {
  12067. val = NewGenericValue(ValueType::Float);
  12068. valueInfo = val->GetValueInfo();
  12069. SetValue(&block->globOptData, val, varSym);
  12070. opnd->SetValueType(valueInfo->Type());
  12071. }
  12072. }
  12073. if(bailOutKind == IR::BailOutNumberOnly)
  12074. {
  12075. if(!IsLoopPrePass())
  12076. {
  12077. // Ensure that all bailout FromVars that generate a value for this type-specialized sym will bail out on any
  12078. // non-number value, even ones that have already been generated before. The dead-store pass will update the
  12079. // bailout kind on already-generated FromVars based on this bit.
  12080. typeSpecSym->m_requiresBailOnNotNumber = true;
  12081. }
  12082. }
  12083. else if(typeSpecSym->m_requiresBailOnNotNumber)
  12084. {
  12085. Assert(bailOutKind == IR::BailOutPrimitiveButString);
  12086. bailOutKind = IR::BailOutNumberOnly;
  12087. }
  12088. livenessBv = block->globOptData.liveFloat64Syms;
  12089. isLive = livenessBv->Test(varSym->m_id);
  12090. if (this->IsLoopPrePass())
  12091. {
  12092. if(!isLive)
  12093. {
  12094. livenessBv->Set(varSym->m_id);
  12095. }
  12096. if (this->OptIsInvariant(opnd, block, this->prePassLoop, val, false, true))
  12097. {
  12098. this->prePassLoop->forceFloat64SymsOnEntry->Set(varSym->m_id);
  12099. }
  12100. else
  12101. {
  12102. Sym *symStore = (valueInfo ? valueInfo->GetSymStore() : NULL);
  12103. if (symStore && symStore != varSym
  12104. && this->OptIsInvariant(symStore, block, this->prePassLoop, this->FindValue(block->globOptData.symToValueMap, symStore), false, true))
  12105. {
  12106. // If symStore is assigned to sym and we want sym to be type-specialized, for symStore to be specialized
  12107. // outside the loop.
  12108. this->prePassLoop->forceFloat64SymsOnEntry->Set(symStore->m_id);
  12109. }
  12110. }
  12111. if(bailOutKind == IR::BailOutNumberOnly)
  12112. {
  12113. if(valueInfo)
  12114. {
  12115. valueInfo = valueInfo->SpecializeToFloat64(alloc);
  12116. ChangeValueInfo(block, val, valueInfo);
  12117. }
  12118. else
  12119. {
  12120. val = NewGenericValue(ValueType::Float);
  12121. valueInfo = val->GetValueInfo();
  12122. SetValue(&block->globOptData, val, varSym);
  12123. }
  12124. if(needReplaceSrc)
  12125. {
  12126. opnd->SetValueType(valueInfo->Type());
  12127. }
  12128. }
  12129. return instr;
  12130. }
  12131. if (!isLive && regSrc->IsVar())
  12132. {
  12133. if (!block->globOptData.liveVarSyms->Test(varSym->m_id) ||
  12134. (
  12135. block->globOptData.liveInt32Syms->Test(varSym->m_id) &&
  12136. !block->globOptData.liveLossyInt32Syms->Test(varSym->m_id) &&
  12137. valueInfo &&
  12138. valueInfo->IsLikelyInt()
  12139. ))
  12140. {
  12141. Assert(block->globOptData.liveInt32Syms->Test(varSym->m_id));
  12142. Assert(!block->globOptData.liveLossyInt32Syms->Test(varSym->m_id)); // Shouldn't try to convert a lossy int32 to anything
  12143. regSrc->SetType(TyInt32);
  12144. regSrc->m_sym = varSym->GetInt32EquivSym(this->func);
  12145. opcode = Js::OpCode::Conv_Prim;
  12146. }
  12147. }
  12148. GOPT_TRACE_OPND(regSrc, _u("Converting to float64\n"));
  12149. }
  12150. else
  12151. {
  12152. // SIMD_JS
  12153. Assert(IRType_IsSimd128(toType));
  12154. // Get or create type-spec sym
  12155. typeSpecSym = varSym->GetSimd128EquivSym(toType, this->func);
  12156. if (!IsLoopPrePass() && IsSimd128TypeSpecialized(toType, varSym, block))
  12157. {
  12158. // Consider: Is this needed ? Shouldn't this have been done at previous FromVar since the simd128 sym is alive ?
  12159. if (valueInfo)
  12160. {
  12161. if (!valueInfo->IsSimd128(toType))
  12162. {
  12163. valueInfo = valueInfo->SpecializeToSimd128(toType, alloc);
  12164. ChangeValueInfo(block, val, valueInfo);
  12165. opnd->SetValueType(valueInfo->Type());
  12166. }
  12167. }
  12168. else
  12169. {
  12170. val = NewGenericValue(GetValueTypeFromIRType(toType));
  12171. valueInfo = val->GetValueInfo();
  12172. SetValue(&block->globOptData, val, varSym);
  12173. opnd->SetValueType(valueInfo->Type());
  12174. }
  12175. }
  12176. livenessBv = block->globOptData.GetSimd128LivenessBV(toType);
  12177. isLive = livenessBv->Test(varSym->m_id);
  12178. if (this->IsLoopPrePass())
  12179. {
  12180. // FromVar Hoisting
  12181. BVSparse<Memory::JitArenaAllocator> * forceSimd128SymsOnEntry;
  12182. forceSimd128SymsOnEntry = \
  12183. toType == TySimd128F4 ? this->prePassLoop->forceSimd128F4SymsOnEntry : this->prePassLoop->forceSimd128I4SymsOnEntry;
  12184. if (!isLive)
  12185. {
  12186. livenessBv->Set(varSym->m_id);
  12187. }
  12188. // Be aggressive with hoisting only if value is always initialized to SIMD type before entering loop.
  12189. // This reduces the chance that the FromVar gets executed while the specialized instruction in the loop is not. Leading to unnecessary excessive bailouts.
  12190. if (val && !val->GetValueInfo()->HasBeenUndefined() && !val->GetValueInfo()->HasBeenNull() &&
  12191. this->OptIsInvariant(opnd, block, this->prePassLoop, val, false, true))
  12192. {
  12193. forceSimd128SymsOnEntry->Set(varSym->m_id);
  12194. }
  12195. else
  12196. {
  12197. Sym *symStore = (valueInfo ? valueInfo->GetSymStore() : NULL);
  12198. Value * value = symStore ? this->FindValue(block->globOptData.symToValueMap, symStore) : nullptr;
  12199. if (symStore && symStore != varSym
  12200. && value
  12201. && !value->GetValueInfo()->HasBeenUndefined() && !value->GetValueInfo()->HasBeenNull()
  12202. && this->OptIsInvariant(symStore, block, this->prePassLoop, value, true, true))
  12203. {
  12204. // If symStore is assigned to sym and we want sym to be type-specialized, for symStore to be specialized
  12205. // outside the loop.
  12206. forceSimd128SymsOnEntry->Set(symStore->m_id);
  12207. }
  12208. }
  12209. Assert(bailOutKind == IR::BailOutSimd128F4Only || bailOutKind == IR::BailOutSimd128I4Only);
  12210. // We are in loop prepass, we haven't propagated the value info to the src. Do it now.
  12211. if (valueInfo)
  12212. {
  12213. valueInfo = valueInfo->SpecializeToSimd128(toType, alloc);
  12214. ChangeValueInfo(block, val, valueInfo);
  12215. }
  12216. else
  12217. {
  12218. val = NewGenericValue(GetValueTypeFromIRType(toType));
  12219. valueInfo = val->GetValueInfo();
  12220. SetValue(&block->globOptData, val, varSym);
  12221. }
  12222. if (needReplaceSrc)
  12223. {
  12224. opnd->SetValueType(valueInfo->Type());
  12225. }
  12226. return instr;
  12227. }
  12228. GOPT_TRACE_OPND(regSrc, _u("Converting to Simd128\n"));
  12229. }
  12230. bool needLoad = false;
  12231. if (needReplaceSrc)
  12232. {
  12233. bool wasDead = regSrc->GetIsDead();
  12234. // needReplaceSrc means we are type specializing a use, and need to replace the src on the instr
  12235. if (!isLive)
  12236. {
  12237. needLoad = true;
  12238. // ReplaceSrc will delete it.
  12239. regSrc = regSrc->Copy(instr->m_func)->AsRegOpnd();
  12240. }
  12241. IR::RegOpnd * regNew = IR::RegOpnd::New(typeSpecSym, toType, instr->m_func);
  12242. if(valueInfo)
  12243. {
  12244. regNew->SetValueType(valueInfo->Type());
  12245. regNew->m_wasNegativeZeroPreventedByBailout = valueInfo->WasNegativeZeroPreventedByBailout();
  12246. }
  12247. regNew->SetIsDead(wasDead);
  12248. regNew->SetIsJITOptimizedReg(true);
  12249. this->CaptureByteCodeSymUses(instr);
  12250. if (indir == nullptr)
  12251. {
  12252. instr->ReplaceSrc(opnd, regNew);
  12253. }
  12254. else
  12255. {
  12256. indir->ReplaceIndexOpnd(regNew);
  12257. }
  12258. opnd = regNew;
  12259. if (!needLoad)
  12260. {
  12261. Assert(isLive);
  12262. return instr;
  12263. }
  12264. }
  12265. else
  12266. {
  12267. // We just need to insert a load of a type spec sym
  12268. if(isLive)
  12269. {
  12270. return instr;
  12271. }
  12272. // Insert it before the specified instruction
  12273. instr = insertBeforeInstr;
  12274. }
  12275. IR::RegOpnd *regDst = IR::RegOpnd::New(typeSpecSym, toType, instr->m_func);
  12276. bool isBailout = false;
  12277. bool isHoisted = false;
  12278. bool isInLandingPad = (block->next && !block->next->isDeleted && block->next->isLoopHeader);
  12279. if (isInLandingPad)
  12280. {
  12281. Loop *loop = block->next->loop;
  12282. Assert(loop && loop->landingPad == block);
  12283. Assert(loop->bailOutInfo);
  12284. }
  12285. if(toType == TyInt32 && opcode == Js::OpCode::FromVar)
  12286. {
  12287. Assert(valueInfo);
  12288. if(lossy)
  12289. {
  12290. if(!valueInfo->IsPrimitive() && !IsTypeSpecialized(varSym, block))
  12291. {
  12292. // Lossy conversions to int32 on non-primitive values may have implicit calls to toString or valueOf, which
  12293. // may be overridden to have a side effect. The side effect needs to happen every time the conversion is
  12294. // supposed to happen, so the resulting lossy int32 value cannot be reused. Bail out on implicit calls.
  12295. Assert(DoLossyIntTypeSpec());
  12296. bailOutKind = IR::BailOutOnNotPrimitive;
  12297. isBailout = true;
  12298. }
  12299. }
  12300. else if(!valueInfo->IsInt())
  12301. {
  12302. // The operand is likely an int (hence the request to convert to int), so bail out if it's not an int. Only
  12303. // bail out if a lossless conversion to int is requested. Lossy conversions to int such as in (a | 0) don't
  12304. // need to bail out.
  12305. if(bailOutKind == IR::BailOutExpectingInteger)
  12306. {
  12307. Assert(IsSwitchOptEnabled());
  12308. }
  12309. else
  12310. {
  12311. Assert(DoAggressiveIntTypeSpec());
  12312. }
  12313. isBailout = true;
  12314. }
  12315. }
  12316. else if (toType == TyFloat64 && opcode == Js::OpCode::FromVar
  12317. && (!valueInfo || !valueInfo->IsNumber()))
  12318. {
  12319. // Bailout if converting vars to float if we can't prove they are floats:
  12320. // x = str + float; -> need to bailout if str is a string
  12321. //
  12322. // x = obj * 0.1;
  12323. // y = obj * 0.2; -> if obj has valueof, we'll only call valueof once on the FromVar conversion...
  12324. Assert(bailOutKind != IR::BailOutInvalid);
  12325. isBailout = true;
  12326. }
  12327. else if (IRType_IsSimd128(toType)
  12328. && opcode == Js::OpCode::FromVar
  12329. && (!valueInfo || !valueInfo->IsSimd128(toType)))
  12330. {
  12331. Assert(toType == TySimd128F4 && bailOutKind == IR::BailOutSimd128F4Only
  12332. || toType == TySimd128I4 && bailOutKind == IR::BailOutSimd128I4Only);
  12333. isBailout = true;
  12334. }
  12335. if (isBailout)
  12336. {
  12337. if (isInLandingPad)
  12338. {
  12339. Loop *loop = block->next->loop;
  12340. this->EnsureBailTarget(loop);
  12341. instr = loop->bailOutInfo->bailOutInstr;
  12342. updateBlockLastInstr = false;
  12343. newInstr = IR::BailOutInstr::New(opcode, bailOutKind, loop->bailOutInfo, instr->m_func);
  12344. newInstr->SetDst(regDst);
  12345. newInstr->SetSrc1(regSrc);
  12346. }
  12347. else
  12348. {
  12349. newInstr = IR::BailOutInstr::New(opcode, regDst, regSrc, bailOutKind, instr, instr->m_func);
  12350. }
  12351. }
  12352. else
  12353. {
  12354. newInstr = IR::Instr::New(opcode, regDst, regSrc, instr->m_func);
  12355. }
  12356. newInstr->SetByteCodeOffset(instr);
  12357. instr->InsertBefore(newInstr);
  12358. if (updateBlockLastInstr)
  12359. {
  12360. block->SetLastInstr(newInstr);
  12361. }
  12362. regDst->SetIsJITOptimizedReg(true);
  12363. newInstr->GetSrc1()->AsRegOpnd()->SetIsJITOptimizedReg(true);
  12364. ValueInfo *const oldValueInfo = valueInfo;
  12365. if(valueInfo)
  12366. {
  12367. newInstr->GetSrc1()->SetValueType(valueInfo->Type());
  12368. }
  12369. if(isBailout)
  12370. {
  12371. Assert(opcode == Js::OpCode::FromVar);
  12372. if(toType == TyInt32)
  12373. {
  12374. Assert(valueInfo);
  12375. if(!lossy)
  12376. {
  12377. Assert(bailOutKind == IR::BailOutIntOnly || bailOutKind == IR::BailOutExpectingInteger);
  12378. valueInfo = valueInfo->SpecializeToInt32(alloc, isPerformingLoopBackEdgeCompensation);
  12379. ChangeValueInfo(nullptr, val, valueInfo);
  12380. int32 intConstantValue;
  12381. if(indir && needReplaceSrc && valueInfo->TryGetIntConstantValue(&intConstantValue))
  12382. {
  12383. // A likely-int value can have constant bounds due to conditional branches narrowing its range. Now that
  12384. // the sym has been proven to be an int, the likely-int value, after specialization, will be constant.
  12385. // Replace the index opnd in the indir with an offset.
  12386. Assert(opnd == indir->GetIndexOpnd());
  12387. indir->UnlinkIndexOpnd()->Free(instr->m_func);
  12388. opnd = nullptr;
  12389. indir->SetOffset(intConstantValue);
  12390. }
  12391. }
  12392. }
  12393. else if (toType == TyFloat64)
  12394. {
  12395. if(bailOutKind == IR::BailOutNumberOnly)
  12396. {
  12397. if(valueInfo)
  12398. {
  12399. valueInfo = valueInfo->SpecializeToFloat64(alloc);
  12400. ChangeValueInfo(block, val, valueInfo);
  12401. }
  12402. else
  12403. {
  12404. val = NewGenericValue(ValueType::Float);
  12405. valueInfo = val->GetValueInfo();
  12406. SetValue(&block->globOptData, val, varSym);
  12407. }
  12408. }
  12409. }
  12410. else
  12411. {
  12412. Assert(IRType_IsSimd128(toType));
  12413. if (valueInfo)
  12414. {
  12415. valueInfo = valueInfo->SpecializeToSimd128(toType, alloc);
  12416. ChangeValueInfo(block, val, valueInfo);
  12417. }
  12418. else
  12419. {
  12420. val = NewGenericValue(GetValueTypeFromIRType(toType));
  12421. valueInfo = val->GetValueInfo();
  12422. SetValue(&block->globOptData, val, varSym);
  12423. }
  12424. }
  12425. }
  12426. if(valueInfo)
  12427. {
  12428. newInstr->GetDst()->SetValueType(valueInfo->Type());
  12429. if(needReplaceSrc && opnd)
  12430. {
  12431. opnd->SetValueType(valueInfo->Type());
  12432. }
  12433. }
  12434. if (block->loop)
  12435. {
  12436. Assert(!this->IsLoopPrePass());
  12437. isHoisted = this->TryHoistInvariant(newInstr, block, val, val, nullptr, false, lossy);
  12438. }
  12439. if (isBailout)
  12440. {
  12441. if (!isHoisted && !isInLandingPad)
  12442. {
  12443. if(valueInfo)
  12444. {
  12445. // Since this is a pre-op bailout, the old value info should be used for the purposes of bailout. For
  12446. // instance, the value info could be LikelyInt but with a constant range. Once specialized to int, the value
  12447. // info would be an int constant. However, the int constant is only guaranteed if the value is actually an
  12448. // int, which this conversion is verifying, so bailout cannot assume the constant value.
  12449. if(oldValueInfo)
  12450. {
  12451. val->SetValueInfo(oldValueInfo);
  12452. }
  12453. else
  12454. {
  12455. block->globOptData.symToValueMap->Clear(varSym->m_id);
  12456. }
  12457. }
  12458. // Fill in bail out info if the FromVar is a bailout instr, and it wasn't hoisted as invariant.
  12459. // If it was hoisted, the invariant code will fill out the bailout info with the loop landing pad bailout info.
  12460. this->FillBailOutInfo(block, newInstr->GetBailOutInfo());
  12461. if(valueInfo)
  12462. {
  12463. // Restore the new value info after filling the bailout info
  12464. if(oldValueInfo)
  12465. {
  12466. val->SetValueInfo(valueInfo);
  12467. }
  12468. else
  12469. {
  12470. SetValue(&block->globOptData, val, varSym);
  12471. }
  12472. }
  12473. }
  12474. }
  12475. // Now that we've captured the liveness in the bailout info, we can mark this as live.
  12476. // This type specialized sym isn't live if the FromVar bails out.
  12477. livenessBv->Set(varSym->m_id);
  12478. if(toType == TyInt32)
  12479. {
  12480. if(lossy)
  12481. {
  12482. block->globOptData.liveLossyInt32Syms->Set(varSym->m_id);
  12483. }
  12484. else
  12485. {
  12486. block->globOptData.liveLossyInt32Syms->Clear(varSym->m_id);
  12487. }
  12488. }
  12489. }
  12490. else
  12491. {
  12492. Assert(valueInfo);
  12493. if(opnd->IsRegOpnd() && valueInfo->IsInt())
  12494. {
  12495. // If two syms have the same value, one is lossy-int-specialized, and then the other is int-specialized, the value
  12496. // would have been updated to definitely int. Upon using the lossy-int-specialized sym later, it would be flagged as
  12497. // lossy while the value is definitely int. Since the bit-vectors are based on the sym and not the value, update the
  12498. // lossy state.
  12499. block->globOptData.liveLossyInt32Syms->Clear(opnd->AsRegOpnd()->m_sym->m_id);
  12500. if(toType == TyInt32)
  12501. {
  12502. lossy = false;
  12503. }
  12504. }
  12505. if (this->IsLoopPrePass())
  12506. {
  12507. if(opnd->IsRegOpnd())
  12508. {
  12509. StackSym *const sym = opnd->AsRegOpnd()->m_sym;
  12510. if(toType == TyInt32)
  12511. {
  12512. Assert(!sym->IsTypeSpec());
  12513. block->globOptData.liveInt32Syms->Set(sym->m_id);
  12514. if(lossy)
  12515. {
  12516. block->globOptData.liveLossyInt32Syms->Set(sym->m_id);
  12517. }
  12518. else
  12519. {
  12520. block->globOptData.liveLossyInt32Syms->Clear(sym->m_id);
  12521. }
  12522. }
  12523. else
  12524. {
  12525. Assert(toType == TyFloat64);
  12526. AnalysisAssert(instr);
  12527. StackSym *const varSym = sym->IsTypeSpec() ? sym->GetVarEquivSym(instr->m_func) : sym;
  12528. block->globOptData.liveFloat64Syms->Set(varSym->m_id);
  12529. }
  12530. }
  12531. return instr;
  12532. }
  12533. if (!needReplaceSrc)
  12534. {
  12535. instr = insertBeforeInstr;
  12536. }
  12537. IR::Opnd *constOpnd;
  12538. int32 intConstantValue;
  12539. if(valueInfo->TryGetIntConstantValue(&intConstantValue))
  12540. {
  12541. if(toType == TyInt32)
  12542. {
  12543. constOpnd = IR::IntConstOpnd::New(intConstantValue, TyInt32, instr->m_func);
  12544. }
  12545. else
  12546. {
  12547. Assert(toType == TyFloat64);
  12548. constOpnd = IR::FloatConstOpnd::New(static_cast<FloatConstType>(intConstantValue), TyFloat64, instr->m_func);
  12549. }
  12550. }
  12551. else if(valueInfo->IsFloatConstant())
  12552. {
  12553. const FloatConstType floatValue = valueInfo->AsFloatConstant()->FloatValue();
  12554. if(toType == TyInt32)
  12555. {
  12556. Assert(lossy);
  12557. constOpnd =
  12558. IR::IntConstOpnd::New(
  12559. Js::JavascriptMath::ToInt32(floatValue),
  12560. TyInt32,
  12561. instr->m_func);
  12562. }
  12563. else
  12564. {
  12565. Assert(toType == TyFloat64);
  12566. constOpnd = IR::FloatConstOpnd::New(floatValue, TyFloat64, instr->m_func);
  12567. }
  12568. }
  12569. else
  12570. {
  12571. Assert(opnd->IsVar());
  12572. Assert(opnd->IsAddrOpnd());
  12573. AssertMsg(opnd->AsAddrOpnd()->IsVar(), "We only expect to see addr that are var before lower.");
  12574. // Don't need to capture uses, we are only replacing an addr opnd
  12575. if(toType == TyInt32)
  12576. {
  12577. constOpnd = IR::IntConstOpnd::New(Js::TaggedInt::ToInt32(opnd->AsAddrOpnd()->m_address), TyInt32, instr->m_func);
  12578. }
  12579. else
  12580. {
  12581. Assert(toType == TyFloat64);
  12582. constOpnd = IR::FloatConstOpnd::New(Js::TaggedInt::ToDouble(opnd->AsAddrOpnd()->m_address), TyFloat64, instr->m_func);
  12583. }
  12584. }
  12585. if (toType == TyInt32)
  12586. {
  12587. if (needReplaceSrc)
  12588. {
  12589. CaptureByteCodeSymUses(instr);
  12590. if(indir)
  12591. {
  12592. Assert(opnd == indir->GetIndexOpnd());
  12593. indir->UnlinkIndexOpnd()->Free(instr->m_func);
  12594. indir->SetOffset(constOpnd->AsIntConstOpnd()->AsInt32());
  12595. }
  12596. else
  12597. {
  12598. instr->ReplaceSrc(opnd, constOpnd);
  12599. }
  12600. }
  12601. else
  12602. {
  12603. StackSym *varSym = opnd->AsRegOpnd()->m_sym;
  12604. if(varSym->IsTypeSpec())
  12605. {
  12606. varSym = varSym->GetVarEquivSym(nullptr);
  12607. Assert(varSym);
  12608. }
  12609. if(block->globOptData.liveInt32Syms->TestAndSet(varSym->m_id))
  12610. {
  12611. Assert(!!block->globOptData.liveLossyInt32Syms->Test(varSym->m_id) == lossy);
  12612. }
  12613. else
  12614. {
  12615. if(lossy)
  12616. {
  12617. block->globOptData.liveLossyInt32Syms->Set(varSym->m_id);
  12618. }
  12619. StackSym *int32Sym = varSym->GetInt32EquivSym(instr->m_func);
  12620. IR::RegOpnd *int32Reg = IR::RegOpnd::New(int32Sym, TyInt32, instr->m_func);
  12621. int32Reg->SetIsJITOptimizedReg(true);
  12622. newInstr = IR::Instr::New(Js::OpCode::Ld_I4, int32Reg, constOpnd, instr->m_func);
  12623. newInstr->SetByteCodeOffset(instr);
  12624. instr->InsertBefore(newInstr);
  12625. if (updateBlockLastInstr)
  12626. {
  12627. block->SetLastInstr(newInstr);
  12628. }
  12629. }
  12630. }
  12631. }
  12632. else
  12633. {
  12634. StackSym *floatSym;
  12635. bool newFloatSym = false;
  12636. StackSym* varSym;
  12637. if (opnd->IsRegOpnd())
  12638. {
  12639. varSym = opnd->AsRegOpnd()->m_sym;
  12640. if (varSym->IsTypeSpec())
  12641. {
  12642. varSym = varSym->GetVarEquivSym(nullptr);
  12643. Assert(varSym);
  12644. }
  12645. floatSym = varSym->GetFloat64EquivSym(instr->m_func);
  12646. }
  12647. else
  12648. {
  12649. varSym = GetCopyPropSym(block, nullptr, val);
  12650. // If there is no float 64 type specialized sym for this - create a new sym.
  12651. if(!varSym || !IsFloat64TypeSpecialized(varSym, block))
  12652. {
  12653. // Clear the symstore to ensure it's set below to this new symbol
  12654. val->GetValueInfo()->SetSymStore(nullptr);
  12655. varSym = StackSym::New(TyVar, instr->m_func);
  12656. newFloatSym = true;
  12657. }
  12658. floatSym = varSym->GetFloat64EquivSym(instr->m_func);
  12659. }
  12660. IR::RegOpnd *floatReg = IR::RegOpnd::New(floatSym, TyFloat64, instr->m_func);
  12661. floatReg->SetIsJITOptimizedReg(true);
  12662. // If the value is not live - let's load it.
  12663. if(!block->globOptData.liveFloat64Syms->TestAndSet(varSym->m_id))
  12664. {
  12665. newInstr = IR::Instr::New(Js::OpCode::LdC_F8_R8, floatReg, constOpnd, instr->m_func);
  12666. newInstr->SetByteCodeOffset(instr);
  12667. instr->InsertBefore(newInstr);
  12668. if (updateBlockLastInstr)
  12669. {
  12670. block->SetLastInstr(newInstr);
  12671. }
  12672. if(newFloatSym)
  12673. {
  12674. this->SetValue(&block->globOptData, val, varSym);
  12675. }
  12676. // Src is always invariant, but check if the dst is, and then hoist.
  12677. if (block->loop &&
  12678. (
  12679. newFloatSym && block->loop->CanHoistInvariants() ||
  12680. this->OptIsInvariant(floatReg, block, block->loop, val, false, false)
  12681. ))
  12682. {
  12683. Assert(!this->IsLoopPrePass());
  12684. this->OptHoistInvariant(newInstr, block, block->loop, val, val, false);
  12685. }
  12686. }
  12687. if (needReplaceSrc)
  12688. {
  12689. CaptureByteCodeSymUses(instr);
  12690. instr->ReplaceSrc(opnd, floatReg);
  12691. }
  12692. }
  12693. return instr;
  12694. }
  12695. return newInstr;
  12696. }
  12697. void
  12698. GlobOpt::ToVarRegOpnd(IR::RegOpnd *dst, BasicBlock *block)
  12699. {
  12700. ToVarStackSym(dst->m_sym, block);
  12701. }
  12702. void
  12703. GlobOpt::ToVarStackSym(StackSym *varSym, BasicBlock *block)
  12704. {
  12705. //added another check for sym , in case of asmjs there is mostly no var syms and hence added a new check to see if it is the primary sym
  12706. Assert(!varSym->IsTypeSpec());
  12707. block->globOptData.liveVarSyms->Set(varSym->m_id);
  12708. block->globOptData.liveInt32Syms->Clear(varSym->m_id);
  12709. block->globOptData.liveLossyInt32Syms->Clear(varSym->m_id);
  12710. block->globOptData.liveFloat64Syms->Clear(varSym->m_id);
  12711. // SIMD_JS
  12712. block->globOptData.liveSimd128F4Syms->Clear(varSym->m_id);
  12713. block->globOptData.liveSimd128I4Syms->Clear(varSym->m_id);
  12714. }
  12715. void
  12716. GlobOpt::ToInt32Dst(IR::Instr *instr, IR::RegOpnd *dst, BasicBlock *block)
  12717. {
  12718. StackSym *varSym = dst->m_sym;
  12719. Assert(!varSym->IsTypeSpec());
  12720. if (!this->IsLoopPrePass() && varSym->IsVar())
  12721. {
  12722. StackSym *int32Sym = varSym->GetInt32EquivSym(instr->m_func);
  12723. // Use UnlinkDst / SetDst to make sure isSingleDef is tracked properly,
  12724. // since we'll just be hammering the symbol.
  12725. dst = instr->UnlinkDst()->AsRegOpnd();
  12726. dst->m_sym = int32Sym;
  12727. dst->SetType(TyInt32);
  12728. instr->SetDst(dst);
  12729. }
  12730. block->globOptData.liveInt32Syms->Set(varSym->m_id);
  12731. block->globOptData.liveLossyInt32Syms->Clear(varSym->m_id); // The store makes it lossless
  12732. block->globOptData.liveVarSyms->Clear(varSym->m_id);
  12733. block->globOptData.liveFloat64Syms->Clear(varSym->m_id);
  12734. // SIMD_JS
  12735. block->globOptData.liveSimd128F4Syms->Clear(varSym->m_id);
  12736. block->globOptData.liveSimd128I4Syms->Clear(varSym->m_id);
  12737. }
  12738. void
  12739. GlobOpt::ToUInt32Dst(IR::Instr *instr, IR::RegOpnd *dst, BasicBlock *block)
  12740. {
  12741. // We should be calling only for asmjs function
  12742. Assert(GetIsAsmJSFunc());
  12743. StackSym *varSym = dst->m_sym;
  12744. Assert(!varSym->IsTypeSpec());
  12745. block->globOptData.liveInt32Syms->Set(varSym->m_id);
  12746. block->globOptData.liveLossyInt32Syms->Clear(varSym->m_id); // The store makes it lossless
  12747. block->globOptData.liveVarSyms->Clear(varSym->m_id);
  12748. block->globOptData.liveFloat64Syms->Clear(varSym->m_id);
  12749. // SIMD_JS
  12750. block->globOptData.liveSimd128F4Syms->Clear(varSym->m_id);
  12751. block->globOptData.liveSimd128I4Syms->Clear(varSym->m_id);
  12752. }
  12753. void
  12754. GlobOpt::ToFloat64Dst(IR::Instr *instr, IR::RegOpnd *dst, BasicBlock *block)
  12755. {
  12756. StackSym *varSym = dst->m_sym;
  12757. Assert(!varSym->IsTypeSpec());
  12758. if (!this->IsLoopPrePass() && varSym->IsVar())
  12759. {
  12760. StackSym *float64Sym = varSym->GetFloat64EquivSym(this->func);
  12761. // Use UnlinkDst / SetDst to make sure isSingleDef is tracked properly,
  12762. // since we'll just be hammering the symbol.
  12763. dst = instr->UnlinkDst()->AsRegOpnd();
  12764. dst->m_sym = float64Sym;
  12765. dst->SetType(TyFloat64);
  12766. instr->SetDst(dst);
  12767. }
  12768. block->globOptData.liveFloat64Syms->Set(varSym->m_id);
  12769. block->globOptData.liveVarSyms->Clear(varSym->m_id);
  12770. block->globOptData.liveInt32Syms->Clear(varSym->m_id);
  12771. block->globOptData.liveLossyInt32Syms->Clear(varSym->m_id);
  12772. // SIMD_JS
  12773. block->globOptData.liveSimd128F4Syms->Clear(varSym->m_id);
  12774. block->globOptData.liveSimd128I4Syms->Clear(varSym->m_id);
  12775. }
  12776. // SIMD_JS
  12777. void
  12778. GlobOpt::ToSimd128Dst(IRType toType, IR::Instr *instr, IR::RegOpnd *dst, BasicBlock *block)
  12779. {
  12780. StackSym *varSym = dst->m_sym;
  12781. Assert(!varSym->IsTypeSpec());
  12782. BVSparse<JitArenaAllocator> * livenessBV = block->globOptData.GetSimd128LivenessBV(toType);
  12783. Assert(livenessBV);
  12784. if (!this->IsLoopPrePass() && varSym->IsVar())
  12785. {
  12786. StackSym *simd128Sym = varSym->GetSimd128EquivSym(toType, this->func);
  12787. // Use UnlinkDst / SetDst to make sure isSingleDef is tracked properly,
  12788. // since we'll just be hammering the symbol.
  12789. dst = instr->UnlinkDst()->AsRegOpnd();
  12790. dst->m_sym = simd128Sym;
  12791. dst->SetType(toType);
  12792. instr->SetDst(dst);
  12793. }
  12794. block->globOptData.liveFloat64Syms->Clear(varSym->m_id);
  12795. block->globOptData.liveVarSyms->Clear(varSym->m_id);
  12796. block->globOptData.liveInt32Syms->Clear(varSym->m_id);
  12797. block->globOptData.liveLossyInt32Syms->Clear(varSym->m_id);
  12798. // SIMD_JS
  12799. block->globOptData.liveSimd128F4Syms->Clear(varSym->m_id);
  12800. block->globOptData.liveSimd128I4Syms->Clear(varSym->m_id);
  12801. livenessBV->Set(varSym->m_id);
  12802. }
  12803. BOOL
  12804. GlobOpt::IsInt32TypeSpecialized(Sym *sym, BasicBlock *block)
  12805. {
  12806. return IsInt32TypeSpecialized(sym, &block->globOptData);
  12807. }
  12808. BOOL
  12809. GlobOpt::IsSwitchInt32TypeSpecialized(IR::Instr * instr, BasicBlock * block)
  12810. {
  12811. return IsSwitchOptEnabled(instr->m_func->GetTopFunc()) && instr->GetSrc1()->IsRegOpnd() &&
  12812. IsInt32TypeSpecialized(instr->GetSrc1()->AsRegOpnd()->m_sym, block);
  12813. }
  12814. BOOL
  12815. GlobOpt::IsInt32TypeSpecialized(Sym *sym, GlobOptBlockData *data)
  12816. {
  12817. sym = StackSym::GetVarEquivStackSym_NoCreate(sym);
  12818. return sym && data->liveInt32Syms->Test(sym->m_id) && !data->liveLossyInt32Syms->Test(sym->m_id);
  12819. }
  12820. BOOL
  12821. GlobOpt::IsFloat64TypeSpecialized(Sym *sym, BasicBlock *block)
  12822. {
  12823. return IsFloat64TypeSpecialized(sym, &block->globOptData);
  12824. }
  12825. BOOL
  12826. GlobOpt::IsFloat64TypeSpecialized(Sym *sym, GlobOptBlockData *data)
  12827. {
  12828. sym = StackSym::GetVarEquivStackSym_NoCreate(sym);
  12829. return sym && data->liveFloat64Syms->Test(sym->m_id);
  12830. }
  12831. // SIMD_JS
  12832. BOOL
  12833. GlobOpt::IsSimd128TypeSpecialized(Sym *sym, BasicBlock *block)
  12834. {
  12835. return IsSimd128TypeSpecialized(sym, &block->globOptData);
  12836. }
  12837. BOOL
  12838. GlobOpt::IsSimd128TypeSpecialized(Sym *sym, GlobOptBlockData *data)
  12839. {
  12840. sym = StackSym::GetVarEquivStackSym_NoCreate(sym);
  12841. return sym && (data->liveSimd128F4Syms->Test(sym->m_id) || data->liveSimd128I4Syms->Test(sym->m_id));
  12842. }
  12843. BOOL
  12844. GlobOpt::IsSimd128TypeSpecialized(IRType type, Sym *sym, BasicBlock *block)
  12845. {
  12846. return IsSimd128TypeSpecialized(type, sym, &block->globOptData);
  12847. }
  12848. BOOL
  12849. GlobOpt::IsSimd128TypeSpecialized(IRType type, Sym *sym, GlobOptBlockData *data)
  12850. {
  12851. switch (type)
  12852. {
  12853. case TySimd128F4:
  12854. return IsSimd128F4TypeSpecialized(sym, data);
  12855. case TySimd128I4:
  12856. return IsSimd128I4TypeSpecialized(sym, data);
  12857. default:
  12858. Assert(UNREACHED);
  12859. return false;
  12860. }
  12861. }
  12862. BOOL
  12863. GlobOpt::IsSimd128F4TypeSpecialized(Sym *sym, BasicBlock *block)
  12864. {
  12865. return IsSimd128F4TypeSpecialized(sym, &block->globOptData);
  12866. }
  12867. BOOL
  12868. GlobOpt::IsSimd128F4TypeSpecialized(Sym *sym, GlobOptBlockData *data)
  12869. {
  12870. sym = StackSym::GetVarEquivStackSym_NoCreate(sym);
  12871. return sym && (data->liveSimd128F4Syms->Test(sym->m_id));
  12872. }
  12873. BOOL
  12874. GlobOpt::IsSimd128I4TypeSpecialized(Sym *sym, BasicBlock *block)
  12875. {
  12876. return IsSimd128I4TypeSpecialized(sym, &block->globOptData);
  12877. }
  12878. BOOL
  12879. GlobOpt::IsSimd128I4TypeSpecialized(Sym *sym, GlobOptBlockData *data)
  12880. {
  12881. sym = StackSym::GetVarEquivStackSym_NoCreate(sym);
  12882. return sym && (data->liveSimd128I4Syms->Test(sym->m_id));
  12883. }
  12884. BOOL
  12885. GlobOpt::IsLiveAsSimd128(Sym *sym, GlobOptBlockData *data)
  12886. {
  12887. sym = StackSym::GetVarEquivStackSym_NoCreate(sym);
  12888. return
  12889. sym &&
  12890. (
  12891. data->liveSimd128F4Syms->Test(sym->m_id) ||
  12892. data->liveSimd128I4Syms->Test(sym->m_id)
  12893. );
  12894. }
  12895. BOOL
  12896. GlobOpt::IsLiveAsSimd128F4(Sym *sym, GlobOptBlockData *data)
  12897. {
  12898. sym = StackSym::GetVarEquivStackSym_NoCreate(sym);
  12899. return sym && data->liveSimd128F4Syms->Test(sym->m_id);
  12900. }
  12901. BOOL
  12902. GlobOpt::IsLiveAsSimd128I4(Sym *sym, GlobOptBlockData *data)
  12903. {
  12904. sym = StackSym::GetVarEquivStackSym_NoCreate(sym);
  12905. return sym && data->liveSimd128I4Syms->Test(sym->m_id);
  12906. }
  12907. BOOL
  12908. GlobOpt::IsTypeSpecialized(Sym *sym, BasicBlock *block)
  12909. {
  12910. return IsTypeSpecialized(sym, &block->globOptData);
  12911. }
  12912. BOOL
  12913. GlobOpt::IsTypeSpecialized(Sym *sym, GlobOptBlockData *data)
  12914. {
  12915. return IsInt32TypeSpecialized(sym, data) || IsFloat64TypeSpecialized(sym, data) || IsSimd128TypeSpecialized(sym, data);
  12916. }
  12917. BOOL
  12918. GlobOpt::IsLive(Sym *sym, BasicBlock *block)
  12919. {
  12920. return IsLive(sym, &block->globOptData);
  12921. }
  12922. BOOL
  12923. GlobOpt::IsLive(Sym *sym, GlobOptBlockData *data)
  12924. {
  12925. sym = StackSym::GetVarEquivStackSym_NoCreate(sym);
  12926. return
  12927. sym &&
  12928. (
  12929. data->liveVarSyms->Test(sym->m_id) ||
  12930. data->liveInt32Syms->Test(sym->m_id) ||
  12931. data->liveFloat64Syms->Test(sym->m_id) ||
  12932. data->liveSimd128F4Syms->Test(sym->m_id) ||
  12933. data->liveSimd128I4Syms->Test(sym->m_id)
  12934. );
  12935. }
  12936. void
  12937. GlobOpt::MakeLive(StackSym *const sym, GlobOptBlockData *const blockData, const bool lossy) const
  12938. {
  12939. Assert(sym);
  12940. Assert(blockData);
  12941. if(sym->IsTypeSpec())
  12942. {
  12943. const SymID varSymId = sym->GetVarEquivSym(func)->m_id;
  12944. if(sym->IsInt32())
  12945. {
  12946. blockData->liveInt32Syms->Set(varSymId);
  12947. if(lossy)
  12948. {
  12949. blockData->liveLossyInt32Syms->Set(varSymId);
  12950. }
  12951. else
  12952. {
  12953. blockData->liveLossyInt32Syms->Clear(varSymId);
  12954. }
  12955. return;
  12956. }
  12957. if (sym->IsFloat64())
  12958. {
  12959. blockData->liveFloat64Syms->Set(varSymId);
  12960. return;
  12961. }
  12962. // SIMD_JS
  12963. if (sym->IsSimd128F4())
  12964. {
  12965. blockData->liveSimd128F4Syms->Set(varSymId);
  12966. return;
  12967. }
  12968. if (sym->IsSimd128I4())
  12969. {
  12970. blockData->liveSimd128I4Syms->Set(varSymId);
  12971. return;
  12972. }
  12973. }
  12974. blockData->liveVarSyms->Set(sym->m_id);
  12975. }
  12976. bool
  12977. GlobOpt::OptConstFoldBinary(
  12978. IR::Instr * *pInstr,
  12979. const IntConstantBounds &src1IntConstantBounds,
  12980. const IntConstantBounds &src2IntConstantBounds,
  12981. Value **pDstVal)
  12982. {
  12983. IR::Instr * &instr = *pInstr;
  12984. int32 value;
  12985. IR::IntConstOpnd *constOpnd;
  12986. if (!DoConstFold())
  12987. {
  12988. return false;
  12989. }
  12990. int32 src1IntConstantValue = -1;
  12991. int32 src2IntConstantValue = -1;
  12992. int32 src1MaxIntConstantValue = -1;
  12993. int32 src2MaxIntConstantValue = -1;
  12994. int32 src1MinIntConstantValue = -1;
  12995. int32 src2MinIntConstantValue = -1;
  12996. if (instr->IsBranchInstr())
  12997. {
  12998. src1MinIntConstantValue = src1IntConstantBounds.LowerBound();
  12999. src1MaxIntConstantValue = src1IntConstantBounds.UpperBound();
  13000. src2MinIntConstantValue = src2IntConstantBounds.LowerBound();
  13001. src2MaxIntConstantValue = src2IntConstantBounds.UpperBound();
  13002. }
  13003. else if (src1IntConstantBounds.IsConstant() && src2IntConstantBounds.IsConstant())
  13004. {
  13005. src1IntConstantValue = src1IntConstantBounds.LowerBound();
  13006. src2IntConstantValue = src2IntConstantBounds.LowerBound();
  13007. }
  13008. else
  13009. {
  13010. return false;
  13011. }
  13012. IntConstType tmpValueOut;
  13013. if (!instr->BinaryCalculator(src1IntConstantValue, src2IntConstantValue, &tmpValueOut)
  13014. || !Math::FitsInDWord(tmpValueOut))
  13015. {
  13016. return false;
  13017. }
  13018. value = (int32)tmpValueOut;
  13019. this->CaptureByteCodeSymUses(instr);
  13020. constOpnd = IR::IntConstOpnd::New(value, TyInt32, instr->m_func);
  13021. instr->ReplaceSrc1(constOpnd);
  13022. instr->FreeSrc2();
  13023. this->OptSrc(constOpnd, &instr);
  13024. IR::Opnd *dst = instr->GetDst();
  13025. Assert(dst->IsRegOpnd());
  13026. StackSym *dstSym = dst->AsRegOpnd()->m_sym;
  13027. if (dstSym->IsSingleDef())
  13028. {
  13029. dstSym->SetIsIntConst(value);
  13030. }
  13031. GOPT_TRACE_INSTR(instr, _u("Constant folding to %d: \n"), value);
  13032. *pDstVal = GetIntConstantValue(value, instr, dst);
  13033. if (IsTypeSpecPhaseOff(this->func))
  13034. {
  13035. instr->m_opcode = Js::OpCode::LdC_A_I4;
  13036. this->ToVarRegOpnd(dst->AsRegOpnd(), this->currentBlock);
  13037. }
  13038. else
  13039. {
  13040. instr->m_opcode = Js::OpCode::Ld_I4;
  13041. this->ToInt32Dst(instr, dst->AsRegOpnd(), this->currentBlock);
  13042. }
  13043. return true;
  13044. }
  13045. void
  13046. GlobOpt::OptConstFoldBr(bool test, IR::Instr *instr, Value * src1Val, Value * src2Val)
  13047. {
  13048. GOPT_TRACE_INSTR(instr, _u("Constant folding to branch: "));
  13049. BasicBlock *deadBlock;
  13050. if (src1Val)
  13051. {
  13052. this->ToInt32(instr, instr->GetSrc1(), this->currentBlock, src1Val, nullptr, false);
  13053. }
  13054. if (src2Val)
  13055. {
  13056. this->ToInt32(instr, instr->GetSrc2(), this->currentBlock, src2Val, nullptr, false);
  13057. }
  13058. this->CaptureByteCodeSymUses(instr);
  13059. if (test)
  13060. {
  13061. instr->m_opcode = Js::OpCode::Br;
  13062. instr->FreeSrc1();
  13063. if(instr->GetSrc2())
  13064. {
  13065. instr->FreeSrc2();
  13066. }
  13067. deadBlock = instr->m_next->AsLabelInstr()->GetBasicBlock();
  13068. }
  13069. else
  13070. {
  13071. AssertMsg(instr->m_next->IsLabelInstr(), "Next instr of branch should be a label...");
  13072. if(instr->AsBranchInstr()->IsMultiBranch())
  13073. {
  13074. return;
  13075. }
  13076. deadBlock = instr->AsBranchInstr()->GetTarget()->GetBasicBlock();
  13077. instr->FreeSrc1();
  13078. if(instr->GetSrc2())
  13079. {
  13080. instr->FreeSrc2();
  13081. }
  13082. instr->m_opcode = Js::OpCode::Nop;
  13083. }
  13084. // Loop back edge: we would have already decremented data use count for the tail block when we processed the loop header.
  13085. if (!(this->currentBlock->loop && this->currentBlock->loop->GetHeadBlock() == deadBlock))
  13086. {
  13087. this->currentBlock->DecrementDataUseCount();
  13088. }
  13089. this->currentBlock->RemoveDeadSucc(deadBlock, this->func->m_fg);
  13090. if (deadBlock->GetPredList()->Count() == 0)
  13091. {
  13092. deadBlock->SetDataUseCount(0);
  13093. }
  13094. }
  13095. void
  13096. GlobOpt::ChangeValueType(
  13097. BasicBlock *const block,
  13098. Value *const value,
  13099. const ValueType newValueType,
  13100. const bool preserveSubclassInfo,
  13101. const bool allowIncompatibleType) const
  13102. {
  13103. Assert(value);
  13104. // Why are we trying to change the value type of the type sym value? Asserting here to make sure we don't deep copy the type sym's value info.
  13105. Assert(!value->GetValueInfo()->IsJsType());
  13106. ValueInfo *const valueInfo = value->GetValueInfo();
  13107. const ValueType valueType(valueInfo->Type());
  13108. if(valueType == newValueType && (preserveSubclassInfo || valueInfo->IsGeneric()))
  13109. {
  13110. return;
  13111. }
  13112. // ArrayValueInfo has information specific to the array type, so make sure that doesn't change
  13113. Assert(
  13114. !preserveSubclassInfo ||
  13115. !valueInfo->IsArrayValueInfo() ||
  13116. newValueType.IsObject() && newValueType.GetObjectType() == valueInfo->GetObjectType());
  13117. ValueInfo *const newValueInfo =
  13118. preserveSubclassInfo
  13119. ? valueInfo->Copy(alloc)
  13120. : valueInfo->CopyWithGenericStructureKind(alloc);
  13121. newValueInfo->Type() = newValueType;
  13122. ChangeValueInfo(block, value, newValueInfo, allowIncompatibleType);
  13123. }
  13124. void
  13125. GlobOpt::ChangeValueInfo(BasicBlock *const block, Value *const value, ValueInfo *const newValueInfo, const bool allowIncompatibleType, const bool compensated) const
  13126. {
  13127. Assert(value);
  13128. Assert(newValueInfo);
  13129. // The value type must be changed to something more specific or something more generic. For instance, it would be changed to
  13130. // something more specific if the current value type is LikelyArray and checks have been done to ensure that it's an array,
  13131. // and it would be changed to something more generic if a call kills the Array value type and it must be treated as
  13132. // LikelyArray going forward.
  13133. // There are cases where we change the type because of different profile information, and because of rejit, these profile information
  13134. // may conflict. Need to allow incompatible type in those cause. However, the old type should be indefinite.
  13135. Assert((allowIncompatibleType && !value->GetValueInfo()->IsDefinite()) ||
  13136. AreValueInfosCompatible(newValueInfo, value->GetValueInfo()));
  13137. // ArrayValueInfo has information specific to the array type, so make sure that doesn't change
  13138. Assert(
  13139. !value->GetValueInfo()->IsArrayValueInfo() ||
  13140. !newValueInfo->IsArrayValueInfo() ||
  13141. newValueInfo->GetObjectType() == value->GetValueInfo()->GetObjectType());
  13142. if(block)
  13143. {
  13144. TrackValueInfoChangeForKills(block, value, newValueInfo, compensated);
  13145. }
  13146. value->SetValueInfo(newValueInfo);
  13147. }
  13148. bool
  13149. GlobOpt::AreValueInfosCompatible(const ValueInfo *const v0, const ValueInfo *const v1) const
  13150. {
  13151. Assert(v0);
  13152. Assert(v1);
  13153. if(v0->IsUninitialized() || v1->IsUninitialized())
  13154. {
  13155. return true;
  13156. }
  13157. const bool doAggressiveIntTypeSpec = DoAggressiveIntTypeSpec();
  13158. if(doAggressiveIntTypeSpec && (v0->IsInt() || v1->IsInt()))
  13159. {
  13160. // Int specialization in some uncommon loop cases involving dependencies, needs to allow specializing values of
  13161. // arbitrary types, even values that are definitely not int, to compensate for aggressive assumptions made by a loop
  13162. // prepass
  13163. return true;
  13164. }
  13165. if ((v0->Type()).IsMixedTypedArrayPair(v1->Type()) || (v1->Type()).IsMixedTypedArrayPair(v0->Type()))
  13166. {
  13167. return true;
  13168. }
  13169. const bool doFloatTypeSpec = DoFloatTypeSpec();
  13170. if(doFloatTypeSpec && (v0->IsFloat() || v1->IsFloat()))
  13171. {
  13172. // Float specialization allows specializing values of arbitrary types, even values that are definitely not float
  13173. return true;
  13174. }
  13175. // SIMD_JS
  13176. if (SIMD128_TYPE_SPEC_FLAG && v0->Type().IsSimd128())
  13177. {
  13178. // We only type-spec Undefined values, Objects (possibly merged SIMD values), or actual SIMD values.
  13179. if (v1->Type().IsLikelyUndefined() || v1->Type().IsLikelyNull())
  13180. {
  13181. return true;
  13182. }
  13183. if (v1->Type().IsLikelyObject() && v1->Type().GetObjectType() == ObjectType::Object)
  13184. {
  13185. return true;
  13186. }
  13187. if (v1->Type().IsSimd128())
  13188. {
  13189. return v0->Type().GetObjectType() == v1->Type().GetObjectType();
  13190. }
  13191. }
  13192. const bool doArrayMissingValueCheckHoist = DoArrayMissingValueCheckHoist();
  13193. const bool doNativeArrayTypeSpec = DoNativeArrayTypeSpec();
  13194. const auto AreValueTypesCompatible = [=](const ValueType t0, const ValueType t1)
  13195. {
  13196. return
  13197. t0.IsSubsetOf(t1, doAggressiveIntTypeSpec, doFloatTypeSpec, doArrayMissingValueCheckHoist, doNativeArrayTypeSpec) ||
  13198. t1.IsSubsetOf(t0, doAggressiveIntTypeSpec, doFloatTypeSpec, doArrayMissingValueCheckHoist, doNativeArrayTypeSpec);
  13199. };
  13200. const ValueType t0(v0->Type().ToDefinite()), t1(v1->Type().ToDefinite());
  13201. if(t0.IsLikelyObject() && t1.IsLikelyObject())
  13202. {
  13203. // Check compatibility for the primitive portions and the object portions of the value types separately
  13204. if(AreValueTypesCompatible(t0.ToDefiniteObject(), t1.ToDefiniteObject()) &&
  13205. (
  13206. !t0.HasBeenPrimitive() ||
  13207. !t1.HasBeenPrimitive() ||
  13208. AreValueTypesCompatible(t0.ToDefinitePrimitiveSubset(), t1.ToDefinitePrimitiveSubset())
  13209. ))
  13210. {
  13211. return true;
  13212. }
  13213. }
  13214. else if(AreValueTypesCompatible(t0, t1))
  13215. {
  13216. return true;
  13217. }
  13218. const FloatConstantValueInfo *floatConstantValueInfo;
  13219. const ValueInfo *likelyIntValueinfo;
  13220. if(v0->IsFloatConstant() && v1->IsLikelyInt())
  13221. {
  13222. floatConstantValueInfo = v0->AsFloatConstant();
  13223. likelyIntValueinfo = v1;
  13224. }
  13225. else if(v0->IsLikelyInt() && v1->IsFloatConstant())
  13226. {
  13227. floatConstantValueInfo = v1->AsFloatConstant();
  13228. likelyIntValueinfo = v0;
  13229. }
  13230. else
  13231. {
  13232. return false;
  13233. }
  13234. // A float constant value with a value that is actually an int is a subset of a likely-int value.
  13235. // Ideally, we should create an int constant value for this up front, such that IsInt() also returns true. There
  13236. // were other issues with that, should see if that can be done.
  13237. int32 int32Value;
  13238. return
  13239. Js::JavascriptNumber::TryGetInt32Value(floatConstantValueInfo->FloatValue(), &int32Value) &&
  13240. (!likelyIntValueinfo->IsLikelyTaggedInt() || !Js::TaggedInt::IsOverflow(int32Value));
  13241. }
  13242. #if DBG
  13243. void
  13244. GlobOpt::VerifyArrayValueInfoForTracking(
  13245. const ValueInfo *const valueInfo,
  13246. const bool isJsArray,
  13247. const BasicBlock *const block,
  13248. const bool ignoreKnownImplicitCalls) const
  13249. {
  13250. Assert(valueInfo);
  13251. Assert(valueInfo->IsAnyOptimizedArray());
  13252. Assert(isJsArray == valueInfo->IsArrayOrObjectWithArray());
  13253. Assert(!isJsArray == valueInfo->IsOptimizedTypedArray());
  13254. Assert(block);
  13255. Loop *implicitCallsLoop;
  13256. if(block->next && !block->next->isDeleted && block->next->isLoopHeader)
  13257. {
  13258. // Since a loop's landing pad does not have user code, determine whether disabling implicit calls is allowed in the
  13259. // landing pad based on the loop for which this block is the landing pad.
  13260. implicitCallsLoop = block->next->loop;
  13261. Assert(implicitCallsLoop);
  13262. Assert(implicitCallsLoop->landingPad == block);
  13263. }
  13264. else
  13265. {
  13266. implicitCallsLoop = block->loop;
  13267. }
  13268. Assert(
  13269. !isJsArray ||
  13270. DoArrayCheckHoist(valueInfo->Type(), implicitCallsLoop) ||
  13271. (
  13272. ignoreKnownImplicitCalls &&
  13273. !(implicitCallsLoop ? ImplicitCallFlagsAllowOpts(implicitCallsLoop) : ImplicitCallFlagsAllowOpts(func))
  13274. ));
  13275. Assert(!(isJsArray && valueInfo->HasNoMissingValues() && !DoArrayMissingValueCheckHoist()));
  13276. Assert(
  13277. !(
  13278. valueInfo->IsArrayValueInfo() &&
  13279. (
  13280. valueInfo->AsArrayValueInfo()->HeadSegmentSym() ||
  13281. valueInfo->AsArrayValueInfo()->HeadSegmentLengthSym()
  13282. ) &&
  13283. !DoArraySegmentHoist(valueInfo->Type())
  13284. ));
  13285. Assert(
  13286. !(
  13287. !isJsArray &&
  13288. valueInfo->IsArrayValueInfo() &&
  13289. valueInfo->AsArrayValueInfo()->HeadSegmentLengthSym() &&
  13290. !(
  13291. DoTypedArraySegmentLengthHoist(implicitCallsLoop) ||
  13292. (
  13293. ignoreKnownImplicitCalls &&
  13294. !(implicitCallsLoop ? ImplicitCallFlagsAllowOpts(implicitCallsLoop) : ImplicitCallFlagsAllowOpts(func))
  13295. )
  13296. )
  13297. ));
  13298. Assert(
  13299. !(
  13300. isJsArray &&
  13301. valueInfo->IsArrayValueInfo() &&
  13302. valueInfo->AsArrayValueInfo()->LengthSym() &&
  13303. !DoArrayLengthHoist()
  13304. ));
  13305. }
  13306. #endif
  13307. void
  13308. GlobOpt::TrackNewValueForKills(Value *const value)
  13309. {
  13310. Assert(value);
  13311. if(!value->GetValueInfo()->IsAnyOptimizedArray())
  13312. {
  13313. return;
  13314. }
  13315. DoTrackNewValueForKills(value);
  13316. }
  13317. void
  13318. GlobOpt::DoTrackNewValueForKills(Value *const value)
  13319. {
  13320. Assert(value);
  13321. ValueInfo *const valueInfo = value->GetValueInfo();
  13322. Assert(valueInfo->IsAnyOptimizedArray());
  13323. Assert(!valueInfo->IsArrayValueInfo());
  13324. // The value and value info here are new, so it's okay to modify the value info in-place
  13325. Assert(!valueInfo->GetSymStore());
  13326. const bool isJsArray = valueInfo->IsArrayOrObjectWithArray();
  13327. Assert(!isJsArray == valueInfo->IsOptimizedTypedArray());
  13328. Loop *implicitCallsLoop;
  13329. if(currentBlock->next && !currentBlock->next->isDeleted && currentBlock->next->isLoopHeader)
  13330. {
  13331. // Since a loop's landing pad does not have user code, determine whether disabling implicit calls is allowed in the
  13332. // landing pad based on the loop for which this block is the landing pad.
  13333. implicitCallsLoop = currentBlock->next->loop;
  13334. Assert(implicitCallsLoop);
  13335. Assert(implicitCallsLoop->landingPad == currentBlock);
  13336. }
  13337. else
  13338. {
  13339. implicitCallsLoop = currentBlock->loop;
  13340. }
  13341. if(isJsArray)
  13342. {
  13343. if(!DoArrayCheckHoist(valueInfo->Type(), implicitCallsLoop))
  13344. {
  13345. // Array opts are disabled for this value type, so treat it as an indefinite value type going forward
  13346. valueInfo->Type() = valueInfo->Type().ToLikely();
  13347. return;
  13348. }
  13349. if(valueInfo->HasNoMissingValues() && !DoArrayMissingValueCheckHoist())
  13350. {
  13351. valueInfo->Type() = valueInfo->Type().SetHasNoMissingValues(false);
  13352. }
  13353. }
  13354. #if DBG
  13355. VerifyArrayValueInfoForTracking(valueInfo, isJsArray, currentBlock);
  13356. #endif
  13357. if(!isJsArray)
  13358. {
  13359. return;
  13360. }
  13361. // Can't assume going forward that it will definitely be an array without disabling implicit calls, because the
  13362. // array may be transformed into an ES5 array. Since array opts are enabled, implicit calls can be disabled, and we can
  13363. // treat it as a definite value type going forward, but the value needs to be tracked so that something like a call can
  13364. // revert the value type to a likely version.
  13365. blockData.valuesToKillOnCalls->Add(value);
  13366. }
  13367. void
  13368. GlobOpt::TrackCopiedValueForKills(Value *const value)
  13369. {
  13370. Assert(value);
  13371. if(!value->GetValueInfo()->IsAnyOptimizedArray())
  13372. {
  13373. return;
  13374. }
  13375. DoTrackCopiedValueForKills(value);
  13376. }
  13377. void
  13378. GlobOpt::DoTrackCopiedValueForKills(Value *const value)
  13379. {
  13380. Assert(value);
  13381. ValueInfo *const valueInfo = value->GetValueInfo();
  13382. Assert(valueInfo->IsAnyOptimizedArray());
  13383. const bool isJsArray = valueInfo->IsArrayOrObjectWithArray();
  13384. Assert(!isJsArray == valueInfo->IsOptimizedTypedArray());
  13385. #if DBG
  13386. VerifyArrayValueInfoForTracking(valueInfo, isJsArray, currentBlock);
  13387. #endif
  13388. if(!isJsArray && !(valueInfo->IsArrayValueInfo() && valueInfo->AsArrayValueInfo()->HeadSegmentLengthSym()))
  13389. {
  13390. return;
  13391. }
  13392. // Can't assume going forward that it will definitely be an array without disabling implicit calls, because the
  13393. // array may be transformed into an ES5 array. Since array opts are enabled, implicit calls can be disabled, and we can
  13394. // treat it as a definite value type going forward, but the value needs to be tracked so that something like a call can
  13395. // revert the value type to a likely version.
  13396. blockData.valuesToKillOnCalls->Add(value);
  13397. }
  13398. void
  13399. GlobOpt::TrackMergedValueForKills(
  13400. Value *const value,
  13401. GlobOptBlockData *const blockData,
  13402. BVSparse<JitArenaAllocator> *const mergedValueTypesTrackedForKills) const
  13403. {
  13404. Assert(value);
  13405. if(!value->GetValueInfo()->IsAnyOptimizedArray())
  13406. {
  13407. return;
  13408. }
  13409. DoTrackMergedValueForKills(value, blockData, mergedValueTypesTrackedForKills);
  13410. }
  13411. void
  13412. GlobOpt::DoTrackMergedValueForKills(
  13413. Value *const value,
  13414. GlobOptBlockData *const blockData,
  13415. BVSparse<JitArenaAllocator> *const mergedValueTypesTrackedForKills) const
  13416. {
  13417. Assert(value);
  13418. Assert(blockData);
  13419. ValueInfo *valueInfo = value->GetValueInfo();
  13420. Assert(valueInfo->IsAnyOptimizedArray());
  13421. const bool isJsArray = valueInfo->IsArrayOrObjectWithArray();
  13422. Assert(!isJsArray == valueInfo->IsOptimizedTypedArray());
  13423. #if DBG
  13424. VerifyArrayValueInfoForTracking(valueInfo, isJsArray, currentBlock, true);
  13425. #endif
  13426. if(!isJsArray && !(valueInfo->IsArrayValueInfo() && valueInfo->AsArrayValueInfo()->HeadSegmentLengthSym()))
  13427. {
  13428. return;
  13429. }
  13430. // Can't assume going forward that it will definitely be an array without disabling implicit calls, because the
  13431. // array may be transformed into an ES5 array. Since array opts are enabled, implicit calls can be disabled, and we can
  13432. // treat it as a definite value type going forward, but the value needs to be tracked so that something like a call can
  13433. // revert the value type to a likely version.
  13434. if(!mergedValueTypesTrackedForKills || !mergedValueTypesTrackedForKills->TestAndSet(value->GetValueNumber()))
  13435. {
  13436. blockData->valuesToKillOnCalls->Add(value);
  13437. }
  13438. }
  13439. void
  13440. GlobOpt::TrackValueInfoChangeForKills(BasicBlock *const block, Value *const value, ValueInfo *const newValueInfo, const bool compensated) const
  13441. {
  13442. Assert(block);
  13443. Assert(value);
  13444. Assert(newValueInfo);
  13445. ValueInfo *const oldValueInfo = value->GetValueInfo();
  13446. #if DBG
  13447. if(oldValueInfo->IsAnyOptimizedArray())
  13448. {
  13449. VerifyArrayValueInfoForTracking(oldValueInfo, oldValueInfo->IsArrayOrObjectWithArray(), block, compensated);
  13450. }
  13451. #endif
  13452. const bool trackOldValueInfo =
  13453. oldValueInfo->IsArrayOrObjectWithArray() ||
  13454. (
  13455. oldValueInfo->IsOptimizedTypedArray() &&
  13456. oldValueInfo->IsArrayValueInfo() &&
  13457. oldValueInfo->AsArrayValueInfo()->HeadSegmentLengthSym()
  13458. );
  13459. Assert(trackOldValueInfo == block->globOptData.valuesToKillOnCalls->ContainsKey(value));
  13460. #if DBG
  13461. if(newValueInfo->IsAnyOptimizedArray())
  13462. {
  13463. VerifyArrayValueInfoForTracking(newValueInfo, newValueInfo->IsArrayOrObjectWithArray(), block, compensated);
  13464. }
  13465. #endif
  13466. const bool trackNewValueInfo =
  13467. newValueInfo->IsArrayOrObjectWithArray() ||
  13468. (
  13469. newValueInfo->IsOptimizedTypedArray() &&
  13470. newValueInfo->IsArrayValueInfo() &&
  13471. newValueInfo->AsArrayValueInfo()->HeadSegmentLengthSym()
  13472. );
  13473. if(trackOldValueInfo == trackNewValueInfo)
  13474. {
  13475. return;
  13476. }
  13477. if(trackNewValueInfo)
  13478. {
  13479. block->globOptData.valuesToKillOnCalls->Add(value);
  13480. }
  13481. else
  13482. {
  13483. block->globOptData.valuesToKillOnCalls->Remove(value);
  13484. }
  13485. }
  13486. void
  13487. GlobOpt::ProcessValueKills(IR::Instr *const instr)
  13488. {
  13489. Assert(instr);
  13490. ValueSet *const valuesToKillOnCalls = blockData.valuesToKillOnCalls;
  13491. if(!IsLoopPrePass() && valuesToKillOnCalls->Count() == 0)
  13492. {
  13493. return;
  13494. }
  13495. const JsArrayKills kills = CheckJsArrayKills(instr);
  13496. Assert(!kills.KillsArrayHeadSegments() || kills.KillsArrayHeadSegmentLengths());
  13497. if(IsLoopPrePass())
  13498. {
  13499. rootLoopPrePass->jsArrayKills = rootLoopPrePass->jsArrayKills.Merge(kills);
  13500. Assert(
  13501. !rootLoopPrePass->parent ||
  13502. rootLoopPrePass->jsArrayKills.AreSubsetOf(rootLoopPrePass->parent->jsArrayKills));
  13503. if(kills.KillsAllArrays())
  13504. {
  13505. rootLoopPrePass->needImplicitCallBailoutChecksForJsArrayCheckHoist = false;
  13506. }
  13507. if(valuesToKillOnCalls->Count() == 0)
  13508. {
  13509. return;
  13510. }
  13511. }
  13512. if(kills.KillsAllArrays())
  13513. {
  13514. Assert(kills.KillsTypedArrayHeadSegmentLengths());
  13515. // - Calls need to kill the value types of values in the following list. For instance, calls can transform a JS array
  13516. // into an ES5 array, so any definitely-array value types need to be killed. Update the value types.
  13517. // - Calls also need to kill typed array head segment lengths. A typed array's array buffer may be transferred to a web
  13518. // worker, in which case the typed array's length is set to zero.
  13519. for(auto it = valuesToKillOnCalls->GetIterator(); it.IsValid(); it.MoveNext())
  13520. {
  13521. Value *const value = it.CurrentValue();
  13522. ValueInfo *const valueInfo = value->GetValueInfo();
  13523. Assert(
  13524. valueInfo->IsArrayOrObjectWithArray() ||
  13525. valueInfo->IsOptimizedTypedArray() && valueInfo->AsArrayValueInfo()->HeadSegmentLengthSym());
  13526. if(valueInfo->IsArrayOrObjectWithArray())
  13527. {
  13528. ChangeValueType(nullptr, value, valueInfo->Type().ToLikely(), false);
  13529. continue;
  13530. }
  13531. ChangeValueInfo(
  13532. nullptr,
  13533. value,
  13534. valueInfo->AsArrayValueInfo()->Copy(alloc, true, false /* copyHeadSegmentLength */, true));
  13535. }
  13536. valuesToKillOnCalls->Clear();
  13537. return;
  13538. }
  13539. if(kills.KillsArraysWithNoMissingValues())
  13540. {
  13541. // Some operations may kill arrays with no missing values in unlikely circumstances. Convert their value types to likely
  13542. // versions so that the checks have to be redone.
  13543. for(auto it = valuesToKillOnCalls->GetIteratorWithRemovalSupport(); it.IsValid(); it.MoveNext())
  13544. {
  13545. Value *const value = it.CurrentValue();
  13546. ValueInfo *const valueInfo = value->GetValueInfo();
  13547. Assert(
  13548. valueInfo->IsArrayOrObjectWithArray() ||
  13549. valueInfo->IsOptimizedTypedArray() && valueInfo->AsArrayValueInfo()->HeadSegmentLengthSym());
  13550. if(!valueInfo->IsArrayOrObjectWithArray() || !valueInfo->HasNoMissingValues())
  13551. {
  13552. continue;
  13553. }
  13554. ChangeValueType(nullptr, value, valueInfo->Type().ToLikely(), false);
  13555. it.RemoveCurrent();
  13556. }
  13557. }
  13558. if(kills.KillsNativeArrays())
  13559. {
  13560. // Some operations may kill native arrays in (what should be) unlikely circumstances. Convert their value types to
  13561. // likely versions so that the checks have to be redone.
  13562. for(auto it = valuesToKillOnCalls->GetIteratorWithRemovalSupport(); it.IsValid(); it.MoveNext())
  13563. {
  13564. Value *const value = it.CurrentValue();
  13565. ValueInfo *const valueInfo = value->GetValueInfo();
  13566. Assert(
  13567. valueInfo->IsArrayOrObjectWithArray() ||
  13568. valueInfo->IsOptimizedTypedArray() && valueInfo->AsArrayValueInfo()->HeadSegmentLengthSym());
  13569. if(!valueInfo->IsArrayOrObjectWithArray() || valueInfo->HasVarElements())
  13570. {
  13571. continue;
  13572. }
  13573. ChangeValueType(nullptr, value, valueInfo->Type().ToLikely(), false);
  13574. it.RemoveCurrent();
  13575. }
  13576. }
  13577. const bool likelyKillsJsArraysWithNoMissingValues = IsOperationThatLikelyKillsJsArraysWithNoMissingValues(instr);
  13578. if(!kills.KillsArrayHeadSegmentLengths())
  13579. {
  13580. Assert(!kills.KillsArrayHeadSegments());
  13581. if(!likelyKillsJsArraysWithNoMissingValues && !kills.KillsArrayLengths())
  13582. {
  13583. return;
  13584. }
  13585. }
  13586. for(auto it = valuesToKillOnCalls->GetIterator(); it.IsValid(); it.MoveNext())
  13587. {
  13588. Value *const value = it.CurrentValue();
  13589. ValueInfo *valueInfo = value->GetValueInfo();
  13590. Assert(
  13591. valueInfo->IsArrayOrObjectWithArray() ||
  13592. valueInfo->IsOptimizedTypedArray() && valueInfo->AsArrayValueInfo()->HeadSegmentLengthSym());
  13593. if(!valueInfo->IsArrayOrObjectWithArray())
  13594. {
  13595. continue;
  13596. }
  13597. if(likelyKillsJsArraysWithNoMissingValues && valueInfo->HasNoMissingValues())
  13598. {
  13599. ChangeValueType(nullptr, value, valueInfo->Type().SetHasNoMissingValues(false), true);
  13600. valueInfo = value->GetValueInfo();
  13601. }
  13602. if(!valueInfo->IsArrayValueInfo())
  13603. {
  13604. continue;
  13605. }
  13606. ArrayValueInfo *const arrayValueInfo = valueInfo->AsArrayValueInfo();
  13607. const bool removeHeadSegment = kills.KillsArrayHeadSegments() && arrayValueInfo->HeadSegmentSym();
  13608. const bool removeHeadSegmentLength = kills.KillsArrayHeadSegmentLengths() && arrayValueInfo->HeadSegmentLengthSym();
  13609. const bool removeLength = kills.KillsArrayLengths() && arrayValueInfo->LengthSym();
  13610. if(removeHeadSegment || removeHeadSegmentLength || removeLength)
  13611. {
  13612. ChangeValueInfo(
  13613. nullptr,
  13614. value,
  13615. arrayValueInfo->Copy(alloc, !removeHeadSegment, !removeHeadSegmentLength, !removeLength));
  13616. valueInfo = value->GetValueInfo();
  13617. }
  13618. }
  13619. }
  13620. void
  13621. GlobOpt::ProcessValueKills(BasicBlock *const block, GlobOptBlockData *const blockData)
  13622. {
  13623. Assert(block);
  13624. Assert(blockData);
  13625. ValueSet *const valuesToKillOnCalls = blockData->valuesToKillOnCalls;
  13626. if(!IsLoopPrePass() && valuesToKillOnCalls->Count() == 0)
  13627. {
  13628. return;
  13629. }
  13630. // If the current block or loop has implicit calls, kill all definitely-array value types, as using that info will cause
  13631. // implicit calls to be disabled, resulting in unnecessary bailouts
  13632. const bool killValuesOnImplicitCalls =
  13633. (block->loop ? !this->ImplicitCallFlagsAllowOpts(block->loop) : !this->ImplicitCallFlagsAllowOpts(func));
  13634. if (!killValuesOnImplicitCalls)
  13635. {
  13636. return;
  13637. }
  13638. if(IsLoopPrePass() && block->loop == rootLoopPrePass)
  13639. {
  13640. AnalysisAssert(rootLoopPrePass);
  13641. rootLoopPrePass->jsArrayKills.SetKillsAllArrays();
  13642. Assert(!rootLoopPrePass->parent || rootLoopPrePass->jsArrayKills.AreSubsetOf(rootLoopPrePass->parent->jsArrayKills));
  13643. if(valuesToKillOnCalls->Count() == 0)
  13644. {
  13645. return;
  13646. }
  13647. }
  13648. for(auto it = valuesToKillOnCalls->GetIterator(); it.IsValid(); it.MoveNext())
  13649. {
  13650. Value *const value = it.CurrentValue();
  13651. ValueInfo *const valueInfo = value->GetValueInfo();
  13652. Assert(
  13653. valueInfo->IsArrayOrObjectWithArray() ||
  13654. valueInfo->IsOptimizedTypedArray() && valueInfo->AsArrayValueInfo()->HeadSegmentLengthSym());
  13655. if(valueInfo->IsArrayOrObjectWithArray())
  13656. {
  13657. ChangeValueType(nullptr, value, valueInfo->Type().ToLikely(), false);
  13658. continue;
  13659. }
  13660. ChangeValueInfo(
  13661. nullptr,
  13662. value,
  13663. valueInfo->AsArrayValueInfo()->Copy(alloc, true, false /* copyHeadSegmentLength */, true));
  13664. }
  13665. valuesToKillOnCalls->Clear();
  13666. }
  13667. void
  13668. GlobOpt::ProcessValueKillsForLoopHeaderAfterBackEdgeMerge(BasicBlock *const block, GlobOptBlockData *const blockData)
  13669. {
  13670. Assert(block);
  13671. Assert(block->isLoopHeader);
  13672. Assert(blockData);
  13673. ValueSet *const valuesToKillOnCalls = blockData->valuesToKillOnCalls;
  13674. if(valuesToKillOnCalls->Count() == 0)
  13675. {
  13676. return;
  13677. }
  13678. const JsArrayKills loopKills(block->loop->jsArrayKills);
  13679. for(auto it = valuesToKillOnCalls->GetIteratorWithRemovalSupport(); it.IsValid(); it.MoveNext())
  13680. {
  13681. Value *const value = it.CurrentValue();
  13682. ValueInfo *valueInfo = value->GetValueInfo();
  13683. Assert(
  13684. valueInfo->IsArrayOrObjectWithArray() ||
  13685. valueInfo->IsOptimizedTypedArray() && valueInfo->AsArrayValueInfo()->HeadSegmentLengthSym());
  13686. const bool isJsArray = valueInfo->IsArrayOrObjectWithArray();
  13687. Assert(!isJsArray == valueInfo->IsOptimizedTypedArray());
  13688. if(isJsArray ? loopKills.KillsValueType(valueInfo->Type()) : loopKills.KillsTypedArrayHeadSegmentLengths())
  13689. {
  13690. // Hoisting array checks and other related things for this type is disabled for the loop due to the kill, as
  13691. // compensation code is currently not added on back-edges. When merging values from a back-edge, the array value
  13692. // type cannot be definite, as that may require adding compensation code on the back-edge if the optimization pass
  13693. // chooses to not optimize the array.
  13694. if(isJsArray)
  13695. {
  13696. ChangeValueType(nullptr, value, valueInfo->Type().ToLikely(), false);
  13697. }
  13698. else
  13699. {
  13700. ChangeValueInfo(
  13701. nullptr,
  13702. value,
  13703. valueInfo->AsArrayValueInfo()->Copy(alloc, true, false /* copyHeadSegmentLength */, true));
  13704. }
  13705. it.RemoveCurrent();
  13706. continue;
  13707. }
  13708. if(!isJsArray || !valueInfo->IsArrayValueInfo())
  13709. {
  13710. continue;
  13711. }
  13712. // Similarly, if the loop contains an operation that kills JS array segments, don't make the segment or other related
  13713. // syms available initially inside the loop
  13714. ArrayValueInfo *const arrayValueInfo = valueInfo->AsArrayValueInfo();
  13715. const bool removeHeadSegment = loopKills.KillsArrayHeadSegments() && arrayValueInfo->HeadSegmentSym();
  13716. const bool removeHeadSegmentLength = loopKills.KillsArrayHeadSegmentLengths() && arrayValueInfo->HeadSegmentLengthSym();
  13717. const bool removeLength = loopKills.KillsArrayLengths() && arrayValueInfo->LengthSym();
  13718. if(removeHeadSegment || removeHeadSegmentLength || removeLength)
  13719. {
  13720. ChangeValueInfo(
  13721. nullptr,
  13722. value,
  13723. arrayValueInfo->Copy(alloc, !removeHeadSegment, !removeHeadSegmentLength, !removeLength));
  13724. valueInfo = value->GetValueInfo();
  13725. }
  13726. }
  13727. }
  13728. bool
  13729. GlobOpt::NeedBailOnImplicitCallForLiveValues(BasicBlock *const block, const bool isForwardPass) const
  13730. {
  13731. if(isForwardPass)
  13732. {
  13733. return block->globOptData.valuesToKillOnCalls->Count() != 0;
  13734. }
  13735. if(block->noImplicitCallUses->IsEmpty())
  13736. {
  13737. Assert(block->noImplicitCallNoMissingValuesUses->IsEmpty());
  13738. Assert(block->noImplicitCallNativeArrayUses->IsEmpty());
  13739. Assert(block->noImplicitCallJsArrayHeadSegmentSymUses->IsEmpty());
  13740. Assert(block->noImplicitCallArrayLengthSymUses->IsEmpty());
  13741. return false;
  13742. }
  13743. return true;
  13744. }
  13745. IR::Instr*
  13746. GlobOpt::CreateBoundsCheckInstr(IR::Opnd* lowerBound, IR::Opnd* upperBound, int offset, Func* func)
  13747. {
  13748. IR::Instr* instr = IR::Instr::New(Js::OpCode::BoundCheck, func);
  13749. return AttachBoundsCheckData(instr, lowerBound, upperBound, offset);
  13750. }
  13751. IR::Instr*
  13752. GlobOpt::CreateBoundsCheckInstr(IR::Opnd* lowerBound, IR::Opnd* upperBound, int offset, IR::BailOutKind bailoutkind, BailOutInfo* bailoutInfo, Func * func)
  13753. {
  13754. IR::Instr* instr = IR::BailOutInstr::New(Js::OpCode::BoundCheck, bailoutkind, bailoutInfo, func);
  13755. return AttachBoundsCheckData(instr, lowerBound, upperBound, offset);
  13756. }
  13757. IR::Instr*
  13758. GlobOpt::AttachBoundsCheckData(IR::Instr* instr, IR::Opnd* lowerBound, IR::Opnd* upperBound, int offset)
  13759. {
  13760. instr->SetSrc1(lowerBound);
  13761. instr->SetSrc2(upperBound);
  13762. if (offset != 0)
  13763. {
  13764. instr->SetDst(IR::IntConstOpnd::New(offset, TyInt32, instr->m_func, true));
  13765. }
  13766. return instr;
  13767. }
  13768. void
  13769. GlobOpt::OptArraySrc(IR::Instr * *const instrRef)
  13770. {
  13771. Assert(instrRef);
  13772. IR::Instr *&instr = *instrRef;
  13773. Assert(instr);
  13774. IR::Instr *baseOwnerInstr;
  13775. IR::IndirOpnd *baseOwnerIndir;
  13776. IR::RegOpnd *baseOpnd;
  13777. bool isProfilableLdElem, isProfilableStElem;
  13778. bool isLoad, isStore;
  13779. bool needsHeadSegment, needsHeadSegmentLength, needsLength, needsBoundChecks;
  13780. switch(instr->m_opcode)
  13781. {
  13782. // SIMD_JS
  13783. case Js::OpCode::Simd128_LdArr_F4:
  13784. case Js::OpCode::Simd128_LdArr_I4:
  13785. // no type-spec for Asm.js
  13786. if (this->GetIsAsmJSFunc())
  13787. {
  13788. return;
  13789. }
  13790. // fall through
  13791. case Js::OpCode::LdElemI_A:
  13792. case Js::OpCode::LdMethodElem:
  13793. if(!instr->GetSrc1()->IsIndirOpnd())
  13794. {
  13795. return;
  13796. }
  13797. baseOwnerInstr = nullptr;
  13798. baseOwnerIndir = instr->GetSrc1()->AsIndirOpnd();
  13799. baseOpnd = baseOwnerIndir->GetBaseOpnd();
  13800. isProfilableLdElem = instr->m_opcode == Js::OpCode::LdElemI_A; // LdMethodElem is currently not profiled
  13801. isProfilableLdElem |= Js::IsSimd128Load(instr->m_opcode);
  13802. needsBoundChecks = needsHeadSegmentLength = needsHeadSegment = isLoad = true;
  13803. needsLength = isStore = isProfilableStElem = false;
  13804. break;
  13805. // SIMD_JS
  13806. case Js::OpCode::Simd128_StArr_F4:
  13807. case Js::OpCode::Simd128_StArr_I4:
  13808. if (this->GetIsAsmJSFunc())
  13809. {
  13810. return;
  13811. }
  13812. // fall through
  13813. case Js::OpCode::StElemI_A:
  13814. case Js::OpCode::StElemI_A_Strict:
  13815. case Js::OpCode::StElemC:
  13816. if(!instr->GetDst()->IsIndirOpnd())
  13817. {
  13818. return;
  13819. }
  13820. baseOwnerInstr = nullptr;
  13821. baseOwnerIndir = instr->GetDst()->AsIndirOpnd();
  13822. baseOpnd = baseOwnerIndir->GetBaseOpnd();
  13823. needsBoundChecks = isProfilableStElem = instr->m_opcode != Js::OpCode::StElemC;
  13824. isProfilableStElem |= Js::IsSimd128Store(instr->m_opcode);
  13825. needsHeadSegmentLength = needsHeadSegment = isStore = true;
  13826. needsLength = isLoad = isProfilableLdElem = false;
  13827. break;
  13828. case Js::OpCode::InlineArrayPush:
  13829. case Js::OpCode::InlineArrayPop:
  13830. {
  13831. baseOwnerInstr = instr;
  13832. baseOwnerIndir = nullptr;
  13833. IR::Opnd * thisOpnd = instr->GetSrc1();
  13834. // Return if it not a LikelyArray or Object with Array - No point in doing array check elimination.
  13835. if(!thisOpnd->IsRegOpnd() || !thisOpnd->GetValueType().IsLikelyArrayOrObjectWithArray())
  13836. {
  13837. return;
  13838. }
  13839. baseOpnd = thisOpnd->AsRegOpnd();
  13840. isLoad = instr->m_opcode == Js::OpCode::InlineArrayPop;
  13841. isStore = instr->m_opcode == Js::OpCode::InlineArrayPush;
  13842. needsLength = needsHeadSegmentLength = needsHeadSegment = true;
  13843. needsBoundChecks = isProfilableLdElem = isProfilableStElem = false;
  13844. break;
  13845. }
  13846. case Js::OpCode::LdLen_A:
  13847. if(!instr->GetSrc1()->IsRegOpnd())
  13848. {
  13849. return;
  13850. }
  13851. baseOwnerInstr = instr;
  13852. baseOwnerIndir = nullptr;
  13853. baseOpnd = instr->GetSrc1()->AsRegOpnd();
  13854. if(baseOpnd->GetValueType().IsLikelyObject() &&
  13855. baseOpnd->GetValueType().GetObjectType() == ObjectType::ObjectWithArray)
  13856. {
  13857. return;
  13858. }
  13859. needsLength = true;
  13860. needsBoundChecks =
  13861. needsHeadSegmentLength =
  13862. needsHeadSegment =
  13863. isStore =
  13864. isLoad =
  13865. isProfilableStElem =
  13866. isProfilableLdElem = false;
  13867. break;
  13868. default:
  13869. return;
  13870. }
  13871. Assert(!(baseOwnerInstr && baseOwnerIndir));
  13872. Assert(!needsHeadSegmentLength || needsHeadSegment);
  13873. if(baseOwnerIndir && !IsLoopPrePass())
  13874. {
  13875. // Since this happens before type specialization, make sure that any necessary conversions are done, and that the index
  13876. // is int-specialized if possible such that the const flags are correct.
  13877. ToVarUses(instr, baseOwnerIndir, baseOwnerIndir == instr->GetDst(), nullptr);
  13878. }
  13879. if(isProfilableStElem && !IsLoopPrePass())
  13880. {
  13881. // If the dead-store pass decides to add the bailout kind IR::BailOutInvalidatedArrayHeadSegment, and the fast path is
  13882. // generated, it may bail out before the operation is done, so this would need to be a pre-op bailout.
  13883. if(instr->HasBailOutInfo())
  13884. {
  13885. Assert(
  13886. instr->GetByteCodeOffset() != Js::Constants::NoByteCodeOffset &&
  13887. instr->GetBailOutInfo()->bailOutOffset <= instr->GetByteCodeOffset());
  13888. const IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  13889. Assert(
  13890. !(bailOutKind & ~IR::BailOutKindBits) ||
  13891. (bailOutKind & ~IR::BailOutKindBits) == IR::BailOutOnImplicitCallsPreOp);
  13892. if(!(bailOutKind & ~IR::BailOutKindBits))
  13893. {
  13894. instr->SetBailOutKind(bailOutKind + IR::BailOutOnImplicitCallsPreOp);
  13895. }
  13896. }
  13897. else
  13898. {
  13899. GenerateBailAtOperation(&instr, IR::BailOutOnImplicitCallsPreOp);
  13900. }
  13901. }
  13902. Value *const baseValue = FindValue(baseOpnd->m_sym);
  13903. if(!baseValue)
  13904. {
  13905. return;
  13906. }
  13907. ValueInfo *baseValueInfo = baseValue->GetValueInfo();
  13908. ValueType baseValueType(baseValueInfo->Type());
  13909. baseOpnd->SetValueType(baseValueType);
  13910. if(!baseValueType.IsLikelyAnyOptimizedArray() ||
  13911. !DoArrayCheckHoist(baseValueType, currentBlock->loop, instr) ||
  13912. baseOwnerIndir && !ShouldExpectConventionalArrayIndexValue(baseOwnerIndir))
  13913. {
  13914. return;
  13915. }
  13916. const bool isLikelyJsArray = !baseValueType.IsLikelyTypedArray();
  13917. Assert(isLikelyJsArray == baseValueType.IsLikelyArrayOrObjectWithArray());
  13918. Assert(!isLikelyJsArray == baseValueType.IsLikelyOptimizedTypedArray());
  13919. if(!isLikelyJsArray && instr->m_opcode == Js::OpCode::LdMethodElem)
  13920. {
  13921. // Fast path is not generated in this case since the subsequent call will throw
  13922. return;
  13923. }
  13924. ValueType newBaseValueType(baseValueType.ToDefiniteObject());
  13925. if(isLikelyJsArray && newBaseValueType.HasNoMissingValues() && !DoArrayMissingValueCheckHoist())
  13926. {
  13927. newBaseValueType = newBaseValueType.SetHasNoMissingValues(false);
  13928. }
  13929. Assert((newBaseValueType == baseValueType) == baseValueType.IsObject());
  13930. ArrayValueInfo *baseArrayValueInfo = nullptr;
  13931. const auto UpdateValue = [&](StackSym *newHeadSegmentSym, StackSym *newHeadSegmentLengthSym, StackSym *newLengthSym)
  13932. {
  13933. Assert(baseValueType.GetObjectType() == newBaseValueType.GetObjectType());
  13934. Assert(newBaseValueType.IsObject());
  13935. Assert(baseValueType.IsLikelyArray() || !newLengthSym);
  13936. if(!(newHeadSegmentSym || newHeadSegmentLengthSym || newLengthSym))
  13937. {
  13938. // We're not adding new information to the value other than changing the value type. Preserve any existing
  13939. // information and just change the value type.
  13940. ChangeValueType(currentBlock, baseValue, newBaseValueType, true);
  13941. return;
  13942. }
  13943. // Merge the new syms into the value while preserving any existing information, and change the value type
  13944. if(baseArrayValueInfo)
  13945. {
  13946. if(!newHeadSegmentSym)
  13947. {
  13948. newHeadSegmentSym = baseArrayValueInfo->HeadSegmentSym();
  13949. }
  13950. if(!newHeadSegmentLengthSym)
  13951. {
  13952. newHeadSegmentLengthSym = baseArrayValueInfo->HeadSegmentLengthSym();
  13953. }
  13954. if(!newLengthSym)
  13955. {
  13956. newLengthSym = baseArrayValueInfo->LengthSym();
  13957. }
  13958. Assert(
  13959. !baseArrayValueInfo->HeadSegmentSym() ||
  13960. newHeadSegmentSym == baseArrayValueInfo->HeadSegmentSym());
  13961. Assert(
  13962. !baseArrayValueInfo->HeadSegmentLengthSym() ||
  13963. newHeadSegmentLengthSym == baseArrayValueInfo->HeadSegmentLengthSym());
  13964. Assert(!baseArrayValueInfo->LengthSym() || newLengthSym == baseArrayValueInfo->LengthSym());
  13965. }
  13966. ArrayValueInfo *const newBaseArrayValueInfo =
  13967. ArrayValueInfo::New(
  13968. alloc,
  13969. newBaseValueType,
  13970. newHeadSegmentSym,
  13971. newHeadSegmentLengthSym,
  13972. newLengthSym,
  13973. baseValueInfo->GetSymStore());
  13974. ChangeValueInfo(currentBlock, baseValue, newBaseArrayValueInfo);
  13975. };
  13976. if(IsLoopPrePass())
  13977. {
  13978. if(newBaseValueType != baseValueType)
  13979. {
  13980. UpdateValue(nullptr, nullptr, nullptr);
  13981. }
  13982. // For javascript arrays and objects with javascript arrays:
  13983. // - Implicit calls need to be disabled and calls cannot be allowed in the loop since the array vtable may be changed
  13984. // into an ES5 array.
  13985. // For typed arrays:
  13986. // - A typed array's array buffer may be transferred to a web worker as part of an implicit call, in which case the
  13987. // typed array's length is set to zero. Implicit calls need to be disabled if the typed array's head segment length
  13988. // is going to be loaded and used later.
  13989. // Since we don't know if the loop has kills after this instruction, the kill information may not be complete. If a kill
  13990. // is found later, this information will be updated to not require disabling implicit calls.
  13991. if(!(
  13992. isLikelyJsArray
  13993. ? rootLoopPrePass->jsArrayKills.KillsValueType(newBaseValueType)
  13994. : rootLoopPrePass->jsArrayKills.KillsTypedArrayHeadSegmentLengths()
  13995. ))
  13996. {
  13997. rootLoopPrePass->needImplicitCallBailoutChecksForJsArrayCheckHoist = true;
  13998. }
  13999. return;
  14000. }
  14001. if(baseValueInfo->IsArrayValueInfo())
  14002. {
  14003. baseArrayValueInfo = baseValueInfo->AsArrayValueInfo();
  14004. }
  14005. const bool doArrayChecks = !baseValueType.IsObject();
  14006. const bool doArraySegmentHoist = DoArraySegmentHoist(baseValueType) && instr->m_opcode != Js::OpCode::StElemC;
  14007. const bool headSegmentIsAvailable = baseArrayValueInfo && baseArrayValueInfo->HeadSegmentSym();
  14008. const bool doHeadSegmentLoad = doArraySegmentHoist && needsHeadSegment && !headSegmentIsAvailable;
  14009. const bool doArraySegmentLengthHoist =
  14010. doArraySegmentHoist && (isLikelyJsArray || DoTypedArraySegmentLengthHoist(currentBlock->loop));
  14011. const bool headSegmentLengthIsAvailable = baseArrayValueInfo && baseArrayValueInfo->HeadSegmentLengthSym();
  14012. const bool doHeadSegmentLengthLoad =
  14013. doArraySegmentLengthHoist &&
  14014. (needsHeadSegmentLength || !isLikelyJsArray && needsLength) &&
  14015. !headSegmentLengthIsAvailable;
  14016. const bool lengthIsAvailable = baseArrayValueInfo && baseArrayValueInfo->LengthSym();
  14017. const bool doLengthLoad =
  14018. DoArrayLengthHoist() &&
  14019. needsLength &&
  14020. !lengthIsAvailable &&
  14021. baseValueType.IsLikelyArray() &&
  14022. DoLdLenIntSpec(instr->m_opcode == Js::OpCode::LdLen_A ? instr : nullptr, baseValueType);
  14023. StackSym *const newHeadSegmentSym = doHeadSegmentLoad ? StackSym::New(TyMachPtr, instr->m_func) : nullptr;
  14024. StackSym *const newHeadSegmentLengthSym = doHeadSegmentLengthLoad ? StackSym::New(TyUint32, instr->m_func) : nullptr;
  14025. StackSym *const newLengthSym = doLengthLoad ? StackSym::New(TyUint32, instr->m_func) : nullptr;
  14026. bool canBailOutOnArrayAccessHelperCall;
  14027. if (Js::IsSimd128LoadStore(instr->m_opcode))
  14028. {
  14029. // SIMD_JS
  14030. // simd load/store never call helper
  14031. canBailOutOnArrayAccessHelperCall = true;
  14032. }
  14033. else
  14034. {
  14035. canBailOutOnArrayAccessHelperCall = (isProfilableLdElem || isProfilableStElem) &&
  14036. DoEliminateArrayAccessHelperCall() &&
  14037. !(
  14038. instr->IsProfiledInstr() &&
  14039. (
  14040. isProfilableLdElem
  14041. ? instr->AsProfiledInstr()->u.ldElemInfo->LikelyNeedsHelperCall()
  14042. : instr->AsProfiledInstr()->u.stElemInfo->LikelyNeedsHelperCall()
  14043. )
  14044. );
  14045. }
  14046. bool doExtractBoundChecks = false, eliminatedLowerBoundCheck = false, eliminatedUpperBoundCheck = false;
  14047. StackSym *indexVarSym = nullptr;
  14048. Value *indexValue = nullptr;
  14049. IntConstantBounds indexConstantBounds;
  14050. Value *headSegmentLengthValue = nullptr;
  14051. IntConstantBounds headSegmentLengthConstantBounds;
  14052. if (baseValueType.IsLikelyOptimizedVirtualTypedArray() && !Js::IsSimd128LoadStore(instr->m_opcode) /*Always extract bounds for SIMD */)
  14053. {
  14054. if (isProfilableStElem ||
  14055. !instr->IsDstNotAlwaysConvertedToInt32() ||
  14056. ( (baseValueType.GetObjectType() == ObjectType::Float32VirtualArray ||
  14057. baseValueType.GetObjectType() == ObjectType::Float64VirtualArray) &&
  14058. !instr->IsDstNotAlwaysConvertedToNumber()
  14059. )
  14060. )
  14061. {
  14062. eliminatedLowerBoundCheck = true;
  14063. eliminatedUpperBoundCheck = true;
  14064. canBailOutOnArrayAccessHelperCall = false;
  14065. }
  14066. }
  14067. if(needsBoundChecks && DoBoundCheckElimination())
  14068. {
  14069. AnalysisAssert(baseOwnerIndir);
  14070. Assert(needsHeadSegmentLength);
  14071. // Bound checks can be separated from the instruction only if it can bail out instead of making a helper call when a
  14072. // bound check fails. And only if it would bail out, can we use a bound check to eliminate redundant bound checks later
  14073. // on that path.
  14074. doExtractBoundChecks = (headSegmentLengthIsAvailable || doHeadSegmentLengthLoad) && canBailOutOnArrayAccessHelperCall;
  14075. do
  14076. {
  14077. // Get the index value
  14078. IR::RegOpnd *const indexOpnd = baseOwnerIndir->GetIndexOpnd();
  14079. if(indexOpnd)
  14080. {
  14081. StackSym *const indexSym = indexOpnd->m_sym;
  14082. if(indexSym->IsTypeSpec())
  14083. {
  14084. Assert(indexSym->IsInt32());
  14085. indexVarSym = indexSym->GetVarEquivSym(nullptr);
  14086. Assert(indexVarSym);
  14087. indexValue = FindValue(indexVarSym);
  14088. Assert(indexValue);
  14089. AssertVerify(indexValue->GetValueInfo()->TryGetIntConstantBounds(&indexConstantBounds));
  14090. Assert(indexOpnd->GetType() == TyInt32 || indexOpnd->GetType() == TyUint32);
  14091. Assert(
  14092. (indexOpnd->GetType() == TyUint32) ==
  14093. ValueInfo::IsGreaterThanOrEqualTo(
  14094. indexValue,
  14095. indexConstantBounds.LowerBound(),
  14096. indexConstantBounds.UpperBound(),
  14097. nullptr,
  14098. 0,
  14099. 0));
  14100. if(indexOpnd->GetType() == TyUint32)
  14101. {
  14102. eliminatedLowerBoundCheck = true;
  14103. }
  14104. }
  14105. else
  14106. {
  14107. doExtractBoundChecks = false; // Bound check instruction operates only on int-specialized operands
  14108. indexValue = FindValue(indexSym);
  14109. if(!indexValue || !indexValue->GetValueInfo()->TryGetIntConstantBounds(&indexConstantBounds))
  14110. {
  14111. break;
  14112. }
  14113. if(ValueInfo::IsGreaterThanOrEqualTo(
  14114. indexValue,
  14115. indexConstantBounds.LowerBound(),
  14116. indexConstantBounds.UpperBound(),
  14117. nullptr,
  14118. 0,
  14119. 0))
  14120. {
  14121. eliminatedLowerBoundCheck = true;
  14122. }
  14123. }
  14124. if(!eliminatedLowerBoundCheck &&
  14125. ValueInfo::IsLessThan(
  14126. indexValue,
  14127. indexConstantBounds.LowerBound(),
  14128. indexConstantBounds.UpperBound(),
  14129. nullptr,
  14130. 0,
  14131. 0))
  14132. {
  14133. eliminatedUpperBoundCheck = true;
  14134. doExtractBoundChecks = false;
  14135. break;
  14136. }
  14137. }
  14138. else
  14139. {
  14140. const int32 indexConstantValue = baseOwnerIndir->GetOffset();
  14141. if(indexConstantValue < 0)
  14142. {
  14143. eliminatedUpperBoundCheck = true;
  14144. doExtractBoundChecks = false;
  14145. break;
  14146. }
  14147. if(indexConstantValue == INT32_MAX)
  14148. {
  14149. eliminatedLowerBoundCheck = true;
  14150. doExtractBoundChecks = false;
  14151. break;
  14152. }
  14153. indexConstantBounds = IntConstantBounds(indexConstantValue, indexConstantValue);
  14154. eliminatedLowerBoundCheck = true;
  14155. }
  14156. if(!headSegmentLengthIsAvailable)
  14157. {
  14158. break;
  14159. }
  14160. headSegmentLengthValue = FindValue(baseArrayValueInfo->HeadSegmentLengthSym());
  14161. if(!headSegmentLengthValue)
  14162. {
  14163. if(doExtractBoundChecks)
  14164. {
  14165. headSegmentLengthConstantBounds = IntConstantBounds(0, Js::SparseArraySegmentBase::MaxLength);
  14166. }
  14167. break;
  14168. }
  14169. AssertVerify(headSegmentLengthValue->GetValueInfo()->TryGetIntConstantBounds(&headSegmentLengthConstantBounds));
  14170. if (ValueInfo::IsLessThanOrEqualTo(
  14171. indexValue,
  14172. indexConstantBounds.LowerBound(),
  14173. indexConstantBounds.UpperBound(),
  14174. headSegmentLengthValue,
  14175. headSegmentLengthConstantBounds.LowerBound(),
  14176. headSegmentLengthConstantBounds.UpperBound(),
  14177. GetBoundCheckOffsetForSimd(newBaseValueType, instr, -1)
  14178. ))
  14179. {
  14180. eliminatedUpperBoundCheck = true;
  14181. if(eliminatedLowerBoundCheck)
  14182. {
  14183. doExtractBoundChecks = false;
  14184. }
  14185. }
  14186. } while(false);
  14187. }
  14188. if(doArrayChecks || doHeadSegmentLoad || doHeadSegmentLengthLoad || doLengthLoad || doExtractBoundChecks)
  14189. {
  14190. // Find the loops out of which array checks and head segment loads need to be hoisted
  14191. Loop *hoistChecksOutOfLoop = nullptr;
  14192. Loop *hoistHeadSegmentLoadOutOfLoop = nullptr;
  14193. Loop *hoistHeadSegmentLengthLoadOutOfLoop = nullptr;
  14194. Loop *hoistLengthLoadOutOfLoop = nullptr;
  14195. if(doArrayChecks || doHeadSegmentLoad || doHeadSegmentLengthLoad || doLengthLoad)
  14196. {
  14197. for(Loop *loop = currentBlock->loop; loop; loop = loop->parent)
  14198. {
  14199. const JsArrayKills loopKills(loop->jsArrayKills);
  14200. Value *baseValueInLoopLandingPad;
  14201. if(isLikelyJsArray && loopKills.KillsValueType(newBaseValueType) ||
  14202. !OptIsInvariant(baseOpnd->m_sym, currentBlock, loop, baseValue, true, true, &baseValueInLoopLandingPad) ||
  14203. !(doArrayChecks || baseValueInLoopLandingPad->GetValueInfo()->IsObject()))
  14204. {
  14205. break;
  14206. }
  14207. // The value types should be the same, except:
  14208. // - The value type in the landing pad is a type that can merge to a specific object type. Typically, these
  14209. // cases will use BailOnNoProfile, but that can be disabled due to excessive bailouts. Those value types
  14210. // merge aggressively to the other side's object type, so the value type may have started off as
  14211. // Uninitialized, [Likely]Undefined|Null, [Likely]UninitializedObject, etc., and changed in the loop to an
  14212. // array type during a prepass.
  14213. // - StElems in the loop can kill the no-missing-values info.
  14214. // - The native array type may be made more conservative based on profile data by an instruction in the loop.
  14215. Assert(
  14216. baseValueInLoopLandingPad->GetValueInfo()->CanMergeToSpecificObjectType() ||
  14217. baseValueInLoopLandingPad->GetValueInfo()->Type().SetCanBeTaggedValue(false) ==
  14218. baseValueType.SetCanBeTaggedValue(false) ||
  14219. baseValueInLoopLandingPad->GetValueInfo()->Type().SetHasNoMissingValues(false).SetCanBeTaggedValue(false) ==
  14220. baseValueType.SetHasNoMissingValues(false).SetCanBeTaggedValue(false) ||
  14221. baseValueInLoopLandingPad->GetValueInfo()->Type().SetHasNoMissingValues(false).ToLikely().SetCanBeTaggedValue(false) ==
  14222. baseValueType.SetHasNoMissingValues(false).SetCanBeTaggedValue(false) ||
  14223. (
  14224. baseValueInLoopLandingPad->GetValueInfo()->Type().IsLikelyNativeArray() &&
  14225. baseValueInLoopLandingPad->GetValueInfo()->Type().Merge(baseValueType).SetHasNoMissingValues(false).SetCanBeTaggedValue(false) ==
  14226. baseValueType.SetHasNoMissingValues(false).SetCanBeTaggedValue(false)
  14227. ));
  14228. if(doArrayChecks)
  14229. {
  14230. hoistChecksOutOfLoop = loop;
  14231. }
  14232. if(isLikelyJsArray && loopKills.KillsArrayHeadSegments())
  14233. {
  14234. Assert(loopKills.KillsArrayHeadSegmentLengths());
  14235. if(!(doArrayChecks || doLengthLoad))
  14236. {
  14237. break;
  14238. }
  14239. }
  14240. else
  14241. {
  14242. if(doHeadSegmentLoad || headSegmentIsAvailable)
  14243. {
  14244. // If the head segment is already available, we may need to rehoist the value including other
  14245. // information. So, need to track the loop out of which the head segment length can be hoisted even if
  14246. // the head segment length is not being loaded here.
  14247. hoistHeadSegmentLoadOutOfLoop = loop;
  14248. }
  14249. if(isLikelyJsArray
  14250. ? loopKills.KillsArrayHeadSegmentLengths()
  14251. : loopKills.KillsTypedArrayHeadSegmentLengths())
  14252. {
  14253. if(!(doArrayChecks || doHeadSegmentLoad || doLengthLoad))
  14254. {
  14255. break;
  14256. }
  14257. }
  14258. else if(doHeadSegmentLengthLoad || headSegmentLengthIsAvailable)
  14259. {
  14260. // If the head segment length is already available, we may need to rehoist the value including other
  14261. // information. So, need to track the loop out of which the head segment length can be hoisted even if
  14262. // the head segment length is not being loaded here.
  14263. hoistHeadSegmentLengthLoadOutOfLoop = loop;
  14264. }
  14265. }
  14266. if(isLikelyJsArray && loopKills.KillsArrayLengths())
  14267. {
  14268. if(!(doArrayChecks || doHeadSegmentLoad || doHeadSegmentLengthLoad))
  14269. {
  14270. break;
  14271. }
  14272. }
  14273. else if(doLengthLoad || lengthIsAvailable)
  14274. {
  14275. // If the length is already available, we may need to rehoist the value including other information. So,
  14276. // need to track the loop out of which the head segment length can be hoisted even if the length is not
  14277. // being loaded here.
  14278. hoistLengthLoadOutOfLoop = loop;
  14279. }
  14280. }
  14281. }
  14282. IR::Instr *insertBeforeInstr = instr->GetInsertBeforeByteCodeUsesInstr();
  14283. const auto InsertInstrInLandingPad = [&](IR::Instr *const instr, Loop *const hoistOutOfLoop)
  14284. {
  14285. if(hoistOutOfLoop->bailOutInfo->bailOutInstr)
  14286. {
  14287. instr->SetByteCodeOffset(hoistOutOfLoop->bailOutInfo->bailOutInstr);
  14288. hoistOutOfLoop->bailOutInfo->bailOutInstr->InsertBefore(instr);
  14289. }
  14290. else
  14291. {
  14292. instr->SetByteCodeOffset(hoistOutOfLoop->landingPad->GetLastInstr());
  14293. hoistOutOfLoop->landingPad->InsertAfter(instr);
  14294. }
  14295. };
  14296. BailOutInfo *shareableBailOutInfo = nullptr;
  14297. IR::Instr *shareableBailOutInfoOriginalOwner = nullptr;
  14298. const auto ShareBailOut = [&]()
  14299. {
  14300. Assert(shareableBailOutInfo);
  14301. if(shareableBailOutInfo->bailOutInstr != shareableBailOutInfoOriginalOwner)
  14302. {
  14303. return;
  14304. }
  14305. Assert(shareableBailOutInfoOriginalOwner->GetBailOutInfo() == shareableBailOutInfo);
  14306. IR::Instr *const sharedBailOut = shareableBailOutInfoOriginalOwner->ShareBailOut();
  14307. Assert(sharedBailOut->GetBailOutInfo() == shareableBailOutInfo);
  14308. shareableBailOutInfoOriginalOwner = nullptr;
  14309. sharedBailOut->Unlink();
  14310. insertBeforeInstr->InsertBefore(sharedBailOut);
  14311. insertBeforeInstr = sharedBailOut;
  14312. };
  14313. if(doArrayChecks)
  14314. {
  14315. TRACE_TESTTRACE_PHASE_INSTR(Js::ArrayCheckHoistPhase, instr, _u("Separating array checks with bailout\n"));
  14316. IR::Instr *bailOnNotArray = IR::Instr::New(Js::OpCode::BailOnNotArray, instr->m_func);
  14317. bailOnNotArray->SetSrc1(baseOpnd);
  14318. bailOnNotArray->GetSrc1()->SetIsJITOptimizedReg(true);
  14319. const IR::BailOutKind bailOutKind =
  14320. newBaseValueType.IsLikelyNativeArray() ? IR::BailOutOnNotNativeArray : IR::BailOutOnNotArray;
  14321. if(hoistChecksOutOfLoop)
  14322. {
  14323. Assert(!(isLikelyJsArray && hoistChecksOutOfLoop->jsArrayKills.KillsValueType(newBaseValueType)));
  14324. TRACE_PHASE_INSTR(
  14325. Js::ArrayCheckHoistPhase,
  14326. instr,
  14327. _u("Hoisting array checks with bailout out of loop %u to landing pad block %u\n"),
  14328. hoistChecksOutOfLoop->GetLoopNumber(),
  14329. hoistChecksOutOfLoop->landingPad->GetBlockNum());
  14330. TESTTRACE_PHASE_INSTR(Js::ArrayCheckHoistPhase, instr, _u("Hoisting array checks with bailout out of loop\n"));
  14331. Assert(hoistChecksOutOfLoop->bailOutInfo);
  14332. EnsureBailTarget(hoistChecksOutOfLoop);
  14333. InsertInstrInLandingPad(bailOnNotArray, hoistChecksOutOfLoop);
  14334. bailOnNotArray = bailOnNotArray->ConvertToBailOutInstr(hoistChecksOutOfLoop->bailOutInfo, bailOutKind);
  14335. }
  14336. else
  14337. {
  14338. bailOnNotArray->SetByteCodeOffset(instr);
  14339. insertBeforeInstr->InsertBefore(bailOnNotArray);
  14340. GenerateBailAtOperation(&bailOnNotArray, bailOutKind);
  14341. shareableBailOutInfo = bailOnNotArray->GetBailOutInfo();
  14342. shareableBailOutInfoOriginalOwner = bailOnNotArray;
  14343. }
  14344. baseValueType = newBaseValueType;
  14345. baseOpnd->SetValueType(newBaseValueType);
  14346. }
  14347. if(doLengthLoad)
  14348. {
  14349. Assert(baseValueType.IsArray());
  14350. Assert(newLengthSym);
  14351. TRACE_TESTTRACE_PHASE_INSTR(Js::Phase::ArrayLengthHoistPhase, instr, _u("Separating array length load\n"));
  14352. // Create an initial value for the length
  14353. blockData.liveVarSyms->Set(newLengthSym->m_id);
  14354. Value *const lengthValue = NewIntRangeValue(0, INT32_MAX, false);
  14355. SetValue(&blockData, lengthValue, newLengthSym);
  14356. // SetValue above would have set the sym store to newLengthSym. This sym won't be used for copy-prop though, so
  14357. // remove it as the sym store.
  14358. lengthValue->GetValueInfo()->SetSymStore(nullptr);
  14359. // length = [array + offsetOf(length)]
  14360. IR::Instr *const loadLength =
  14361. IR::Instr::New(
  14362. Js::OpCode::LdIndir,
  14363. IR::RegOpnd::New(newLengthSym, newLengthSym->GetType(), instr->m_func),
  14364. IR::IndirOpnd::New(
  14365. baseOpnd,
  14366. Js::JavascriptArray::GetOffsetOfLength(),
  14367. newLengthSym->GetType(),
  14368. instr->m_func),
  14369. instr->m_func);
  14370. loadLength->GetDst()->SetIsJITOptimizedReg(true);
  14371. loadLength->GetSrc1()->AsIndirOpnd()->GetBaseOpnd()->SetIsJITOptimizedReg(true);
  14372. // BailOnNegative length (BailOutOnIrregularLength)
  14373. IR::Instr *bailOnIrregularLength = IR::Instr::New(Js::OpCode::BailOnNegative, instr->m_func);
  14374. bailOnIrregularLength->SetSrc1(loadLength->GetDst());
  14375. const IR::BailOutKind bailOutKind = IR::BailOutOnIrregularLength;
  14376. if(hoistLengthLoadOutOfLoop)
  14377. {
  14378. Assert(!hoistLengthLoadOutOfLoop->jsArrayKills.KillsArrayLengths());
  14379. TRACE_PHASE_INSTR(
  14380. Js::Phase::ArrayLengthHoistPhase,
  14381. instr,
  14382. _u("Hoisting array length load out of loop %u to landing pad block %u\n"),
  14383. hoistLengthLoadOutOfLoop->GetLoopNumber(),
  14384. hoistLengthLoadOutOfLoop->landingPad->GetBlockNum());
  14385. TESTTRACE_PHASE_INSTR(Js::Phase::ArrayLengthHoistPhase, instr, _u("Hoisting array length load out of loop\n"));
  14386. Assert(hoistLengthLoadOutOfLoop->bailOutInfo);
  14387. EnsureBailTarget(hoistLengthLoadOutOfLoop);
  14388. InsertInstrInLandingPad(loadLength, hoistLengthLoadOutOfLoop);
  14389. InsertInstrInLandingPad(bailOnIrregularLength, hoistLengthLoadOutOfLoop);
  14390. bailOnIrregularLength =
  14391. bailOnIrregularLength->ConvertToBailOutInstr(hoistLengthLoadOutOfLoop->bailOutInfo, bailOutKind);
  14392. // Hoist the length value
  14393. for(InvariantBlockBackwardIterator it(
  14394. this,
  14395. currentBlock,
  14396. hoistLengthLoadOutOfLoop->landingPad,
  14397. baseOpnd->m_sym,
  14398. baseValue->GetValueNumber());
  14399. it.IsValid();
  14400. it.MoveNext())
  14401. {
  14402. BasicBlock *const block = it.Block();
  14403. block->globOptData.liveVarSyms->Set(newLengthSym->m_id);
  14404. Assert(!FindValue(block->globOptData.symToValueMap, newLengthSym));
  14405. Value *const lengthValueCopy = CopyValue(lengthValue, lengthValue->GetValueNumber());
  14406. SetValue(&block->globOptData, lengthValueCopy, newLengthSym);
  14407. lengthValueCopy->GetValueInfo()->SetSymStore(nullptr);
  14408. }
  14409. }
  14410. else
  14411. {
  14412. loadLength->SetByteCodeOffset(instr);
  14413. insertBeforeInstr->InsertBefore(loadLength);
  14414. bailOnIrregularLength->SetByteCodeOffset(instr);
  14415. insertBeforeInstr->InsertBefore(bailOnIrregularLength);
  14416. if(shareableBailOutInfo)
  14417. {
  14418. ShareBailOut();
  14419. bailOnIrregularLength = bailOnIrregularLength->ConvertToBailOutInstr(shareableBailOutInfo, bailOutKind);
  14420. }
  14421. else
  14422. {
  14423. GenerateBailAtOperation(&bailOnIrregularLength, bailOutKind);
  14424. shareableBailOutInfo = bailOnIrregularLength->GetBailOutInfo();
  14425. shareableBailOutInfoOriginalOwner = bailOnIrregularLength;
  14426. }
  14427. }
  14428. }
  14429. const auto InsertHeadSegmentLoad = [&]()
  14430. {
  14431. TRACE_TESTTRACE_PHASE_INSTR(Js::ArraySegmentHoistPhase, instr, _u("Separating array segment load\n"));
  14432. Assert(newHeadSegmentSym);
  14433. IR::RegOpnd *const headSegmentOpnd =
  14434. IR::RegOpnd::New(newHeadSegmentSym, newHeadSegmentSym->GetType(), instr->m_func);
  14435. headSegmentOpnd->SetIsJITOptimizedReg(true);
  14436. IR::RegOpnd *const jitOptimizedBaseOpnd = baseOpnd->Copy(instr->m_func)->AsRegOpnd();
  14437. jitOptimizedBaseOpnd->SetIsJITOptimizedReg(true);
  14438. IR::Instr *loadObjectArray;
  14439. if(baseValueType.GetObjectType() == ObjectType::ObjectWithArray)
  14440. {
  14441. loadObjectArray =
  14442. IR::Instr::New(
  14443. Js::OpCode::LdIndir,
  14444. headSegmentOpnd,
  14445. IR::IndirOpnd::New(
  14446. jitOptimizedBaseOpnd,
  14447. Js::DynamicObject::GetOffsetOfObjectArray(),
  14448. jitOptimizedBaseOpnd->GetType(),
  14449. instr->m_func),
  14450. instr->m_func);
  14451. }
  14452. else
  14453. {
  14454. loadObjectArray = nullptr;
  14455. }
  14456. IR::Instr *const loadHeadSegment =
  14457. IR::Instr::New(
  14458. Js::OpCode::LdIndir,
  14459. headSegmentOpnd,
  14460. IR::IndirOpnd::New(
  14461. loadObjectArray ? headSegmentOpnd : jitOptimizedBaseOpnd,
  14462. Lowerer::GetArrayOffsetOfHeadSegment(baseValueType),
  14463. headSegmentOpnd->GetType(),
  14464. instr->m_func),
  14465. instr->m_func);
  14466. if(hoistHeadSegmentLoadOutOfLoop)
  14467. {
  14468. Assert(!(isLikelyJsArray && hoistHeadSegmentLoadOutOfLoop->jsArrayKills.KillsArrayHeadSegments()));
  14469. TRACE_PHASE_INSTR(
  14470. Js::ArraySegmentHoistPhase,
  14471. instr,
  14472. _u("Hoisting array segment load out of loop %u to landing pad block %u\n"),
  14473. hoistHeadSegmentLoadOutOfLoop->GetLoopNumber(),
  14474. hoistHeadSegmentLoadOutOfLoop->landingPad->GetBlockNum());
  14475. TESTTRACE_PHASE_INSTR(Js::ArraySegmentHoistPhase, instr, _u("Hoisting array segment load out of loop\n"));
  14476. if(loadObjectArray)
  14477. {
  14478. InsertInstrInLandingPad(loadObjectArray, hoistHeadSegmentLoadOutOfLoop);
  14479. }
  14480. InsertInstrInLandingPad(loadHeadSegment, hoistHeadSegmentLoadOutOfLoop);
  14481. }
  14482. else
  14483. {
  14484. if(loadObjectArray)
  14485. {
  14486. loadObjectArray->SetByteCodeOffset(instr);
  14487. insertBeforeInstr->InsertBefore(loadObjectArray);
  14488. }
  14489. loadHeadSegment->SetByteCodeOffset(instr);
  14490. insertBeforeInstr->InsertBefore(loadHeadSegment);
  14491. instr->loadedArrayHeadSegment = true;
  14492. }
  14493. };
  14494. if(doHeadSegmentLoad && isLikelyJsArray)
  14495. {
  14496. // For javascript arrays, the head segment is required to load the head segment length
  14497. InsertHeadSegmentLoad();
  14498. }
  14499. if(doHeadSegmentLengthLoad)
  14500. {
  14501. Assert(!isLikelyJsArray || newHeadSegmentSym || baseArrayValueInfo && baseArrayValueInfo->HeadSegmentSym());
  14502. Assert(newHeadSegmentLengthSym);
  14503. Assert(!headSegmentLengthValue);
  14504. TRACE_TESTTRACE_PHASE_INSTR(Js::ArraySegmentHoistPhase, instr, _u("Separating array segment length load\n"));
  14505. // Create an initial value for the head segment length
  14506. blockData.liveVarSyms->Set(newHeadSegmentLengthSym->m_id);
  14507. headSegmentLengthValue = NewIntRangeValue(0, Js::SparseArraySegmentBase::MaxLength, false);
  14508. headSegmentLengthConstantBounds = IntConstantBounds(0, Js::SparseArraySegmentBase::MaxLength);
  14509. SetValue(&blockData, headSegmentLengthValue, newHeadSegmentLengthSym);
  14510. // SetValue above would have set the sym store to newHeadSegmentLengthSym. This sym won't be used for copy-prop
  14511. // though, so remove it as the sym store.
  14512. headSegmentLengthValue->GetValueInfo()->SetSymStore(nullptr);
  14513. StackSym *const headSegmentSym =
  14514. isLikelyJsArray
  14515. ? newHeadSegmentSym ? newHeadSegmentSym : baseArrayValueInfo->HeadSegmentSym()
  14516. : nullptr;
  14517. IR::Instr *const loadHeadSegmentLength =
  14518. IR::Instr::New(
  14519. Js::OpCode::LdIndir,
  14520. IR::RegOpnd::New(newHeadSegmentLengthSym, newHeadSegmentLengthSym->GetType(), instr->m_func),
  14521. IR::IndirOpnd::New(
  14522. isLikelyJsArray ? IR::RegOpnd::New(headSegmentSym, headSegmentSym->GetType(), instr->m_func) : baseOpnd,
  14523. isLikelyJsArray
  14524. ? Js::SparseArraySegmentBase::GetOffsetOfLength()
  14525. : Lowerer::GetArrayOffsetOfLength(baseValueType),
  14526. newHeadSegmentLengthSym->GetType(),
  14527. instr->m_func),
  14528. instr->m_func);
  14529. loadHeadSegmentLength->GetDst()->SetIsJITOptimizedReg(true);
  14530. loadHeadSegmentLength->GetSrc1()->AsIndirOpnd()->GetBaseOpnd()->SetIsJITOptimizedReg(true);
  14531. // We don't check the head segment length for negative (very large uint32) values. For JS arrays, the bound checks
  14532. // cover that. For typed arrays, we currently don't allocate array buffers with more than 1 GB elements.
  14533. if(hoistHeadSegmentLengthLoadOutOfLoop)
  14534. {
  14535. Assert(
  14536. !(
  14537. isLikelyJsArray
  14538. ? hoistHeadSegmentLengthLoadOutOfLoop->jsArrayKills.KillsArrayHeadSegmentLengths()
  14539. : hoistHeadSegmentLengthLoadOutOfLoop->jsArrayKills.KillsTypedArrayHeadSegmentLengths()
  14540. ));
  14541. TRACE_PHASE_INSTR(
  14542. Js::ArraySegmentHoistPhase,
  14543. instr,
  14544. _u("Hoisting array segment length load out of loop %u to landing pad block %u\n"),
  14545. hoistHeadSegmentLengthLoadOutOfLoop->GetLoopNumber(),
  14546. hoistHeadSegmentLengthLoadOutOfLoop->landingPad->GetBlockNum());
  14547. TESTTRACE_PHASE_INSTR(Js::ArraySegmentHoistPhase, instr, _u("Hoisting array segment length load out of loop\n"));
  14548. InsertInstrInLandingPad(loadHeadSegmentLength, hoistHeadSegmentLengthLoadOutOfLoop);
  14549. // Hoist the head segment length value
  14550. for(InvariantBlockBackwardIterator it(
  14551. this,
  14552. currentBlock,
  14553. hoistHeadSegmentLengthLoadOutOfLoop->landingPad,
  14554. baseOpnd->m_sym,
  14555. baseValue->GetValueNumber());
  14556. it.IsValid();
  14557. it.MoveNext())
  14558. {
  14559. BasicBlock *const block = it.Block();
  14560. block->globOptData.liveVarSyms->Set(newHeadSegmentLengthSym->m_id);
  14561. Assert(!FindValue(block->globOptData.symToValueMap, newHeadSegmentLengthSym));
  14562. Value *const headSegmentLengthValueCopy =
  14563. CopyValue(headSegmentLengthValue, headSegmentLengthValue->GetValueNumber());
  14564. SetValue(&block->globOptData, headSegmentLengthValueCopy, newHeadSegmentLengthSym);
  14565. headSegmentLengthValueCopy->GetValueInfo()->SetSymStore(nullptr);
  14566. }
  14567. }
  14568. else
  14569. {
  14570. loadHeadSegmentLength->SetByteCodeOffset(instr);
  14571. insertBeforeInstr->InsertBefore(loadHeadSegmentLength);
  14572. instr->loadedArrayHeadSegmentLength = true;
  14573. }
  14574. }
  14575. if(doExtractBoundChecks)
  14576. {
  14577. Assert(!(eliminatedLowerBoundCheck && eliminatedUpperBoundCheck));
  14578. Assert(baseOwnerIndir);
  14579. Assert(!baseOwnerIndir->GetIndexOpnd() || baseOwnerIndir->GetIndexOpnd()->m_sym->IsTypeSpec());
  14580. Assert(doHeadSegmentLengthLoad || headSegmentLengthIsAvailable);
  14581. Assert(canBailOutOnArrayAccessHelperCall);
  14582. Assert(!isStore || instr->m_opcode == Js::OpCode::StElemI_A || instr->m_opcode == Js::OpCode::StElemI_A_Strict || Js::IsSimd128LoadStore(instr->m_opcode));
  14583. StackSym *const headSegmentLengthSym =
  14584. headSegmentLengthIsAvailable ? baseArrayValueInfo->HeadSegmentLengthSym() : newHeadSegmentLengthSym;
  14585. Assert(headSegmentLengthSym);
  14586. Assert(headSegmentLengthValue);
  14587. ArrayLowerBoundCheckHoistInfo lowerBoundCheckHoistInfo;
  14588. ArrayUpperBoundCheckHoistInfo upperBoundCheckHoistInfo;
  14589. bool failedToUpdateCompatibleLowerBoundCheck = false, failedToUpdateCompatibleUpperBoundCheck = false;
  14590. if(DoBoundCheckHoist())
  14591. {
  14592. if(indexVarSym)
  14593. {
  14594. TRACE_PHASE_INSTR_VERBOSE(
  14595. Js::Phase::BoundCheckHoistPhase,
  14596. instr,
  14597. _u("Determining array bound check hoistability for index s%u\n"),
  14598. indexVarSym->m_id);
  14599. }
  14600. else
  14601. {
  14602. TRACE_PHASE_INSTR_VERBOSE(
  14603. Js::Phase::BoundCheckHoistPhase,
  14604. instr,
  14605. _u("Determining array bound check hoistability for index %d\n"),
  14606. indexConstantBounds.LowerBound());
  14607. }
  14608. DetermineArrayBoundCheckHoistability(
  14609. !eliminatedLowerBoundCheck,
  14610. !eliminatedUpperBoundCheck,
  14611. lowerBoundCheckHoistInfo,
  14612. upperBoundCheckHoistInfo,
  14613. isLikelyJsArray,
  14614. indexVarSym,
  14615. indexValue,
  14616. indexConstantBounds,
  14617. headSegmentLengthSym,
  14618. headSegmentLengthValue,
  14619. headSegmentLengthConstantBounds,
  14620. hoistHeadSegmentLengthLoadOutOfLoop,
  14621. failedToUpdateCompatibleLowerBoundCheck,
  14622. failedToUpdateCompatibleUpperBoundCheck);
  14623. // SIMD_JS
  14624. UpdateBoundCheckHoistInfoForSimd(upperBoundCheckHoistInfo, newBaseValueType, instr);
  14625. }
  14626. if(!eliminatedLowerBoundCheck)
  14627. {
  14628. eliminatedLowerBoundCheck = true;
  14629. Assert(indexVarSym);
  14630. Assert(baseOwnerIndir->GetIndexOpnd());
  14631. Assert(indexValue);
  14632. ArrayLowerBoundCheckHoistInfo &hoistInfo = lowerBoundCheckHoistInfo;
  14633. if(hoistInfo.HasAnyInfo())
  14634. {
  14635. BasicBlock *hoistBlock;
  14636. if(hoistInfo.CompatibleBoundCheckBlock())
  14637. {
  14638. hoistBlock = hoistInfo.CompatibleBoundCheckBlock();
  14639. TRACE_PHASE_INSTR(
  14640. Js::Phase::BoundCheckHoistPhase,
  14641. instr,
  14642. _u("Hoisting array lower bound check into existing bound check instruction in block %u\n"),
  14643. hoistBlock->GetBlockNum());
  14644. TESTTRACE_PHASE_INSTR(
  14645. Js::Phase::BoundCheckHoistPhase,
  14646. instr,
  14647. _u("Hoisting array lower bound check into existing bound check instruction\n"));
  14648. }
  14649. else
  14650. {
  14651. Assert(hoistInfo.Loop());
  14652. BasicBlock *const landingPad = hoistInfo.Loop()->landingPad;
  14653. hoistBlock = landingPad;
  14654. StackSym *indexIntSym;
  14655. if(hoistInfo.IndexSym() && hoistInfo.IndexSym()->IsVar())
  14656. {
  14657. if(!IsInt32TypeSpecialized(hoistInfo.IndexSym(), landingPad))
  14658. {
  14659. // Int-specialize the index sym, as the BoundCheck instruction requires int operands. Specialize
  14660. // it in this block if it is invariant, as the conversion will be hoisted along with value
  14661. // updates.
  14662. BasicBlock *specializationBlock = hoistInfo.Loop()->landingPad;
  14663. IR::Instr *specializeBeforeInstr = nullptr;
  14664. if(!IsInt32TypeSpecialized(hoistInfo.IndexSym(), &blockData) &&
  14665. OptIsInvariant(
  14666. hoistInfo.IndexSym(),
  14667. currentBlock,
  14668. hoistInfo.Loop(),
  14669. FindValue(hoistInfo.IndexSym()),
  14670. false,
  14671. true))
  14672. {
  14673. specializationBlock = currentBlock;
  14674. specializeBeforeInstr = insertBeforeInstr;
  14675. }
  14676. Assert(tempBv->IsEmpty());
  14677. tempBv->Set(hoistInfo.IndexSym()->m_id);
  14678. ToInt32(tempBv, specializationBlock, false, specializeBeforeInstr);
  14679. tempBv->ClearAll();
  14680. Assert(IsInt32TypeSpecialized(hoistInfo.IndexSym(), landingPad));
  14681. }
  14682. indexIntSym = hoistInfo.IndexSym()->GetInt32EquivSym(nullptr);
  14683. Assert(indexIntSym);
  14684. }
  14685. else
  14686. {
  14687. indexIntSym = hoistInfo.IndexSym();
  14688. Assert(!indexIntSym || indexIntSym->GetType() == TyInt32 || indexIntSym->GetType() == TyUint32);
  14689. }
  14690. // The info in the landing pad may be better than the info in the current block due to changes made to
  14691. // the index sym inside the loop. Check if the bound check we intend to hoist is unnecessary in the
  14692. // landing pad.
  14693. if(!ValueInfo::IsLessThanOrEqualTo(
  14694. nullptr,
  14695. 0,
  14696. 0,
  14697. hoistInfo.IndexValue(),
  14698. hoistInfo.IndexConstantBounds().LowerBound(),
  14699. hoistInfo.IndexConstantBounds().UpperBound(),
  14700. hoistInfo.Offset()))
  14701. {
  14702. Assert(hoistInfo.IndexSym());
  14703. Assert(hoistInfo.Loop()->bailOutInfo);
  14704. EnsureBailTarget(hoistInfo.Loop());
  14705. if(hoistInfo.LoopCount())
  14706. {
  14707. // Generate the loop count and loop count based bound that will be used for the bound check
  14708. if(!hoistInfo.LoopCount()->HasBeenGenerated())
  14709. {
  14710. GenerateLoopCount(hoistInfo.Loop(), hoistInfo.LoopCount());
  14711. }
  14712. GenerateSecondaryInductionVariableBound(
  14713. hoistInfo.Loop(),
  14714. indexVarSym->GetInt32EquivSym(nullptr),
  14715. hoistInfo.LoopCount(),
  14716. hoistInfo.MaxMagnitudeChange(),
  14717. hoistInfo.IndexSym());
  14718. }
  14719. IR::Opnd* lowerBound = IR::IntConstOpnd::New(0, TyInt32, instr->m_func, true);
  14720. IR::Opnd* upperBound = IR::RegOpnd::New(indexIntSym, TyInt32, instr->m_func);
  14721. upperBound->SetIsJITOptimizedReg(true);
  14722. // 0 <= indexSym + offset (src1 <= src2 + dst)
  14723. IR::Instr *const boundCheck = CreateBoundsCheckInstr(
  14724. lowerBound,
  14725. upperBound,
  14726. hoistInfo.Offset(),
  14727. hoistInfo.IsLoopCountBasedBound()
  14728. ? IR::BailOutOnFailedHoistedLoopCountBasedBoundCheck
  14729. : IR::BailOutOnFailedHoistedBoundCheck,
  14730. hoistInfo.Loop()->bailOutInfo,
  14731. hoistInfo.Loop()->bailOutInfo->bailOutFunc);
  14732. InsertInstrInLandingPad(boundCheck, hoistInfo.Loop());
  14733. TRACE_PHASE_INSTR(
  14734. Js::Phase::BoundCheckHoistPhase,
  14735. instr,
  14736. _u("Hoisting array lower bound check out of loop %u to landing pad block %u, as (0 <= s%u + %d)\n"),
  14737. hoistInfo.Loop()->GetLoopNumber(),
  14738. landingPad->GetBlockNum(),
  14739. hoistInfo.IndexSym()->m_id,
  14740. hoistInfo.Offset());
  14741. TESTTRACE_PHASE_INSTR(
  14742. Js::Phase::BoundCheckHoistPhase,
  14743. instr,
  14744. _u("Hoisting array lower bound check out of loop\n"));
  14745. // Record the bound check instruction as available
  14746. const IntBoundCheck boundCheckInfo(
  14747. ZeroValueNumber,
  14748. hoistInfo.IndexValueNumber(),
  14749. boundCheck,
  14750. landingPad);
  14751. const bool added = blockData.availableIntBoundChecks->AddNew(boundCheckInfo) >= 0;
  14752. Assert(added || failedToUpdateCompatibleLowerBoundCheck);
  14753. for(InvariantBlockBackwardIterator it(this, currentBlock, landingPad, nullptr);
  14754. it.IsValid();
  14755. it.MoveNext())
  14756. {
  14757. const bool added = it.Block()->globOptData.availableIntBoundChecks->AddNew(boundCheckInfo) >= 0;
  14758. Assert(added || failedToUpdateCompatibleLowerBoundCheck);
  14759. }
  14760. }
  14761. }
  14762. // Update values of the syms involved in the bound check to reflect the bound check
  14763. if(hoistBlock != currentBlock && hoistInfo.IndexSym() && hoistInfo.Offset() != INT32_MIN)
  14764. {
  14765. for(InvariantBlockBackwardIterator it(
  14766. this,
  14767. currentBlock->next,
  14768. hoistBlock,
  14769. hoistInfo.IndexSym(),
  14770. hoistInfo.IndexValueNumber());
  14771. it.IsValid();
  14772. it.MoveNext())
  14773. {
  14774. Value *const value = it.InvariantSymValue();
  14775. IntConstantBounds constantBounds;
  14776. AssertVerify(value->GetValueInfo()->TryGetIntConstantBounds(&constantBounds, true));
  14777. ValueInfo *const newValueInfo =
  14778. UpdateIntBoundsForGreaterThanOrEqual(
  14779. value,
  14780. constantBounds,
  14781. nullptr,
  14782. IntConstantBounds(-hoistInfo.Offset(), -hoistInfo.Offset()),
  14783. false);
  14784. if(newValueInfo)
  14785. {
  14786. ChangeValueInfo(nullptr, value, newValueInfo);
  14787. if(it.Block() == currentBlock && value == indexValue)
  14788. {
  14789. AssertVerify(newValueInfo->TryGetIntConstantBounds(&indexConstantBounds));
  14790. }
  14791. }
  14792. }
  14793. }
  14794. }
  14795. else
  14796. {
  14797. IR::Opnd* lowerBound = IR::IntConstOpnd::New(0, TyInt32, instr->m_func, true);
  14798. IR::Opnd* upperBound = baseOwnerIndir->GetIndexOpnd();
  14799. upperBound->SetIsJITOptimizedReg(true);
  14800. const int offset = 0;
  14801. IR::Instr *boundCheck;
  14802. if(shareableBailOutInfo)
  14803. {
  14804. ShareBailOut();
  14805. boundCheck = CreateBoundsCheckInstr(
  14806. lowerBound,
  14807. upperBound,
  14808. offset,
  14809. IR::BailOutOnArrayAccessHelperCall,
  14810. shareableBailOutInfo,
  14811. shareableBailOutInfo->bailOutFunc);
  14812. }
  14813. else
  14814. {
  14815. boundCheck = CreateBoundsCheckInstr(
  14816. lowerBound,
  14817. upperBound,
  14818. offset,
  14819. instr->m_func);
  14820. }
  14821. boundCheck->SetByteCodeOffset(instr);
  14822. insertBeforeInstr->InsertBefore(boundCheck);
  14823. if(!shareableBailOutInfo)
  14824. {
  14825. GenerateBailAtOperation(&boundCheck, IR::BailOutOnArrayAccessHelperCall);
  14826. shareableBailOutInfo = boundCheck->GetBailOutInfo();
  14827. shareableBailOutInfoOriginalOwner = boundCheck;
  14828. }
  14829. TRACE_PHASE_INSTR(
  14830. Js::Phase::BoundCheckEliminationPhase,
  14831. instr,
  14832. _u("Separating array lower bound check, as (0 <= s%u)\n"),
  14833. indexVarSym->m_id);
  14834. TESTTRACE_PHASE_INSTR(
  14835. Js::Phase::BoundCheckEliminationPhase,
  14836. instr,
  14837. _u("Separating array lower bound check\n"));
  14838. if(DoBoundCheckHoist())
  14839. {
  14840. // Record the bound check instruction as available
  14841. const bool added =
  14842. blockData.availableIntBoundChecks->AddNew(
  14843. IntBoundCheck(ZeroValueNumber, indexValue->GetValueNumber(), boundCheck, currentBlock)) >= 0;
  14844. Assert(added || failedToUpdateCompatibleLowerBoundCheck);
  14845. }
  14846. }
  14847. // Update the index value to reflect the bound check
  14848. ValueInfo *const newValueInfo =
  14849. UpdateIntBoundsForGreaterThanOrEqual(
  14850. indexValue,
  14851. indexConstantBounds,
  14852. nullptr,
  14853. IntConstantBounds(0, 0),
  14854. false);
  14855. if(newValueInfo)
  14856. {
  14857. ChangeValueInfo(nullptr, indexValue, newValueInfo);
  14858. AssertVerify(newValueInfo->TryGetIntConstantBounds(&indexConstantBounds));
  14859. }
  14860. }
  14861. if(!eliminatedUpperBoundCheck)
  14862. {
  14863. eliminatedUpperBoundCheck = true;
  14864. ArrayUpperBoundCheckHoistInfo &hoistInfo = upperBoundCheckHoistInfo;
  14865. if(hoistInfo.HasAnyInfo())
  14866. {
  14867. BasicBlock *hoistBlock;
  14868. if(hoistInfo.CompatibleBoundCheckBlock())
  14869. {
  14870. hoistBlock = hoistInfo.CompatibleBoundCheckBlock();
  14871. TRACE_PHASE_INSTR(
  14872. Js::Phase::BoundCheckHoistPhase,
  14873. instr,
  14874. _u("Hoisting array upper bound check into existing bound check instruction in block %u\n"),
  14875. hoistBlock->GetBlockNum());
  14876. TESTTRACE_PHASE_INSTR(
  14877. Js::Phase::BoundCheckHoistPhase,
  14878. instr,
  14879. _u("Hoisting array upper bound check into existing bound check instruction\n"));
  14880. }
  14881. else
  14882. {
  14883. Assert(hoistInfo.Loop());
  14884. BasicBlock *const landingPad = hoistInfo.Loop()->landingPad;
  14885. hoistBlock = landingPad;
  14886. StackSym *indexIntSym;
  14887. if(hoistInfo.IndexSym() && hoistInfo.IndexSym()->IsVar())
  14888. {
  14889. if(!IsInt32TypeSpecialized(hoistInfo.IndexSym(), landingPad))
  14890. {
  14891. // Int-specialize the index sym, as the BoundCheck instruction requires int operands. Specialize it
  14892. // in this block if it is invariant, as the conversion will be hoisted along with value updates.
  14893. BasicBlock *specializationBlock = hoistInfo.Loop()->landingPad;
  14894. IR::Instr *specializeBeforeInstr = nullptr;
  14895. if(!IsInt32TypeSpecialized(hoistInfo.IndexSym(), &blockData) &&
  14896. OptIsInvariant(
  14897. hoistInfo.IndexSym(),
  14898. currentBlock,
  14899. hoistInfo.Loop(),
  14900. FindValue(hoistInfo.IndexSym()),
  14901. false,
  14902. true))
  14903. {
  14904. specializationBlock = currentBlock;
  14905. specializeBeforeInstr = insertBeforeInstr;
  14906. }
  14907. Assert(tempBv->IsEmpty());
  14908. tempBv->Set(hoistInfo.IndexSym()->m_id);
  14909. ToInt32(tempBv, specializationBlock, false, specializeBeforeInstr);
  14910. tempBv->ClearAll();
  14911. Assert(IsInt32TypeSpecialized(hoistInfo.IndexSym(), landingPad));
  14912. }
  14913. indexIntSym = hoistInfo.IndexSym()->GetInt32EquivSym(nullptr);
  14914. Assert(indexIntSym);
  14915. }
  14916. else
  14917. {
  14918. indexIntSym = hoistInfo.IndexSym();
  14919. Assert(!indexIntSym || indexIntSym->GetType() == TyInt32 || indexIntSym->GetType() == TyUint32);
  14920. }
  14921. // The info in the landing pad may be better than the info in the current block due to changes made to the
  14922. // index sym inside the loop. Check if the bound check we intend to hoist is unnecessary in the landing pad.
  14923. if(!ValueInfo::IsLessThanOrEqualTo(
  14924. hoistInfo.IndexValue(),
  14925. hoistInfo.IndexConstantBounds().LowerBound(),
  14926. hoistInfo.IndexConstantBounds().UpperBound(),
  14927. hoistInfo.HeadSegmentLengthValue(),
  14928. hoistInfo.HeadSegmentLengthConstantBounds().LowerBound(),
  14929. hoistInfo.HeadSegmentLengthConstantBounds().UpperBound(),
  14930. hoistInfo.Offset()))
  14931. {
  14932. Assert(hoistInfo.Loop()->bailOutInfo);
  14933. EnsureBailTarget(hoistInfo.Loop());
  14934. if(hoistInfo.LoopCount())
  14935. {
  14936. // Generate the loop count and loop count based bound that will be used for the bound check
  14937. if(!hoistInfo.LoopCount()->HasBeenGenerated())
  14938. {
  14939. GenerateLoopCount(hoistInfo.Loop(), hoistInfo.LoopCount());
  14940. }
  14941. GenerateSecondaryInductionVariableBound(
  14942. hoistInfo.Loop(),
  14943. indexVarSym->GetInt32EquivSym(nullptr),
  14944. hoistInfo.LoopCount(),
  14945. hoistInfo.MaxMagnitudeChange(),
  14946. hoistInfo.IndexSym());
  14947. }
  14948. IR::Opnd* lowerBound = indexIntSym
  14949. ? static_cast<IR::Opnd *>(IR::RegOpnd::New(indexIntSym, TyInt32, instr->m_func))
  14950. : IR::IntConstOpnd::New(
  14951. hoistInfo.IndexConstantBounds().LowerBound(),
  14952. TyInt32,
  14953. instr->m_func,
  14954. true);
  14955. lowerBound->SetIsJITOptimizedReg(true);
  14956. IR::Opnd* upperBound = IR::RegOpnd::New(headSegmentLengthSym, headSegmentLengthSym->GetType(), instr->m_func);
  14957. upperBound->SetIsJITOptimizedReg(true);
  14958. // indexSym <= headSegmentLength + offset (src1 <= src2 + dst)
  14959. IR::Instr *const boundCheck = CreateBoundsCheckInstr(
  14960. lowerBound,
  14961. upperBound,
  14962. hoistInfo.Offset(),
  14963. hoistInfo.IsLoopCountBasedBound()
  14964. ? IR::BailOutOnFailedHoistedLoopCountBasedBoundCheck
  14965. : IR::BailOutOnFailedHoistedBoundCheck,
  14966. hoistInfo.Loop()->bailOutInfo,
  14967. hoistInfo.Loop()->bailOutInfo->bailOutFunc);
  14968. InsertInstrInLandingPad(boundCheck, hoistInfo.Loop());
  14969. if(indexIntSym)
  14970. {
  14971. TRACE_PHASE_INSTR(
  14972. Js::Phase::BoundCheckHoistPhase,
  14973. instr,
  14974. _u("Hoisting array upper bound check out of loop %u to landing pad block %u, as (s%u <= s%u + %d)\n"),
  14975. hoistInfo.Loop()->GetLoopNumber(),
  14976. landingPad->GetBlockNum(),
  14977. hoistInfo.IndexSym()->m_id,
  14978. headSegmentLengthSym->m_id,
  14979. hoistInfo.Offset());
  14980. }
  14981. else
  14982. {
  14983. TRACE_PHASE_INSTR(
  14984. Js::Phase::BoundCheckHoistPhase,
  14985. instr,
  14986. _u("Hoisting array upper bound check out of loop %u to landing pad block %u, as (%d <= s%u + %d)\n"),
  14987. hoistInfo.Loop()->GetLoopNumber(),
  14988. landingPad->GetBlockNum(),
  14989. hoistInfo.IndexConstantBounds().LowerBound(),
  14990. headSegmentLengthSym->m_id,
  14991. hoistInfo.Offset());
  14992. }
  14993. TESTTRACE_PHASE_INSTR(
  14994. Js::Phase::BoundCheckHoistPhase,
  14995. instr,
  14996. _u("Hoisting array upper bound check out of loop\n"));
  14997. // Record the bound check instruction as available
  14998. const IntBoundCheck boundCheckInfo(
  14999. hoistInfo.IndexValue() ? hoistInfo.IndexValueNumber() : ZeroValueNumber,
  15000. hoistInfo.HeadSegmentLengthValue()->GetValueNumber(),
  15001. boundCheck,
  15002. landingPad);
  15003. const bool added = blockData.availableIntBoundChecks->AddNew(boundCheckInfo) >= 0;
  15004. Assert(added || failedToUpdateCompatibleUpperBoundCheck);
  15005. for(InvariantBlockBackwardIterator it(this, currentBlock, landingPad, nullptr);
  15006. it.IsValid();
  15007. it.MoveNext())
  15008. {
  15009. const bool added = it.Block()->globOptData.availableIntBoundChecks->AddNew(boundCheckInfo) >= 0;
  15010. Assert(added || failedToUpdateCompatibleUpperBoundCheck);
  15011. }
  15012. }
  15013. }
  15014. // Update values of the syms involved in the bound check to reflect the bound check
  15015. Assert(!hoistInfo.Loop() || hoistBlock != currentBlock);
  15016. if(hoistBlock != currentBlock)
  15017. {
  15018. for(InvariantBlockBackwardIterator it(this, currentBlock->next, hoistBlock, nullptr);
  15019. it.IsValid();
  15020. it.MoveNext())
  15021. {
  15022. BasicBlock *const block = it.Block();
  15023. Value *leftValue;
  15024. IntConstantBounds leftConstantBounds;
  15025. if(hoistInfo.IndexSym())
  15026. {
  15027. leftValue = FindValue(block->globOptData.symToValueMap, hoistInfo.IndexSym());
  15028. if(!leftValue || leftValue->GetValueNumber() != hoistInfo.IndexValueNumber())
  15029. {
  15030. continue;
  15031. }
  15032. AssertVerify(leftValue->GetValueInfo()->TryGetIntConstantBounds(&leftConstantBounds, true));
  15033. }
  15034. else
  15035. {
  15036. leftValue = nullptr;
  15037. leftConstantBounds = hoistInfo.IndexConstantBounds();
  15038. }
  15039. Value *const rightValue = FindValue(block->globOptData.symToValueMap, headSegmentLengthSym);
  15040. if(!rightValue)
  15041. {
  15042. continue;
  15043. }
  15044. Assert(rightValue->GetValueNumber() == headSegmentLengthValue->GetValueNumber());
  15045. IntConstantBounds rightConstantBounds;
  15046. AssertVerify(rightValue->GetValueInfo()->TryGetIntConstantBounds(&rightConstantBounds));
  15047. ValueInfo *const newValueInfo =
  15048. UpdateIntBoundsForLessThanOrEqual(
  15049. leftValue,
  15050. leftConstantBounds,
  15051. rightValue,
  15052. rightConstantBounds,
  15053. hoistInfo.Offset(),
  15054. false);
  15055. if(newValueInfo)
  15056. {
  15057. ChangeValueInfo(nullptr, leftValue, newValueInfo);
  15058. AssertVerify(newValueInfo->TryGetIntConstantBounds(&leftConstantBounds, true));
  15059. if(block == currentBlock && leftValue == indexValue)
  15060. {
  15061. Assert(newValueInfo->IsInt());
  15062. indexConstantBounds = leftConstantBounds;
  15063. }
  15064. }
  15065. if(hoistInfo.Offset() != INT32_MIN)
  15066. {
  15067. ValueInfo *const newValueInfo =
  15068. UpdateIntBoundsForGreaterThanOrEqual(
  15069. rightValue,
  15070. rightConstantBounds,
  15071. leftValue,
  15072. leftConstantBounds,
  15073. -hoistInfo.Offset(),
  15074. false);
  15075. if(newValueInfo)
  15076. {
  15077. ChangeValueInfo(nullptr, rightValue, newValueInfo);
  15078. if(block == currentBlock)
  15079. {
  15080. Assert(rightValue == headSegmentLengthValue);
  15081. AssertVerify(newValueInfo->TryGetIntConstantBounds(&headSegmentLengthConstantBounds));
  15082. }
  15083. }
  15084. }
  15085. }
  15086. }
  15087. }
  15088. else
  15089. {
  15090. IR::Opnd* lowerBound = baseOwnerIndir->GetIndexOpnd()
  15091. ? static_cast<IR::Opnd *>(baseOwnerIndir->GetIndexOpnd())
  15092. : IR::IntConstOpnd::New(baseOwnerIndir->GetOffset(), TyInt32, instr->m_func, true);
  15093. lowerBound->SetIsJITOptimizedReg(true);
  15094. IR::Opnd* upperBound = IR::RegOpnd::New(headSegmentLengthSym, headSegmentLengthSym->GetType(), instr->m_func);
  15095. upperBound->SetIsJITOptimizedReg(true);
  15096. const int offset = GetBoundCheckOffsetForSimd(newBaseValueType, instr, -1);
  15097. IR::Instr *boundCheck;
  15098. // index <= headSegmentLength - 1 (src1 <= src2 + dst)
  15099. if (shareableBailOutInfo)
  15100. {
  15101. ShareBailOut();
  15102. boundCheck = CreateBoundsCheckInstr(
  15103. lowerBound,
  15104. upperBound,
  15105. offset,
  15106. IR::BailOutOnArrayAccessHelperCall,
  15107. shareableBailOutInfo,
  15108. shareableBailOutInfo->bailOutFunc);
  15109. }
  15110. else
  15111. {
  15112. boundCheck = CreateBoundsCheckInstr(
  15113. lowerBound,
  15114. upperBound,
  15115. offset,
  15116. instr->m_func);
  15117. }
  15118. boundCheck->SetByteCodeOffset(instr);
  15119. insertBeforeInstr->InsertBefore(boundCheck);
  15120. if(!shareableBailOutInfo)
  15121. {
  15122. GenerateBailAtOperation(&boundCheck, IR::BailOutOnArrayAccessHelperCall);
  15123. shareableBailOutInfo = boundCheck->GetBailOutInfo();
  15124. shareableBailOutInfoOriginalOwner = boundCheck;
  15125. }
  15126. instr->extractedUpperBoundCheckWithoutHoisting = true;
  15127. if(baseOwnerIndir->GetIndexOpnd())
  15128. {
  15129. TRACE_PHASE_INSTR(
  15130. Js::Phase::BoundCheckEliminationPhase,
  15131. instr,
  15132. _u("Separating array upper bound check, as (s%u < s%u)\n"),
  15133. indexVarSym->m_id,
  15134. headSegmentLengthSym->m_id);
  15135. }
  15136. else
  15137. {
  15138. TRACE_PHASE_INSTR(
  15139. Js::Phase::BoundCheckEliminationPhase,
  15140. instr,
  15141. _u("Separating array upper bound check, as (%d < s%u)\n"),
  15142. baseOwnerIndir->GetOffset(),
  15143. headSegmentLengthSym->m_id);
  15144. }
  15145. TESTTRACE_PHASE_INSTR(
  15146. Js::Phase::BoundCheckEliminationPhase,
  15147. instr,
  15148. _u("Separating array upper bound check\n"));
  15149. if(DoBoundCheckHoist())
  15150. {
  15151. // Record the bound check instruction as available
  15152. const bool added =
  15153. blockData.availableIntBoundChecks->AddNew(
  15154. IntBoundCheck(
  15155. indexValue ? indexValue->GetValueNumber() : ZeroValueNumber,
  15156. headSegmentLengthValue->GetValueNumber(),
  15157. boundCheck,
  15158. currentBlock)) >= 0;
  15159. Assert(added || failedToUpdateCompatibleUpperBoundCheck);
  15160. }
  15161. }
  15162. // Update the index and head segment length values to reflect the bound check
  15163. ValueInfo *newValueInfo =
  15164. UpdateIntBoundsForLessThan(
  15165. indexValue,
  15166. indexConstantBounds,
  15167. headSegmentLengthValue,
  15168. headSegmentLengthConstantBounds,
  15169. false);
  15170. if(newValueInfo)
  15171. {
  15172. ChangeValueInfo(nullptr, indexValue, newValueInfo);
  15173. AssertVerify(newValueInfo->TryGetIntConstantBounds(&indexConstantBounds));
  15174. }
  15175. newValueInfo =
  15176. UpdateIntBoundsForGreaterThan(
  15177. headSegmentLengthValue,
  15178. headSegmentLengthConstantBounds,
  15179. indexValue,
  15180. indexConstantBounds,
  15181. false);
  15182. if(newValueInfo)
  15183. {
  15184. ChangeValueInfo(nullptr, headSegmentLengthValue, newValueInfo);
  15185. }
  15186. }
  15187. }
  15188. if(doHeadSegmentLoad && !isLikelyJsArray)
  15189. {
  15190. // For typed arrays, load the length first, followed by the bound checks, and then load the head segment. This
  15191. // allows the length sym to become dead by the time of the head segment load, freeing up the register for use by the
  15192. // head segment sym.
  15193. InsertHeadSegmentLoad();
  15194. }
  15195. if(doArrayChecks || doHeadSegmentLoad || doHeadSegmentLengthLoad || doLengthLoad)
  15196. {
  15197. UpdateValue(newHeadSegmentSym, newHeadSegmentLengthSym, newLengthSym);
  15198. baseValueInfo = baseValue->GetValueInfo();
  15199. baseArrayValueInfo = baseValueInfo->IsArrayValueInfo() ? baseValueInfo->AsArrayValueInfo() : nullptr;
  15200. // Iterate up to the root loop's landing pad until all necessary value info is updated
  15201. uint hoistItemCount =
  15202. static_cast<uint>(!!hoistChecksOutOfLoop) +
  15203. !!hoistHeadSegmentLoadOutOfLoop +
  15204. !!hoistHeadSegmentLengthLoadOutOfLoop +
  15205. !!hoistLengthLoadOutOfLoop;
  15206. if(hoistItemCount != 0)
  15207. {
  15208. Loop *rootLoop = nullptr;
  15209. for(Loop *loop = currentBlock->loop; loop; loop = loop->parent)
  15210. {
  15211. rootLoop = loop;
  15212. }
  15213. Assert(rootLoop);
  15214. ValueInfo *valueInfoToHoist = baseValueInfo;
  15215. bool removeHeadSegment, removeHeadSegmentLength, removeLength;
  15216. if(baseArrayValueInfo)
  15217. {
  15218. removeHeadSegment = baseArrayValueInfo->HeadSegmentSym() && !hoistHeadSegmentLoadOutOfLoop;
  15219. removeHeadSegmentLength =
  15220. baseArrayValueInfo->HeadSegmentLengthSym() && !hoistHeadSegmentLengthLoadOutOfLoop;
  15221. removeLength = baseArrayValueInfo->LengthSym() && !hoistLengthLoadOutOfLoop;
  15222. }
  15223. else
  15224. {
  15225. removeLength = removeHeadSegmentLength = removeHeadSegment = false;
  15226. }
  15227. for(InvariantBlockBackwardIterator it(
  15228. this,
  15229. currentBlock,
  15230. rootLoop->landingPad,
  15231. baseOpnd->m_sym,
  15232. baseValue->GetValueNumber());
  15233. it.IsValid();
  15234. it.MoveNext())
  15235. {
  15236. if(removeHeadSegment || removeHeadSegmentLength || removeLength)
  15237. {
  15238. // Remove information that shouldn't be there anymore, from the value info
  15239. valueInfoToHoist =
  15240. valueInfoToHoist->AsArrayValueInfo()->Copy(
  15241. alloc,
  15242. !removeHeadSegment,
  15243. !removeHeadSegmentLength,
  15244. !removeLength);
  15245. removeLength = removeHeadSegmentLength = removeHeadSegment = false;
  15246. }
  15247. BasicBlock *const block = it.Block();
  15248. Value *const blockBaseValue = it.InvariantSymValue();
  15249. HoistInvariantValueInfo(valueInfoToHoist, blockBaseValue, block);
  15250. // See if we have completed hoisting value info for one of the items
  15251. if(hoistChecksOutOfLoop && block == hoistChecksOutOfLoop->landingPad)
  15252. {
  15253. // All other items depend on array checks, so we can just stop here
  15254. hoistChecksOutOfLoop = nullptr;
  15255. break;
  15256. }
  15257. if(hoistHeadSegmentLoadOutOfLoop && block == hoistHeadSegmentLoadOutOfLoop->landingPad)
  15258. {
  15259. hoistHeadSegmentLoadOutOfLoop = nullptr;
  15260. if(--hoistItemCount == 0)
  15261. break;
  15262. if(valueInfoToHoist->IsArrayValueInfo() && valueInfoToHoist->AsArrayValueInfo()->HeadSegmentSym())
  15263. removeHeadSegment = true;
  15264. }
  15265. if(hoistHeadSegmentLengthLoadOutOfLoop && block == hoistHeadSegmentLengthLoadOutOfLoop->landingPad)
  15266. {
  15267. hoistHeadSegmentLengthLoadOutOfLoop = nullptr;
  15268. if(--hoistItemCount == 0)
  15269. break;
  15270. if(valueInfoToHoist->IsArrayValueInfo() && valueInfoToHoist->AsArrayValueInfo()->HeadSegmentLengthSym())
  15271. removeHeadSegmentLength = true;
  15272. }
  15273. if(hoistLengthLoadOutOfLoop && block == hoistLengthLoadOutOfLoop->landingPad)
  15274. {
  15275. hoistLengthLoadOutOfLoop = nullptr;
  15276. if(--hoistItemCount == 0)
  15277. break;
  15278. if(valueInfoToHoist->IsArrayValueInfo() && valueInfoToHoist->AsArrayValueInfo()->LengthSym())
  15279. removeLength = true;
  15280. }
  15281. }
  15282. }
  15283. }
  15284. }
  15285. IR::ArrayRegOpnd *baseArrayOpnd;
  15286. if(baseArrayValueInfo)
  15287. {
  15288. // Update the opnd to include the associated syms
  15289. baseArrayOpnd =
  15290. baseArrayValueInfo->CreateOpnd(
  15291. baseOpnd,
  15292. needsHeadSegment,
  15293. needsHeadSegmentLength || !isLikelyJsArray && needsLength,
  15294. needsLength,
  15295. eliminatedLowerBoundCheck,
  15296. eliminatedUpperBoundCheck,
  15297. instr->m_func);
  15298. if(baseOwnerInstr)
  15299. {
  15300. Assert(baseOwnerInstr->GetSrc1() == baseOpnd);
  15301. baseOwnerInstr->ReplaceSrc1(baseArrayOpnd);
  15302. }
  15303. else
  15304. {
  15305. Assert(baseOwnerIndir);
  15306. Assert(baseOwnerIndir->GetBaseOpnd() == baseOpnd);
  15307. baseOwnerIndir->ReplaceBaseOpnd(baseArrayOpnd);
  15308. }
  15309. baseOpnd = baseArrayOpnd;
  15310. }
  15311. else
  15312. {
  15313. baseArrayOpnd = nullptr;
  15314. }
  15315. if(isLikelyJsArray)
  15316. {
  15317. // Insert an instruction to indicate to the dead-store pass that implicit calls need to be kept disabled until this
  15318. // instruction. Operations other than LdElem and StElem don't benefit much from arrays having no missing values, so
  15319. // no need to ensure that the array still has no missing values. For a particular array, if none of the accesses
  15320. // benefit much from the no-missing-values information, it may be beneficial to avoid checking for no missing
  15321. // values, especially in the case for a single array access, where the cost of the check could be relatively
  15322. // significant. An StElem has to do additional checks in the common path if the array may have missing values, and
  15323. // a StElem that operates on an array that has no missing values is more likely to keep the no-missing-values info
  15324. // on the array more precise, so it still benefits a little from the no-missing-values info.
  15325. CaptureNoImplicitCallUses(baseOpnd, isLoad || isStore);
  15326. }
  15327. else if(baseArrayOpnd && baseArrayOpnd->HeadSegmentLengthSym())
  15328. {
  15329. // A typed array's array buffer may be transferred to a web worker as part of an implicit call, in which case the typed
  15330. // array's length is set to zero. Insert an instruction to indicate to the dead-store pass that implicit calls need to
  15331. // be disabled until this instruction.
  15332. IR::RegOpnd *const headSegmentLengthOpnd =
  15333. IR::RegOpnd::New(
  15334. baseArrayOpnd->HeadSegmentLengthSym(),
  15335. baseArrayOpnd->HeadSegmentLengthSym()->GetType(),
  15336. instr->m_func);
  15337. const IR::AutoReuseOpnd autoReuseHeadSegmentLengthOpnd(headSegmentLengthOpnd, instr->m_func);
  15338. CaptureNoImplicitCallUses(headSegmentLengthOpnd, false);
  15339. }
  15340. const auto OnEliminated = [&](const Js::Phase phase, const char *const eliminatedLoad)
  15341. {
  15342. TRACE_TESTTRACE_PHASE_INSTR(phase, instr, _u("Eliminating array %S\n"), eliminatedLoad);
  15343. };
  15344. OnEliminated(Js::Phase::ArrayCheckHoistPhase, "checks");
  15345. if(baseArrayOpnd)
  15346. {
  15347. if(baseArrayOpnd->HeadSegmentSym())
  15348. {
  15349. OnEliminated(Js::Phase::ArraySegmentHoistPhase, "head segment load");
  15350. }
  15351. if(baseArrayOpnd->HeadSegmentLengthSym())
  15352. {
  15353. OnEliminated(Js::Phase::ArraySegmentHoistPhase, "head segment length load");
  15354. }
  15355. if(baseArrayOpnd->LengthSym())
  15356. {
  15357. OnEliminated(Js::Phase::ArrayLengthHoistPhase, "length load");
  15358. }
  15359. if(baseArrayOpnd->EliminatedLowerBoundCheck())
  15360. {
  15361. OnEliminated(Js::Phase::BoundCheckEliminationPhase, "lower bound check");
  15362. }
  15363. if(baseArrayOpnd->EliminatedUpperBoundCheck())
  15364. {
  15365. OnEliminated(Js::Phase::BoundCheckEliminationPhase, "upper bound check");
  15366. }
  15367. }
  15368. if(!canBailOutOnArrayAccessHelperCall)
  15369. {
  15370. return;
  15371. }
  15372. // Bail out instead of generating a helper call. This helps to remove the array reference when the head segment and head
  15373. // segment length are available, reduces code size, and allows bound checks to be separated.
  15374. if(instr->HasBailOutInfo())
  15375. {
  15376. const IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  15377. Assert(
  15378. !(bailOutKind & ~IR::BailOutKindBits) ||
  15379. (bailOutKind & ~IR::BailOutKindBits) == IR::BailOutOnImplicitCallsPreOp);
  15380. instr->SetBailOutKind(bailOutKind & IR::BailOutKindBits | IR::BailOutOnArrayAccessHelperCall);
  15381. }
  15382. else
  15383. {
  15384. GenerateBailAtOperation(&instr, IR::BailOutOnArrayAccessHelperCall);
  15385. }
  15386. }
  15387. void
  15388. GlobOpt::CaptureNoImplicitCallUses(
  15389. IR::Opnd *opnd,
  15390. const bool usesNoMissingValuesInfo,
  15391. IR::Instr *const includeCurrentInstr)
  15392. {
  15393. Assert(!IsLoopPrePass());
  15394. Assert(noImplicitCallUsesToInsert);
  15395. Assert(opnd);
  15396. // The opnd may be deleted later, so make a copy to ensure it is alive for inserting NoImplicitCallUses later
  15397. opnd = opnd->Copy(func);
  15398. if(!usesNoMissingValuesInfo)
  15399. {
  15400. const ValueType valueType(opnd->GetValueType());
  15401. if(valueType.IsArrayOrObjectWithArray() && valueType.HasNoMissingValues())
  15402. {
  15403. // Inserting NoImplicitCallUses for an opnd with a definitely-array-with-no-missing-values value type means that the
  15404. // instruction following it uses the information that the array has no missing values in some way, for instance, it
  15405. // may omit missing value checks. Based on that, the dead-store phase in turn ensures that the necessary bailouts
  15406. // are inserted to ensure that the array still has no missing values until the following instruction. Since
  15407. // 'usesNoMissingValuesInfo' is false, change the value type to indicate to the dead-store phase that the following
  15408. // instruction does not use the no-missing-values information.
  15409. opnd->SetValueType(valueType.SetHasNoMissingValues(false));
  15410. }
  15411. }
  15412. if(includeCurrentInstr)
  15413. {
  15414. IR::Instr *const noImplicitCallUses =
  15415. IR::PragmaInstr::New(Js::OpCode::NoImplicitCallUses, 0, includeCurrentInstr->m_func);
  15416. noImplicitCallUses->SetSrc1(opnd);
  15417. noImplicitCallUses->GetSrc1()->SetIsJITOptimizedReg(true);
  15418. includeCurrentInstr->InsertAfter(noImplicitCallUses);
  15419. return;
  15420. }
  15421. noImplicitCallUsesToInsert->Add(opnd);
  15422. }
  15423. void
  15424. GlobOpt::InsertNoImplicitCallUses(IR::Instr *const instr)
  15425. {
  15426. Assert(noImplicitCallUsesToInsert);
  15427. const int n = noImplicitCallUsesToInsert->Count();
  15428. if(n == 0)
  15429. {
  15430. return;
  15431. }
  15432. IR::Instr *const insertBeforeInstr = instr->GetInsertBeforeByteCodeUsesInstr();
  15433. for(int i = 0; i < n;)
  15434. {
  15435. IR::Instr *const noImplicitCallUses = IR::PragmaInstr::New(Js::OpCode::NoImplicitCallUses, 0, instr->m_func);
  15436. noImplicitCallUses->SetSrc1(noImplicitCallUsesToInsert->Item(i));
  15437. noImplicitCallUses->GetSrc1()->SetIsJITOptimizedReg(true);
  15438. ++i;
  15439. if(i < n)
  15440. {
  15441. noImplicitCallUses->SetSrc2(noImplicitCallUsesToInsert->Item(i));
  15442. noImplicitCallUses->GetSrc2()->SetIsJITOptimizedReg(true);
  15443. ++i;
  15444. }
  15445. noImplicitCallUses->SetByteCodeOffset(instr);
  15446. insertBeforeInstr->InsertBefore(noImplicitCallUses);
  15447. }
  15448. noImplicitCallUsesToInsert->Clear();
  15449. }
  15450. void
  15451. GlobOpt::PrepareLoopArrayCheckHoist()
  15452. {
  15453. if(IsLoopPrePass() || !currentBlock->loop || !currentBlock->isLoopHeader || !currentBlock->loop->parent)
  15454. {
  15455. return;
  15456. }
  15457. if(currentBlock->loop->parent->needImplicitCallBailoutChecksForJsArrayCheckHoist)
  15458. {
  15459. // If the parent loop is an array check elimination candidate, so is the current loop. Even though the current loop may
  15460. // not have array accesses, if the parent loop hoists array checks, the current loop also needs implicit call checks.
  15461. currentBlock->loop->needImplicitCallBailoutChecksForJsArrayCheckHoist = true;
  15462. }
  15463. }
  15464. JsArrayKills
  15465. GlobOpt::CheckJsArrayKills(IR::Instr *const instr)
  15466. {
  15467. Assert(instr);
  15468. JsArrayKills kills;
  15469. if(instr->UsesAllFields())
  15470. {
  15471. // Calls can (but are unlikely to) change a javascript array into an ES5 array, which may have different behavior for
  15472. // index properties.
  15473. kills.SetKillsAllArrays();
  15474. return kills;
  15475. }
  15476. const bool doArrayMissingValueCheckHoist = DoArrayMissingValueCheckHoist();
  15477. const bool doNativeArrayTypeSpec = DoNativeArrayTypeSpec();
  15478. const bool doArraySegmentHoist = DoArraySegmentHoist(ValueType::GetObject(ObjectType::Array));
  15479. Assert(doArraySegmentHoist == DoArraySegmentHoist(ValueType::GetObject(ObjectType::ObjectWithArray)));
  15480. const bool doArrayLengthHoist = DoArrayLengthHoist();
  15481. if(!doArrayMissingValueCheckHoist && !doNativeArrayTypeSpec && !doArraySegmentHoist && !doArrayLengthHoist)
  15482. {
  15483. return kills;
  15484. }
  15485. // The following operations may create missing values in an array in an unlikely circumstance. Even though they don't kill
  15486. // the fact that the 'this' parameter is an array (when implicit calls are disabled), we don't have a way to say the value
  15487. // type is definitely array but it likely has no missing values. So, these will kill the definite value type as well, making
  15488. // it likely array, such that the array checks will have to be redone.
  15489. const bool useValueTypes = !IsLoopPrePass(); // Source value types are not guaranteed to be correct in a loop prepass
  15490. switch(instr->m_opcode)
  15491. {
  15492. case Js::OpCode::StElemI_A:
  15493. case Js::OpCode::StElemI_A_Strict:
  15494. {
  15495. Assert(instr->GetDst());
  15496. if(!instr->GetDst()->IsIndirOpnd())
  15497. {
  15498. break;
  15499. }
  15500. const ValueType baseValueType =
  15501. useValueTypes ? instr->GetDst()->AsIndirOpnd()->GetBaseOpnd()->GetValueType() : ValueType::Uninitialized;
  15502. if(useValueTypes && baseValueType.IsNotArrayOrObjectWithArray())
  15503. {
  15504. break;
  15505. }
  15506. if(instr->IsProfiledInstr())
  15507. {
  15508. const Js::StElemInfo *const stElemInfo = instr->AsProfiledInstr()->u.stElemInfo;
  15509. if(doArraySegmentHoist && stElemInfo->LikelyStoresOutsideHeadSegmentBounds())
  15510. {
  15511. kills.SetKillsArrayHeadSegments();
  15512. kills.SetKillsArrayHeadSegmentLengths();
  15513. }
  15514. if(doArrayLengthHoist &&
  15515. !(useValueTypes && baseValueType.IsNotArray()) &&
  15516. stElemInfo->LikelyStoresOutsideArrayBounds())
  15517. {
  15518. kills.SetKillsArrayLengths();
  15519. }
  15520. }
  15521. break;
  15522. }
  15523. case Js::OpCode::DeleteElemI_A:
  15524. case Js::OpCode::DeleteElemIStrict_A:
  15525. Assert(instr->GetSrc1());
  15526. if(!instr->GetSrc1()->IsIndirOpnd() ||
  15527. useValueTypes && instr->GetSrc1()->AsIndirOpnd()->GetBaseOpnd()->GetValueType().IsNotArrayOrObjectWithArray())
  15528. {
  15529. break;
  15530. }
  15531. if(doArrayMissingValueCheckHoist)
  15532. {
  15533. kills.SetKillsArraysWithNoMissingValues();
  15534. }
  15535. if(doArraySegmentHoist)
  15536. {
  15537. kills.SetKillsArrayHeadSegmentLengths();
  15538. }
  15539. break;
  15540. case Js::OpCode::StFld:
  15541. case Js::OpCode::StFldStrict:
  15542. {
  15543. Assert(instr->GetDst());
  15544. if(!doArraySegmentHoist && !doArrayLengthHoist)
  15545. {
  15546. break;
  15547. }
  15548. IR::SymOpnd *const symDst = instr->GetDst()->AsSymOpnd();
  15549. if(!symDst->IsPropertySymOpnd())
  15550. {
  15551. break;
  15552. }
  15553. IR::PropertySymOpnd *const dst = symDst->AsPropertySymOpnd();
  15554. if(dst->m_sym->AsPropertySym()->m_propertyId != Js::PropertyIds::length)
  15555. {
  15556. break;
  15557. }
  15558. if(useValueTypes && dst->GetPropertyOwnerValueType().IsNotArray())
  15559. {
  15560. // Setting the 'length' property of an object that is not an array, even if it has an internal array, does
  15561. // not kill the head segment or head segment length of any arrays.
  15562. break;
  15563. }
  15564. if(doArraySegmentHoist)
  15565. {
  15566. kills.SetKillsArrayHeadSegmentLengths();
  15567. }
  15568. if(doArrayLengthHoist)
  15569. {
  15570. kills.SetKillsArrayLengths();
  15571. }
  15572. break;
  15573. }
  15574. case Js::OpCode::InlineArrayPush:
  15575. {
  15576. Assert(instr->GetSrc2());
  15577. IR::Opnd *const arrayOpnd = instr->GetSrc1();
  15578. Assert(arrayOpnd);
  15579. const ValueType arrayValueType(arrayOpnd->GetValueType());
  15580. if(!arrayOpnd->IsRegOpnd() || useValueTypes && arrayValueType.IsNotArrayOrObjectWithArray())
  15581. {
  15582. break;
  15583. }
  15584. if(doArrayMissingValueCheckHoist)
  15585. {
  15586. kills.SetKillsArraysWithNoMissingValues();
  15587. }
  15588. if(doArraySegmentHoist)
  15589. {
  15590. kills.SetKillsArrayHeadSegments();
  15591. kills.SetKillsArrayHeadSegmentLengths();
  15592. }
  15593. if(doArrayLengthHoist && !(useValueTypes && arrayValueType.IsNotArray()))
  15594. {
  15595. kills.SetKillsArrayLengths();
  15596. }
  15597. // Don't kill NativeArray, if there is no mismatch between array's type and element's type.
  15598. if(doNativeArrayTypeSpec && !(useValueTypes && arrayValueType.IsNativeArray() &&
  15599. (arrayValueType.IsLikelyNativeIntArray() && instr->GetSrc2()->IsInt32()) ||
  15600. (arrayValueType.IsLikelyNativeFloatArray() && instr->GetSrc2()->IsFloat()))
  15601. && !(useValueTypes && arrayValueType.IsNotNativeArray()))
  15602. {
  15603. kills.SetKillsNativeArrays();
  15604. }
  15605. break;
  15606. }
  15607. case Js::OpCode::InlineArrayPop:
  15608. {
  15609. IR::Opnd *const arrayOpnd = instr->GetSrc1();
  15610. Assert(arrayOpnd);
  15611. const ValueType arrayValueType(arrayOpnd->GetValueType());
  15612. if(!arrayOpnd->IsRegOpnd() || useValueTypes && arrayValueType.IsNotArrayOrObjectWithArray())
  15613. {
  15614. break;
  15615. }
  15616. if(doArraySegmentHoist)
  15617. {
  15618. kills.SetKillsArrayHeadSegmentLengths();
  15619. }
  15620. if(doArrayLengthHoist && !(useValueTypes && arrayValueType.IsNotArray()))
  15621. {
  15622. kills.SetKillsArrayLengths();
  15623. }
  15624. break;
  15625. }
  15626. case Js::OpCode::CallDirect:
  15627. {
  15628. Assert(instr->GetSrc1());
  15629. // Find the 'this' parameter and check if it's possible for it to be an array
  15630. IR::Opnd *const arrayOpnd = instr->FindCallArgumentOpnd(1);
  15631. Assert(arrayOpnd);
  15632. const ValueType arrayValueType(arrayOpnd->GetValueType());
  15633. if(!arrayOpnd->IsRegOpnd() || useValueTypes && arrayValueType.IsNotArrayOrObjectWithArray())
  15634. {
  15635. break;
  15636. }
  15637. const IR::JnHelperMethod helperMethod = instr->GetSrc1()->AsHelperCallOpnd()->m_fnHelper;
  15638. if(doArrayMissingValueCheckHoist)
  15639. {
  15640. switch(helperMethod)
  15641. {
  15642. case IR::HelperArray_Reverse:
  15643. case IR::HelperArray_Shift:
  15644. case IR::HelperArray_Splice:
  15645. case IR::HelperArray_Unshift:
  15646. kills.SetKillsArraysWithNoMissingValues();
  15647. break;
  15648. }
  15649. }
  15650. if(doArraySegmentHoist)
  15651. {
  15652. switch(helperMethod)
  15653. {
  15654. case IR::HelperArray_Reverse:
  15655. case IR::HelperArray_Shift:
  15656. case IR::HelperArray_Splice:
  15657. case IR::HelperArray_Unshift:
  15658. kills.SetKillsArrayHeadSegments();
  15659. kills.SetKillsArrayHeadSegmentLengths();
  15660. break;
  15661. }
  15662. }
  15663. if(doArrayLengthHoist && !(useValueTypes && arrayValueType.IsNotArray()))
  15664. {
  15665. switch(helperMethod)
  15666. {
  15667. case IR::HelperArray_Shift:
  15668. case IR::HelperArray_Splice:
  15669. case IR::HelperArray_Unshift:
  15670. kills.SetKillsArrayLengths();
  15671. break;
  15672. }
  15673. }
  15674. if(doNativeArrayTypeSpec && !(useValueTypes && arrayValueType.IsNotNativeArray()))
  15675. {
  15676. switch(helperMethod)
  15677. {
  15678. case IR::HelperArray_Reverse:
  15679. case IR::HelperArray_Shift:
  15680. case IR::HelperArray_Slice:
  15681. // Currently not inlined.
  15682. //case IR::HelperArray_Sort:
  15683. case IR::HelperArray_Splice:
  15684. case IR::HelperArray_Unshift:
  15685. kills.SetKillsNativeArrays();
  15686. break;
  15687. }
  15688. }
  15689. break;
  15690. }
  15691. }
  15692. return kills;
  15693. }
  15694. bool
  15695. GlobOpt::IsOperationThatLikelyKillsJsArraysWithNoMissingValues(IR::Instr *const instr)
  15696. {
  15697. // StElem is profiled with information indicating whether it will likely create a missing value in the array. In that case,
  15698. // we prefer to kill the no-missing-values information in the value so that we don't bail out in a likely circumstance.
  15699. return
  15700. (instr->m_opcode == Js::OpCode::StElemI_A || instr->m_opcode == Js::OpCode::StElemI_A_Strict) &&
  15701. DoArrayMissingValueCheckHoist() &&
  15702. instr->IsProfiledInstr() &&
  15703. instr->AsProfiledInstr()->u.stElemInfo->LikelyCreatesMissingValue();
  15704. }
  15705. bool
  15706. GlobOpt::NeedBailOnImplicitCallForArrayCheckHoist(BasicBlock *const block, const bool isForwardPass) const
  15707. {
  15708. Assert(block);
  15709. return isForwardPass && block->loop && block->loop->needImplicitCallBailoutChecksForJsArrayCheckHoist;
  15710. }
  15711. bool
  15712. GlobOpt::PrepareForIgnoringIntOverflow(IR::Instr *const instr)
  15713. {
  15714. Assert(instr);
  15715. const bool isBoundary = instr->m_opcode == Js::OpCode::NoIntOverflowBoundary;
  15716. // Update the instruction's "int overflow matters" flag based on whether we are currently allowing ignoring int overflows.
  15717. // Some operations convert their srcs to int32s, those can still ignore int overflow.
  15718. if(instr->ignoreIntOverflowInRange)
  15719. {
  15720. instr->ignoreIntOverflowInRange = !intOverflowCurrentlyMattersInRange || OpCodeAttr::IsInt32(instr->m_opcode);
  15721. }
  15722. if(!intOverflowDoesNotMatterRange)
  15723. {
  15724. Assert(intOverflowCurrentlyMattersInRange);
  15725. // There are no more ranges of instructions where int overflow does not matter, in this block.
  15726. return isBoundary;
  15727. }
  15728. if(instr == intOverflowDoesNotMatterRange->LastInstr())
  15729. {
  15730. Assert(isBoundary);
  15731. // Reached the last instruction in the range
  15732. intOverflowCurrentlyMattersInRange = true;
  15733. intOverflowDoesNotMatterRange = intOverflowDoesNotMatterRange->Next();
  15734. return isBoundary;
  15735. }
  15736. if(!intOverflowCurrentlyMattersInRange)
  15737. {
  15738. return isBoundary;
  15739. }
  15740. if(instr != intOverflowDoesNotMatterRange->FirstInstr())
  15741. {
  15742. // Have not reached the next range
  15743. return isBoundary;
  15744. }
  15745. Assert(isBoundary);
  15746. // This is the first instruction in a range of instructions where int overflow does not matter. There can be many inputs to
  15747. // instructions in the range, some of which are inputs to the range itself (that is, the values are not defined in the
  15748. // range). Ignoring int overflow is only valid for int operations, so we need to ensure that all inputs to the range are
  15749. // int (not "likely int") before ignoring any overflows in the range. Ensuring that a sym with a "likely int" value is an
  15750. // int requires a bail-out. These bail-out check need to happen before any overflows are ignored, otherwise it's too late.
  15751. // The backward pass tracked all inputs into the range. Iterate over them and verify the values, and insert lossless
  15752. // conversions to int as necessary, before the first instruction in the range. If for any reason all values cannot be
  15753. // guaranteed to be ints, the optimization will be disabled for this range.
  15754. intOverflowCurrentlyMattersInRange = false;
  15755. {
  15756. BVSparse<JitArenaAllocator> tempBv1(tempAlloc);
  15757. BVSparse<JitArenaAllocator> tempBv2(tempAlloc);
  15758. {
  15759. // Just renaming the temp BVs for this section to indicate how they're used so that it makes sense
  15760. BVSparse<JitArenaAllocator> &symsToExclude = tempBv1;
  15761. BVSparse<JitArenaAllocator> &symsToInclude = tempBv2;
  15762. #if DBG_DUMP
  15763. SymID couldNotConvertSymId = 0;
  15764. #endif
  15765. FOREACH_BITSET_IN_SPARSEBV(id, intOverflowDoesNotMatterRange->SymsRequiredToBeInt())
  15766. {
  15767. Sym *const sym = func->m_symTable->Find(id);
  15768. Assert(sym);
  15769. // Some instructions with property syms are also tracked by the backward pass, and may be included in the range
  15770. // (LdSlot for instance). These property syms don't get their values until either copy-prop resolves a value for
  15771. // them, or a new value is created once the use of the property sym is reached. In either case, we're not that
  15772. // far yet, so we need to find the future value of the property sym by evaluating copy-prop in reverse.
  15773. Value *const value = sym->IsStackSym() ? FindValue(sym) : FindFuturePropertyValue(sym->AsPropertySym());
  15774. if(!value)
  15775. {
  15776. #if DBG_DUMP
  15777. couldNotConvertSymId = id;
  15778. #endif
  15779. intOverflowCurrentlyMattersInRange = true;
  15780. BREAK_BITSET_IN_SPARSEBV;
  15781. }
  15782. const bool isInt32OrUInt32Float =
  15783. value->GetValueInfo()->IsFloatConstant() &&
  15784. Js::JavascriptNumber::IsInt32OrUInt32(value->GetValueInfo()->AsFloatConstant()->FloatValue());
  15785. if(value->GetValueInfo()->IsInt() || isInt32OrUInt32Float)
  15786. {
  15787. if(!IsLoopPrePass())
  15788. {
  15789. // Input values that are already int can be excluded from int-specialization. We can treat unsigned
  15790. // int32 values as int32 values (ignoring the overflow), since the values will only be used inside the
  15791. // range where overflow does not matter.
  15792. symsToExclude.Set(sym->m_id);
  15793. }
  15794. continue;
  15795. }
  15796. if(!DoAggressiveIntTypeSpec() || !value->GetValueInfo()->IsLikelyInt())
  15797. {
  15798. // When aggressive int specialization is off, syms with "likely int" values cannot be forced to int since
  15799. // int bail-out checks are not allowed in that mode. Similarly, with aggressive int specialization on, it
  15800. // wouldn't make sense to force non-"likely int" values to int since it would almost guarantee a bail-out at
  15801. // runtime. In both cases, just disable ignoring overflow for this range.
  15802. #if DBG_DUMP
  15803. couldNotConvertSymId = id;
  15804. #endif
  15805. intOverflowCurrentlyMattersInRange = true;
  15806. BREAK_BITSET_IN_SPARSEBV;
  15807. }
  15808. if(IsLoopPrePass())
  15809. {
  15810. // The loop prepass does not modify bit-vectors. Since it doesn't add bail-out checks, it also does not need
  15811. // to specialize anything up-front. It only needs to be consistent in how it determines whether to allow
  15812. // ignoring overflow for a range, based on the values of inputs into the range.
  15813. continue;
  15814. }
  15815. // Since input syms are tracked in the backward pass, where there is no value tracking, it will not be aware of
  15816. // copy-prop. If a copy-prop sym is available, it will be used instead, so exclude the original sym and include
  15817. // the copy-prop sym for specialization.
  15818. StackSym *const copyPropSym = GetCopyPropSym(sym, value);
  15819. if(copyPropSym)
  15820. {
  15821. symsToExclude.Set(sym->m_id);
  15822. Assert(!symsToExclude.Test(copyPropSym->m_id));
  15823. const bool needsToBeLossless =
  15824. !intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Test(sym->m_id);
  15825. if(intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Test(copyPropSym->m_id) ||
  15826. symsToInclude.TestAndSet(copyPropSym->m_id))
  15827. {
  15828. // The copy-prop sym is already included
  15829. if(needsToBeLossless)
  15830. {
  15831. // The original sym needs to be lossless, so make the copy-prop sym lossless as well.
  15832. intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Clear(copyPropSym->m_id);
  15833. }
  15834. }
  15835. else if(!needsToBeLossless)
  15836. {
  15837. // The copy-prop sym was not included before, and the original sym can be lossy, so make it lossy.
  15838. intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Set(copyPropSym->m_id);
  15839. }
  15840. }
  15841. else if(!sym->IsStackSym())
  15842. {
  15843. // Only stack syms can be converted to int, and copy-prop syms are stack syms. If a copy-prop sym was not
  15844. // found for the property sym, we can't ignore overflows in this range.
  15845. #if DBG_DUMP
  15846. couldNotConvertSymId = id;
  15847. #endif
  15848. intOverflowCurrentlyMattersInRange = true;
  15849. BREAK_BITSET_IN_SPARSEBV;
  15850. }
  15851. } NEXT_BITSET_IN_SPARSEBV;
  15852. if(intOverflowCurrentlyMattersInRange)
  15853. {
  15854. #if DBG_DUMP
  15855. if(PHASE_TRACE(Js::TrackCompoundedIntOverflowPhase, func->GetJnFunction()) && !IsLoopPrePass())
  15856. {
  15857. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  15858. Output::Print(
  15859. _u("TrackCompoundedIntOverflow - Top function: %s (%s), Phase: %s, Block: %u, Disabled ignoring overflows\n"),
  15860. func->GetJnFunction()->GetDisplayName(),
  15861. func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  15862. Js::PhaseNames[Js::ForwardPhase],
  15863. currentBlock->GetBlockNum());
  15864. Output::Print(_u(" Input sym could not be turned into an int: %u\n"), couldNotConvertSymId);
  15865. Output::Print(_u(" First instr: "));
  15866. instr->m_next->Dump();
  15867. Output::Flush();
  15868. }
  15869. #endif
  15870. intOverflowDoesNotMatterRange = intOverflowDoesNotMatterRange->Next();
  15871. return isBoundary;
  15872. }
  15873. if(IsLoopPrePass())
  15874. {
  15875. return isBoundary;
  15876. }
  15877. // Update the syms to specialize after enumeration
  15878. intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Minus(&symsToExclude);
  15879. intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Minus(&symsToExclude);
  15880. intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Or(&symsToInclude);
  15881. }
  15882. {
  15883. // Exclude syms that are already live as lossless int32, and exclude lossy conversions of syms that are already live
  15884. // as lossy int32.
  15885. // symsToExclude = liveInt32Syms - liveLossyInt32Syms // syms live as lossless int
  15886. // lossySymsToExclude = symsRequiredToBeLossyInt & liveLossyInt32Syms; // syms we want as lossy int that are already live as lossy int
  15887. // symsToExclude |= lossySymsToExclude
  15888. // symsRequiredToBeInt -= symsToExclude
  15889. // symsRequiredToBeLossyInt -= symsToExclude
  15890. BVSparse<JitArenaAllocator> &symsToExclude = tempBv1;
  15891. BVSparse<JitArenaAllocator> &lossySymsToExclude = tempBv2;
  15892. symsToExclude.Minus(currentBlock->globOptData.liveInt32Syms, currentBlock->globOptData.liveLossyInt32Syms);
  15893. lossySymsToExclude.And(
  15894. intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt(),
  15895. currentBlock->globOptData.liveLossyInt32Syms);
  15896. symsToExclude.Or(&lossySymsToExclude);
  15897. intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Minus(&symsToExclude);
  15898. intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Minus(&symsToExclude);
  15899. }
  15900. #if DBG
  15901. {
  15902. // Verify that the syms to be converted are live
  15903. // liveSyms = liveInt32Syms | liveFloat64Syms | liveVarSyms
  15904. // deadSymsRequiredToBeInt = symsRequiredToBeInt - liveSyms
  15905. BVSparse<JitArenaAllocator> &liveSyms = tempBv1;
  15906. BVSparse<JitArenaAllocator> &deadSymsRequiredToBeInt = tempBv2;
  15907. liveSyms.Or(currentBlock->globOptData.liveInt32Syms, currentBlock->globOptData.liveFloat64Syms);
  15908. liveSyms.Or(currentBlock->globOptData.liveVarSyms);
  15909. deadSymsRequiredToBeInt.Minus(intOverflowDoesNotMatterRange->SymsRequiredToBeInt(), &liveSyms);
  15910. Assert(deadSymsRequiredToBeInt.IsEmpty());
  15911. }
  15912. #endif
  15913. }
  15914. // Int-specialize the syms before the first instruction of the range (the current instruction)
  15915. intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Minus(intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt());
  15916. #if DBG_DUMP
  15917. if(PHASE_TRACE(Js::TrackCompoundedIntOverflowPhase, func->GetJnFunction()))
  15918. {
  15919. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  15920. Output::Print(
  15921. _u("TrackCompoundedIntOverflow - Top function: %s (%s), Phase: %s, Block: %u\n"),
  15922. func->GetJnFunction()->GetDisplayName(),
  15923. func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  15924. Js::PhaseNames[Js::ForwardPhase],
  15925. currentBlock->GetBlockNum());
  15926. Output::Print(_u(" Input syms to be int-specialized (lossless): "));
  15927. intOverflowDoesNotMatterRange->SymsRequiredToBeInt()->Dump();
  15928. Output::Print(_u(" Input syms to be converted to int (lossy): "));
  15929. intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt()->Dump();
  15930. Output::Print(_u(" First instr: "));
  15931. instr->m_next->Dump();
  15932. Output::Flush();
  15933. }
  15934. #endif
  15935. ToInt32(intOverflowDoesNotMatterRange->SymsRequiredToBeInt(), currentBlock, false /* lossy */, instr);
  15936. ToInt32(intOverflowDoesNotMatterRange->SymsRequiredToBeLossyInt(), currentBlock, true /* lossy */, instr);
  15937. return isBoundary;
  15938. }
  15939. void
  15940. GlobOpt::VerifyIntSpecForIgnoringIntOverflow(IR::Instr *const instr)
  15941. {
  15942. if(intOverflowCurrentlyMattersInRange || IsLoopPrePass())
  15943. {
  15944. return;
  15945. }
  15946. Assert(instr->m_opcode != Js::OpCode::Mul_I4 ||
  15947. (instr->m_opcode == Js::OpCode::Mul_I4 && !instr->ShouldCheckFor32BitOverflow() && instr->ShouldCheckForNon32BitOverflow() ));
  15948. // Instructions that are marked as "overflow doesn't matter" in the range must guarantee that they operate on int values and
  15949. // result in int values, for ignoring overflow to be valid. So, int-specialization is required for such instructions in the
  15950. // range. Ld_A is an exception because it only specializes if the src sym is available as a required specialized sym, and it
  15951. // doesn't generate bailouts or cause ignoring int overflow to be invalid.
  15952. // MULs are allowed to start a region and have BailOutInfo since they will bailout on non-32 bit overflow.
  15953. if(instr->m_opcode == Js::OpCode::Ld_A ||
  15954. (!instr->HasBailOutInfo() || instr->m_opcode == Js::OpCode::Mul_I4) &&
  15955. (!instr->GetDst() || instr->GetDst()->IsInt32()) &&
  15956. (!instr->GetSrc1() || instr->GetSrc1()->IsInt32()) &&
  15957. (!instr->GetSrc2() || instr->GetSrc2()->IsInt32()))
  15958. {
  15959. return;
  15960. }
  15961. if (!instr->HasBailOutInfo() && !instr->HasAnySideEffects())
  15962. {
  15963. return;
  15964. }
  15965. // This can happen for Neg_A if it needs to bail out on negative zero, and perhaps other cases as well. It's too late to fix
  15966. // the problem (overflows may already be ignored), so handle it by bailing out at compile-time and disabling tracking int
  15967. // overflow.
  15968. Assert(!func->GetProfileInfo()->IsTrackCompoundedIntOverflowDisabled());
  15969. if(PHASE_TRACE(Js::BailOutPhase, this->func->GetJnFunction()))
  15970. {
  15971. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  15972. Output::Print(
  15973. _u("BailOut (compile-time): function: %s (%s) instr: "),
  15974. func->GetJnFunction()->GetDisplayName(),
  15975. func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer));
  15976. #if DBG_DUMP
  15977. instr->Dump();
  15978. #else
  15979. Output::Print(_u("%s "), Js::OpCodeUtil::GetOpCodeName(instr->m_opcode));
  15980. #endif
  15981. Output::Print(_u("(overflow does not matter but could not int-spec or needed bailout)\n"));
  15982. Output::Flush();
  15983. }
  15984. if(func->GetProfileInfo()->IsTrackCompoundedIntOverflowDisabled())
  15985. {
  15986. // Tracking int overflows is already off for some reason. Prevent trying to rejit again because it won't help and the
  15987. // same thing will happen again and cause an infinite loop. Just abort jitting this function.
  15988. if(PHASE_TRACE(Js::BailOutPhase, this->func->GetJnFunction()))
  15989. {
  15990. Output::Print(_u(" Aborting JIT because TrackIntOverflow is already off\n"));
  15991. Output::Flush();
  15992. }
  15993. throw Js::OperationAbortedException();
  15994. }
  15995. throw Js::RejitException(RejitReason::TrackIntOverflowDisabled);
  15996. }
  15997. // It makes lowering easier if it can assume that the first src is never a constant,
  15998. // at least for commutative operators. For non-commutative, just hoist the constant.
  15999. void
  16000. GlobOpt::PreLowerCanonicalize(IR::Instr *instr, Value **pSrc1Val, Value **pSrc2Val)
  16001. {
  16002. IR::Opnd *dst = instr->GetDst();
  16003. IR::Opnd *src1 = instr->GetSrc1();
  16004. IR::Opnd *src2 = instr->GetSrc2();
  16005. if (src1->IsImmediateOpnd())
  16006. {
  16007. // Swap for dst, src
  16008. }
  16009. else if (src2 && dst && src2->IsRegOpnd())
  16010. {
  16011. if (src2->GetIsDead() && !src1->GetIsDead() && !src1->IsEqual(dst))
  16012. {
  16013. // Swap if src2 is dead, as the reg can be reuse for the dst for opEqs like on x86 (ADD r1, r2)
  16014. }
  16015. else if (src2->IsEqual(dst))
  16016. {
  16017. // Helps lowering of opEqs
  16018. }
  16019. else
  16020. {
  16021. return;
  16022. }
  16023. // Make sure we don't swap 2 srcs with valueOf calls.
  16024. if (OpCodeAttr::CallsValueOf(instr->m_opcode))
  16025. {
  16026. if (instr->IsBranchInstr())
  16027. {
  16028. if (!src1->GetValueType().IsPrimitive() || !src2->GetValueType().IsPrimitive())
  16029. {
  16030. return;
  16031. }
  16032. }
  16033. else if (!src1->GetValueType().IsPrimitive() && !src2->GetValueType().IsPrimitive())
  16034. {
  16035. return;
  16036. }
  16037. }
  16038. }
  16039. else
  16040. {
  16041. return;
  16042. }
  16043. Js::OpCode opcode = instr->m_opcode;
  16044. switch (opcode)
  16045. {
  16046. case Js::OpCode::And_A:
  16047. case Js::OpCode::Mul_A:
  16048. case Js::OpCode::Or_A:
  16049. case Js::OpCode::Xor_A:
  16050. case Js::OpCode::And_I4:
  16051. case Js::OpCode::Mul_I4:
  16052. case Js::OpCode::Or_I4:
  16053. case Js::OpCode::Xor_I4:
  16054. case Js::OpCode::Add_I4:
  16055. case Js::OpCode::Add_Ptr:
  16056. swap_srcs:
  16057. if (!instr->GetSrc2()->IsImmediateOpnd())
  16058. {
  16059. instr->m_opcode = opcode;
  16060. src1 = instr->UnlinkSrc1();
  16061. src2 = instr->UnlinkSrc2();
  16062. instr->SetSrc1(src2);
  16063. instr->SetSrc2(src1);
  16064. Value *tempVal = *pSrc1Val;
  16065. *pSrc1Val = *pSrc2Val;
  16066. *pSrc2Val = tempVal;
  16067. return;
  16068. }
  16069. break;
  16070. case Js::OpCode::BrSrEq_A:
  16071. case Js::OpCode::BrSrNotNeq_A:
  16072. case Js::OpCode::BrEq_I4:
  16073. goto swap_srcs;
  16074. case Js::OpCode::BrSrNeq_A:
  16075. case Js::OpCode::BrNeq_A:
  16076. case Js::OpCode::BrSrNotEq_A:
  16077. case Js::OpCode::BrNotEq_A:
  16078. case Js::OpCode::BrNeq_I4:
  16079. goto swap_srcs;
  16080. case Js::OpCode::BrGe_A:
  16081. opcode = Js::OpCode::BrLe_A;
  16082. goto swap_srcs;
  16083. case Js::OpCode::BrNotGe_A:
  16084. opcode = Js::OpCode::BrNotLe_A;
  16085. goto swap_srcs;
  16086. case Js::OpCode::BrGe_I4:
  16087. opcode = Js::OpCode::BrLe_I4;
  16088. goto swap_srcs;
  16089. case Js::OpCode::BrGt_A:
  16090. opcode = Js::OpCode::BrLt_A;
  16091. goto swap_srcs;
  16092. case Js::OpCode::BrNotGt_A:
  16093. opcode = Js::OpCode::BrNotLt_A;
  16094. goto swap_srcs;
  16095. case Js::OpCode::BrGt_I4:
  16096. opcode = Js::OpCode::BrLt_I4;
  16097. goto swap_srcs;
  16098. case Js::OpCode::BrLe_A:
  16099. opcode = Js::OpCode::BrGe_A;
  16100. goto swap_srcs;
  16101. case Js::OpCode::BrNotLe_A:
  16102. opcode = Js::OpCode::BrNotGe_A;
  16103. goto swap_srcs;
  16104. case Js::OpCode::BrLe_I4:
  16105. opcode = Js::OpCode::BrGe_I4;
  16106. goto swap_srcs;
  16107. case Js::OpCode::BrLt_A:
  16108. opcode = Js::OpCode::BrGt_A;
  16109. goto swap_srcs;
  16110. case Js::OpCode::BrNotLt_A:
  16111. opcode = Js::OpCode::BrNotGt_A;
  16112. goto swap_srcs;
  16113. case Js::OpCode::BrLt_I4:
  16114. opcode = Js::OpCode::BrGt_I4;
  16115. goto swap_srcs;
  16116. case Js::OpCode::BrEq_A:
  16117. case Js::OpCode::BrNotNeq_A:
  16118. case Js::OpCode::CmEq_A:
  16119. case Js::OpCode::CmNeq_A:
  16120. // this == "" not the same as "" == this...
  16121. if (!src1->IsImmediateOpnd() && (!src1->GetValueType().IsPrimitive() || !src2->GetValueType().IsPrimitive()))
  16122. {
  16123. return;
  16124. }
  16125. goto swap_srcs;
  16126. case Js::OpCode::CmGe_A:
  16127. if (!src1->IsImmediateOpnd() && (!src1->GetValueType().IsPrimitive() || !src2->GetValueType().IsPrimitive()))
  16128. {
  16129. return;
  16130. }
  16131. opcode = Js::OpCode::CmLe_A;
  16132. goto swap_srcs;
  16133. case Js::OpCode::CmGt_A:
  16134. if (!src1->IsImmediateOpnd() && (!src1->GetValueType().IsPrimitive() || !src2->GetValueType().IsPrimitive()))
  16135. {
  16136. return;
  16137. }
  16138. opcode = Js::OpCode::CmLt_A;
  16139. goto swap_srcs;
  16140. case Js::OpCode::CmLe_A:
  16141. if (!src1->IsImmediateOpnd() && (!src1->GetValueType().IsPrimitive() || !src2->GetValueType().IsPrimitive()))
  16142. {
  16143. return;
  16144. }
  16145. opcode = Js::OpCode::CmGe_A;
  16146. goto swap_srcs;
  16147. case Js::OpCode::CmLt_A:
  16148. if (!src1->IsImmediateOpnd() && (!src1->GetValueType().IsPrimitive() || !src2->GetValueType().IsPrimitive()))
  16149. {
  16150. return;
  16151. }
  16152. opcode = Js::OpCode::CmGt_A;
  16153. goto swap_srcs;
  16154. case Js::OpCode::CallI:
  16155. case Js::OpCode::CallIFixed:
  16156. case Js::OpCode::NewScObject:
  16157. case Js::OpCode::NewScObjectSpread:
  16158. case Js::OpCode::NewScObjArray:
  16159. case Js::OpCode::NewScObjArraySpread:
  16160. case Js::OpCode::NewScObjectNoCtor:
  16161. // Don't insert load to register if the function operand is a fixed function.
  16162. if (instr->HasFixedFunctionAddressTarget())
  16163. {
  16164. return;
  16165. }
  16166. break;
  16167. // Can't do add because <32 + "Hello"> isn't equal to <"Hello" + 32>
  16168. // Lower can do the swap. Other op-codes listed below don't need immediate source hoisting, as the fast paths handle it,
  16169. // or the lowering handles the hoisting.
  16170. case Js::OpCode::Add_A:
  16171. if (src1->IsFloat())
  16172. {
  16173. goto swap_srcs;
  16174. }
  16175. return;
  16176. case Js::OpCode::Sub_I4:
  16177. case Js::OpCode::Neg_I4:
  16178. case Js::OpCode::Not_I4:
  16179. case Js::OpCode::NewScFunc:
  16180. case Js::OpCode::NewScGenFunc:
  16181. case Js::OpCode::NewScArray:
  16182. case Js::OpCode::NewScIntArray:
  16183. case Js::OpCode::NewScFltArray:
  16184. case Js::OpCode::NewScArrayWithMissingValues:
  16185. case Js::OpCode::NewRegEx:
  16186. case Js::OpCode::Ld_A:
  16187. case Js::OpCode::Ld_I4:
  16188. case Js::OpCode::FromVar:
  16189. case Js::OpCode::Conv_Prim:
  16190. case Js::OpCode::LdC_A_I4:
  16191. case Js::OpCode::LdStr:
  16192. case Js::OpCode::InitFld:
  16193. case Js::OpCode::InitRootFld:
  16194. case Js::OpCode::StartCall:
  16195. case Js::OpCode::ArgOut_A:
  16196. case Js::OpCode::ArgOut_A_Inline:
  16197. case Js::OpCode::ArgOut_A_Dynamic:
  16198. case Js::OpCode::ArgOut_A_FromStackArgs:
  16199. case Js::OpCode::ArgOut_A_InlineBuiltIn:
  16200. case Js::OpCode::ArgOut_A_InlineSpecialized:
  16201. case Js::OpCode::ArgOut_A_SpreadArg:
  16202. case Js::OpCode::InlineeEnd:
  16203. case Js::OpCode::EndCallForPolymorphicInlinee:
  16204. case Js::OpCode::InlineeMetaArg:
  16205. case Js::OpCode::InlineBuiltInEnd:
  16206. case Js::OpCode::InlineNonTrackingBuiltInEnd:
  16207. case Js::OpCode::CallHelper:
  16208. case Js::OpCode::LdElemUndef:
  16209. case Js::OpCode::LdElemUndefScoped:
  16210. case Js::OpCode::RuntimeTypeError:
  16211. case Js::OpCode::RuntimeReferenceError:
  16212. case Js::OpCode::Ret:
  16213. case Js::OpCode::NewScObjectSimple:
  16214. case Js::OpCode::NewScObjectLiteral:
  16215. case Js::OpCode::StFld:
  16216. case Js::OpCode::StRootFld:
  16217. case Js::OpCode::StSlot:
  16218. case Js::OpCode::StSlotChkUndecl:
  16219. case Js::OpCode::StElemC:
  16220. case Js::OpCode::StArrSegElemC:
  16221. case Js::OpCode::StElemI_A:
  16222. case Js::OpCode::StElemI_A_Strict:
  16223. case Js::OpCode::CallDirect:
  16224. case Js::OpCode::BrNotHasSideEffects:
  16225. case Js::OpCode::NewConcatStrMulti:
  16226. case Js::OpCode::NewConcatStrMultiBE:
  16227. case Js::OpCode::ExtendArg_A:
  16228. #ifdef ENABLE_DOM_FAST_PATH
  16229. case Js::OpCode::DOMFastPathGetter:
  16230. case Js::OpCode::DOMFastPathSetter:
  16231. #endif
  16232. case Js::OpCode::NewScopeSlots:
  16233. case Js::OpCode::NewScopeSlotsWithoutPropIds:
  16234. case Js::OpCode::NewStackScopeSlots:
  16235. case Js::OpCode::IsInst:
  16236. case Js::OpCode::BailOnEqual:
  16237. case Js::OpCode::BailOnNotEqual:
  16238. case Js::OpCode::StInt8ArrViewElem:
  16239. case Js::OpCode::StUInt8ArrViewElem:
  16240. case Js::OpCode::StInt16ArrViewElem:
  16241. case Js::OpCode::StUInt16ArrViewElem:
  16242. case Js::OpCode::StInt32ArrViewElem:
  16243. case Js::OpCode::StUInt32ArrViewElem:
  16244. case Js::OpCode::StFloat32ArrViewElem:
  16245. case Js::OpCode::StFloat64ArrViewElem:
  16246. return;
  16247. }
  16248. if (!src1->IsImmediateOpnd())
  16249. {
  16250. return;
  16251. }
  16252. // The fast paths or lowering of the remaining instructions may not support handling immediate opnds for the first src. The
  16253. // immediate src1 is hoisted here into a separate instruction.
  16254. if (src1->IsIntConstOpnd())
  16255. {
  16256. IR::Instr *newInstr = instr->HoistSrc1(Js::OpCode::Ld_I4);
  16257. ToInt32Dst(newInstr, newInstr->GetDst()->AsRegOpnd(), this->currentBlock);
  16258. }
  16259. else
  16260. {
  16261. instr->HoistSrc1(Js::OpCode::Ld_A);
  16262. }
  16263. src1 = instr->GetSrc1();
  16264. src1->AsRegOpnd()->m_sym->SetIsConst();
  16265. }
  16266. // Clear the ValueMap pf the values invalidated by this instr.
  16267. void
  16268. GlobOpt::ProcessKills(IR::Instr *instr)
  16269. {
  16270. this->ProcessFieldKills(instr);
  16271. this->ProcessValueKills(instr);
  16272. this->ProcessArrayValueKills(instr);
  16273. }
  16274. bool
  16275. GlobOpt::OptIsInvariant(IR::Opnd *src, BasicBlock *block, Loop *loop, Value *srcVal, bool isNotTypeSpecConv, bool allowNonPrimitives)
  16276. {
  16277. if(!loop->CanHoistInvariants())
  16278. {
  16279. return false;
  16280. }
  16281. Sym *sym;
  16282. switch(src->GetKind())
  16283. {
  16284. case IR::OpndKindAddr:
  16285. case IR::OpndKindFloatConst:
  16286. case IR::OpndKindIntConst:
  16287. return true;
  16288. case IR::OpndKindReg:
  16289. sym = src->AsRegOpnd()->m_sym;
  16290. break;
  16291. case IR::OpndKindSym:
  16292. sym = src->AsSymOpnd()->m_sym;
  16293. if (src->AsSymOpnd()->IsPropertySymOpnd())
  16294. {
  16295. if (src->AsSymOpnd()->AsPropertySymOpnd()->IsTypeChecked())
  16296. {
  16297. // We do not handle hoisting these yet. We might be hoisting this across the instr with the type check protecting this one.
  16298. // And somehow, the dead-store pass now removes the type check on that instr later on...
  16299. // For CheckFixedFld, there is no benefit hoisting these if they don't have a type check as they won't generate code.
  16300. return false;
  16301. }
  16302. }
  16303. break;
  16304. case IR::OpndKindHelperCall:
  16305. // Helper calls, like the private slot getter, can be invariant.
  16306. // Consider moving more math builtin to invariant?
  16307. return HelperMethodAttributes::IsInVariant(src->AsHelperCallOpnd()->m_fnHelper);
  16308. default:
  16309. return false;
  16310. }
  16311. return OptIsInvariant(sym, block, loop, srcVal, isNotTypeSpecConv, allowNonPrimitives);
  16312. }
  16313. bool
  16314. GlobOpt::OptIsInvariant(Sym *sym, BasicBlock *block, Loop *loop, Value *srcVal, bool isNotTypeSpecConv, bool allowNonPrimitives, Value **loopHeadValRef)
  16315. {
  16316. Value *localLoopHeadVal;
  16317. if(!loopHeadValRef)
  16318. {
  16319. loopHeadValRef = &localLoopHeadVal;
  16320. }
  16321. Value *&loopHeadVal = *loopHeadValRef;
  16322. loopHeadVal = nullptr;
  16323. if(!loop->CanHoistInvariants())
  16324. {
  16325. return false;
  16326. }
  16327. if (sym->IsStackSym())
  16328. {
  16329. if (sym->AsStackSym()->IsTypeSpec())
  16330. {
  16331. StackSym *varSym = sym->AsStackSym()->GetVarEquivSym(this->func);
  16332. // Make sure the int32/float64 version of this is available.
  16333. // Note: We could handle this by converting the src, but usually the
  16334. // conversion is hoistable if this is hoistable anyway.
  16335. // In some weird cases it may not be however, so we'll bail out.
  16336. if (sym->AsStackSym()->IsInt32())
  16337. {
  16338. Assert(block->globOptData.liveInt32Syms->Test(varSym->m_id));
  16339. if (!loop->landingPad->globOptData.liveInt32Syms->Test(varSym->m_id) ||
  16340. loop->landingPad->globOptData.liveLossyInt32Syms->Test(varSym->m_id) &&
  16341. !block->globOptData.liveLossyInt32Syms->Test(varSym->m_id))
  16342. {
  16343. // Either the int32 sym is not live in the landing pad, or it's lossy in the landing pad and the
  16344. // instruction's block is using the lossless version. In either case, the instruction cannot be hoisted
  16345. // without doing a conversion of this operand.
  16346. return false;
  16347. }
  16348. }
  16349. else if (sym->AsStackSym()->IsFloat64())
  16350. {
  16351. if (!loop->landingPad->globOptData.liveFloat64Syms->Test(varSym->m_id))
  16352. {
  16353. return false;
  16354. }
  16355. }
  16356. else
  16357. {
  16358. Assert(sym->AsStackSym()->IsSimd128());
  16359. if (!loop->landingPad->globOptData.liveSimd128F4Syms->Test(varSym->m_id) && !loop->landingPad->globOptData.liveSimd128I4Syms->Test(varSym->m_id))
  16360. {
  16361. return false;
  16362. }
  16363. }
  16364. sym = sym->AsStackSym()->GetVarEquivSym(this->func);
  16365. }
  16366. else
  16367. {
  16368. // Make sure the var version of this is available.
  16369. // Note: We could handle this by converting the src, but usually the
  16370. // conversion is hoistable if this is hoistable anyway.
  16371. // In some weird cases it may not be however, so we'll bail out.
  16372. if (!loop->landingPad->globOptData.liveVarSyms->Test(sym->m_id))
  16373. {
  16374. return false;
  16375. }
  16376. }
  16377. }
  16378. else if (sym->IsPropertySym())
  16379. {
  16380. if (!loop->landingPad->globOptData.liveFields->Test(sym->m_id))
  16381. {
  16382. return false;
  16383. }
  16384. }
  16385. else
  16386. {
  16387. return false;
  16388. }
  16389. // We rely on having a value.
  16390. if (srcVal == NULL)
  16391. {
  16392. return false;
  16393. }
  16394. // Can't hoist non-primitives, unless we have safeguards against valueof/tostring.
  16395. if (!allowNonPrimitives && !srcVal->GetValueInfo()->IsPrimitive() && !this->IsTypeSpecialized(sym, loop->landingPad))
  16396. {
  16397. return false;
  16398. }
  16399. if(!isNotTypeSpecConv && loop->symsDefInLoop->Test(sym->m_id))
  16400. {
  16401. // Typically, a sym is considered invariant if it has the same value in the current block and in the loop landing pad.
  16402. // The sym may have had a different value earlier in the loop or on the back-edge, but as long as it's reassigned to its
  16403. // value outside the loop, it would be considered invariant in this block. Consider that case:
  16404. // s1 = s2[invariant]
  16405. // <loop start>
  16406. // s1 = s2[invariant]
  16407. // // s1 now has the same value as in the landing pad, and is considered invariant
  16408. // s1 += s3
  16409. // // s1 is not invariant here, or on the back-edge
  16410. // ++s3 // s3 is not invariant, so the add above cannot be hoisted
  16411. // <loop end>
  16412. //
  16413. // A problem occurs at the point of (s1 += s3) when:
  16414. // - At (s1 = s2) inside the loop, s1 was made to be the sym store of that value. This by itself is legal, because
  16415. // after that transfer, s1 and s2 have the same value.
  16416. // - (s1 += s3) is type-specialized but s1 is not specialized in the loop header. This happens when s1 is not
  16417. // specialized entering the loop, and since s1 is not used before it's defined in the loop, it's not specialized
  16418. // on back-edges.
  16419. //
  16420. // With that, at (s1 += s3), the conversion of s1 to the type-specialized version would be hoisted because s1 is
  16421. // invariant just before that instruction. Since this add is specialized, the specialized version of the sym is modified
  16422. // in the loop without a reassignment at (s1 = s2) inside the loop, and (s1 += s3) would then use an incorrect value of
  16423. // s1 (it would use the value of s1 from the previous loop iteration, instead of using the value of s2).
  16424. //
  16425. // The problem here, is that we cannot hoist the conversion of s1 into its specialized version across the assignment
  16426. // (s1 = s2) inside the loop. So for the purposes of type specialization, don't consider a sym invariant if it has a def
  16427. // inside the loop.
  16428. return false;
  16429. }
  16430. // A symbol is invariant if it's current value is the same as it was upon entering the loop.
  16431. loopHeadVal = this->FindValue(loop->landingPad->globOptData.symToValueMap, sym);
  16432. if (loopHeadVal == NULL || loopHeadVal->GetValueNumber() != srcVal->GetValueNumber())
  16433. {
  16434. return false;
  16435. }
  16436. // For values with an int range, require additionally that the range is the same as in the landing pad, as the range may
  16437. // have been changed on this path based on branches, and int specialization and invariant hoisting may rely on the range
  16438. // being the same. For type spec conversions, only require that if the value is an int constant in the current block, that
  16439. // it is also an int constant with the same value in the landing pad. Other range differences don't matter for type spec.
  16440. IntConstantBounds srcIntConstantBounds, loopHeadIntConstantBounds;
  16441. if(srcVal->GetValueInfo()->TryGetIntConstantBounds(&srcIntConstantBounds) &&
  16442. (isNotTypeSpecConv || srcIntConstantBounds.IsConstant()) &&
  16443. (
  16444. !loopHeadVal->GetValueInfo()->TryGetIntConstantBounds(&loopHeadIntConstantBounds) ||
  16445. loopHeadIntConstantBounds.LowerBound() != srcIntConstantBounds.LowerBound() ||
  16446. loopHeadIntConstantBounds.UpperBound() != srcIntConstantBounds.UpperBound()
  16447. ))
  16448. {
  16449. return false;
  16450. }
  16451. return true;
  16452. }
  16453. bool
  16454. GlobOpt::OptIsInvariant(
  16455. IR::Instr *instr,
  16456. BasicBlock *block,
  16457. Loop *loop,
  16458. Value *src1Val,
  16459. Value *src2Val,
  16460. bool isNotTypeSpecConv,
  16461. const bool forceInvariantHoisting)
  16462. {
  16463. if (!loop->CanHoistInvariants())
  16464. {
  16465. return false;
  16466. }
  16467. if (!OpCodeAttr::CanCSE(instr->m_opcode))
  16468. {
  16469. return false;
  16470. }
  16471. bool allowNonPrimitives = !OpCodeAttr::CallsValueOf(instr->m_opcode);
  16472. switch(instr->m_opcode)
  16473. {
  16474. // Can't legally hoist these
  16475. case Js::OpCode::LdLen_A:
  16476. return false;
  16477. // Usually not worth hoisting these
  16478. case Js::OpCode::LdStr:
  16479. case Js::OpCode::Ld_A:
  16480. case Js::OpCode::Ld_I4:
  16481. case Js::OpCode::LdC_A_I4:
  16482. if(!forceInvariantHoisting)
  16483. {
  16484. return false;
  16485. }
  16486. break;
  16487. // Can't hoist these outside the function it's for. The LdArgumentsFromFrame for an inlinee depends on the inlinee meta arg
  16488. // that holds the arguments object, which is only initialized at the start of the inlinee. So, can't hoist this outside the
  16489. // inlinee.
  16490. case Js::OpCode::LdArgumentsFromFrame:
  16491. if(instr->m_func != loop->GetFunc())
  16492. {
  16493. return false;
  16494. }
  16495. break;
  16496. case Js::OpCode::FromVar:
  16497. if (instr->HasBailOutInfo())
  16498. {
  16499. allowNonPrimitives = true;
  16500. }
  16501. break;
  16502. }
  16503. IR::Opnd *dst = instr->GetDst();
  16504. if (dst && !dst->IsRegOpnd())
  16505. {
  16506. return false;
  16507. }
  16508. IR::Opnd *src1 = instr->GetSrc1();
  16509. if (src1)
  16510. {
  16511. if (!this->OptIsInvariant(src1, block, loop, src1Val, isNotTypeSpecConv, allowNonPrimitives))
  16512. {
  16513. return false;
  16514. }
  16515. IR::Opnd *src2 = instr->GetSrc2();
  16516. if (src2)
  16517. {
  16518. if (!this->OptIsInvariant(src2, block, loop, src2Val, isNotTypeSpecConv, allowNonPrimitives))
  16519. {
  16520. return false;
  16521. }
  16522. }
  16523. }
  16524. return true;
  16525. }
  16526. bool
  16527. GlobOpt::OptDstIsInvariant(IR::RegOpnd *dst)
  16528. {
  16529. StackSym *dstSym = dst->m_sym;
  16530. if (dstSym->IsTypeSpec())
  16531. {
  16532. // The type-specialized sym may be single def, but not the original...
  16533. dstSym = dstSym->GetVarEquivSym(this->func);
  16534. }
  16535. return (dstSym->m_isSingleDef);
  16536. }
  16537. void
  16538. GlobOpt::OptHoistInvariant(
  16539. IR::Instr *instr,
  16540. BasicBlock *block,
  16541. Loop *loop,
  16542. Value *dstVal,
  16543. Value *const src1Val,
  16544. bool isNotTypeSpecConv,
  16545. bool lossy)
  16546. {
  16547. BasicBlock *landingPad = loop->landingPad;
  16548. IR::RegOpnd *dst = instr->GetDst() ? instr->GetDst()->AsRegOpnd() : nullptr;
  16549. if(dst)
  16550. {
  16551. switch(instr->m_opcode)
  16552. {
  16553. case Js::OpCode::CmEq_I4:
  16554. case Js::OpCode::CmNeq_I4:
  16555. case Js::OpCode::CmLt_I4:
  16556. case Js::OpCode::CmLe_I4:
  16557. case Js::OpCode::CmGt_I4:
  16558. case Js::OpCode::CmGe_I4:
  16559. case Js::OpCode::CmUnLt_I4:
  16560. case Js::OpCode::CmUnLe_I4:
  16561. case Js::OpCode::CmUnGt_I4:
  16562. case Js::OpCode::CmUnGe_I4:
  16563. // These operations are a special case. They generate a lossy int value, and the var sym is initialized using
  16564. // Conv_Bool. A sym cannot be live only as a lossy int sym, the var needs to be live as well since the lossy int
  16565. // sym cannot be used to convert to var. We don't know however, whether the Conv_Bool will be hoisted. The idea
  16566. // currently is that the sym is only used on the path in which it is initialized inside the loop. So, don't
  16567. // hoist any liveness info for the dst.
  16568. if (!this->GetIsAsmJSFunc())
  16569. {
  16570. lossy = true;
  16571. }
  16572. break;
  16573. }
  16574. if (dstVal == NULL)
  16575. {
  16576. dstVal = this->NewGenericValue(ValueType::Uninitialized, dst);
  16577. }
  16578. // ToVar/FromVar don't need a new dst because it has to be invariant if their src is invariant.
  16579. bool dstDoesntNeedLoad = (!isNotTypeSpecConv && instr->m_opcode != Js::OpCode::LdC_A_I4);
  16580. StackSym *varSym = dst->m_sym;
  16581. if (varSym->IsTypeSpec())
  16582. {
  16583. varSym = varSym->GetVarEquivSym(this->func);
  16584. }
  16585. Value *const landingPadDstVal = FindValue(loop->landingPad->globOptData.symToValueMap, varSym);
  16586. if(landingPadDstVal
  16587. ? dstVal->GetValueNumber() != landingPadDstVal->GetValueNumber()
  16588. : loop->symsDefInLoop->Test(varSym->m_id))
  16589. {
  16590. // We need a temp for FromVar/ToVar if dst changes in the loop.
  16591. dstDoesntNeedLoad = false;
  16592. }
  16593. if (!dstDoesntNeedLoad && this->OptDstIsInvariant(dst) == false)
  16594. {
  16595. // Keep dst in place, hoist instr using a new dst.
  16596. instr->UnlinkDst();
  16597. // Set type specialization info correctly for this new sym
  16598. StackSym *copyVarSym;
  16599. IR::RegOpnd *copyReg;
  16600. if (dst->m_sym->IsTypeSpec())
  16601. {
  16602. copyVarSym = StackSym::New(TyVar, instr->m_func);
  16603. StackSym *copySym = copyVarSym;
  16604. if (dst->m_sym->IsInt32())
  16605. {
  16606. if(lossy)
  16607. {
  16608. // The new sym would only be live as a lossy int since we're only hoisting the store to the int version
  16609. // of the sym, and cannot be converted to var. It is not legal to have a sym only live as a lossy int,
  16610. // so don't update liveness info for this sym.
  16611. }
  16612. else
  16613. {
  16614. block->globOptData.liveInt32Syms->Set(copyVarSym->m_id);
  16615. }
  16616. copySym = copySym->GetInt32EquivSym(instr->m_func);
  16617. }
  16618. else if (dst->m_sym->IsFloat64())
  16619. {
  16620. block->globOptData.liveFloat64Syms->Set(copyVarSym->m_id);
  16621. copySym = copySym->GetFloat64EquivSym(instr->m_func);
  16622. }
  16623. else if (dst->IsSimd128())
  16624. {
  16625. // SIMD_JS
  16626. if (dst->IsSimd128F4())
  16627. {
  16628. block->globOptData.liveSimd128F4Syms->Set(copyVarSym->m_id);
  16629. copySym = copySym->GetSimd128F4EquivSym(instr->m_func);
  16630. }
  16631. else
  16632. {
  16633. Assert(dst->IsSimd128I4());
  16634. block->globOptData.liveSimd128I4Syms->Set(copyVarSym->m_id);
  16635. copySym = copySym->GetSimd128I4EquivSym(instr->m_func);
  16636. }
  16637. }
  16638. copyReg = IR::RegOpnd::New(copySym, copySym->GetType(), instr->m_func);
  16639. }
  16640. else
  16641. {
  16642. copyReg = IR::RegOpnd::New(dst->GetType(), instr->m_func);
  16643. copyVarSym = copyReg->m_sym;
  16644. block->globOptData.liveVarSyms->Set(copyVarSym->m_id);
  16645. }
  16646. copyReg->SetValueType(dst->GetValueType());
  16647. IR::Instr *copyInstr = IR::Instr::New(Js::OpCode::Ld_A, dst, copyReg, instr->m_func);
  16648. copyInstr->SetByteCodeOffset(instr);
  16649. instr->SetDst(copyReg);
  16650. instr->InsertBefore(copyInstr);
  16651. dst->m_sym->m_mayNotBeTempLastUse = true;
  16652. if (instr->GetSrc1() && instr->GetSrc1()->IsImmediateOpnd())
  16653. {
  16654. // Propagate IsIntConst if appropriate
  16655. switch(instr->m_opcode)
  16656. {
  16657. case Js::OpCode::Ld_A:
  16658. case Js::OpCode::Ld_I4:
  16659. case Js::OpCode::LdC_A_I4:
  16660. copyReg->m_sym->SetIsConst();
  16661. break;
  16662. }
  16663. }
  16664. ValueInfo *dstValueInfo = dstVal->GetValueInfo();
  16665. if((!dstValueInfo->GetSymStore() || dstValueInfo->GetSymStore() == varSym) && !lossy)
  16666. {
  16667. // The destination's value may have been transferred from one of the invariant sources, in which case we should
  16668. // keep the sym store intact, as that sym will likely have a better lifetime than this new copy sym. For
  16669. // instance, if we're inside a conditioned block, because we don't make the copy sym live and set its value in
  16670. // all preceding blocks, this sym would not be live after exiting this block, causing this value to not
  16671. // participate in copy-prop after this block.
  16672. dstValueInfo->SetSymStore(copyVarSym);
  16673. }
  16674. this->InsertNewValue(&block->globOptData, dstVal, copyReg);
  16675. dst = copyReg;
  16676. }
  16677. }
  16678. // Move to landing pad
  16679. block->UnlinkInstr(instr);
  16680. if (loop->bailOutInfo->bailOutInstr)
  16681. {
  16682. loop->bailOutInfo->bailOutInstr->InsertBefore(instr);
  16683. }
  16684. else
  16685. {
  16686. landingPad->InsertAfter(instr);
  16687. }
  16688. GlobOpt::MarkNonByteCodeUsed(instr);
  16689. if (instr->HasBailOutInfo() || instr->HasAuxBailOut())
  16690. {
  16691. Assert(loop->bailOutInfo);
  16692. EnsureBailTarget(loop);
  16693. // Copy bailout info of loop top.
  16694. instr->ReplaceBailOutInfo(loop->bailOutInfo);
  16695. }
  16696. if (instr->GetSrc1())
  16697. {
  16698. // We are hoisting this instruction possibly past other uses, which might invalidate the last use info. Clear it.
  16699. IR::Opnd *src1 = instr->GetSrc1();
  16700. if (src1->IsRegOpnd())
  16701. {
  16702. src1->AsRegOpnd()->m_isTempLastUse = false;
  16703. }
  16704. if (instr->GetSrc2())
  16705. {
  16706. IR::Opnd *src2 = instr->GetSrc2();
  16707. if (src2->IsRegOpnd())
  16708. {
  16709. src2->AsRegOpnd()->m_isTempLastUse = false;
  16710. }
  16711. }
  16712. }
  16713. if(!dst)
  16714. {
  16715. return;
  16716. }
  16717. // The bailout info's liveness for the dst sym is not updated in loop landing pads because bailout instructions previously
  16718. // hoisted into the loop's landing pad may bail out before the current type of the dst sym became live (perhaps due to this
  16719. // instruction). Since the landing pad will have a shared bailout point, the bailout info cannot assume that the current
  16720. // type of the dst sym was live during every bailout hoisted into the landing pad.
  16721. StackSym *const dstSym = dst->m_sym;
  16722. StackSym *const dstVarSym = dstSym->IsTypeSpec() ? dstSym->GetVarEquivSym(nullptr) : dstSym;
  16723. Assert(dstVarSym);
  16724. if(isNotTypeSpecConv || !IsLive(dstVarSym, loop->landingPad))
  16725. {
  16726. // A new dst is being hoisted, or the same single-def dst that would not be live before this block. So, make it live and
  16727. // update the value info with the same value info in this block.
  16728. if(lossy)
  16729. {
  16730. // This is a lossy conversion to int. The instruction was given a new dst specifically for hoisting, so this new dst
  16731. // will not be live as a var before this block. A sym cannot be live only as a lossy int sym, the var needs to be
  16732. // live as well since the lossy int sym cannot be used to convert to var. Since the var version of the sym is not
  16733. // going to be initialized, don't hoist any liveness info for the dst. The sym is only going to be used on the path
  16734. // in which it is initialized inside the loop.
  16735. Assert(dstSym->IsTypeSpec());
  16736. Assert(dstSym->IsInt32());
  16737. return;
  16738. }
  16739. // Check if the dst value was transferred from the src. If so, the value transfer needs to be replicated.
  16740. bool isTransfer = dstVal == src1Val;
  16741. StackSym *transferValueOfSym = nullptr;
  16742. if(isTransfer)
  16743. {
  16744. Assert(instr->GetSrc1());
  16745. if(instr->GetSrc1()->IsRegOpnd())
  16746. {
  16747. StackSym *src1Sym = instr->GetSrc1()->AsRegOpnd()->m_sym;
  16748. if(src1Sym->IsTypeSpec())
  16749. {
  16750. src1Sym = src1Sym->GetVarEquivSym(nullptr);
  16751. Assert(src1Sym);
  16752. }
  16753. if(dstVal == FindValue(block->globOptData.symToValueMap, src1Sym))
  16754. {
  16755. transferValueOfSym = src1Sym;
  16756. }
  16757. }
  16758. }
  16759. // SIMD_JS
  16760. if (instr->m_opcode == Js::OpCode::ExtendArg_A)
  16761. {
  16762. // Check if we should have CSE'ed this EA
  16763. Assert(instr->GetSrc1());
  16764. // If the dstVal symstore is not the dst itself, then we copied the Value from another expression.
  16765. if (dstVal->GetValueInfo()->GetSymStore() != instr->GetDst()->GetStackSym())
  16766. {
  16767. isTransfer = true;
  16768. transferValueOfSym = dstVal->GetValueInfo()->GetSymStore()->AsStackSym();
  16769. }
  16770. }
  16771. const ValueNumber dstValueNumber = dstVal->GetValueNumber();
  16772. ValueNumber dstNewValueNumber = InvalidValueNumber;
  16773. for(InvariantBlockBackwardIterator it(this, block, loop->landingPad, nullptr); it.IsValid(); it.MoveNext())
  16774. {
  16775. BasicBlock *const hoistBlock = it.Block();
  16776. GlobOptBlockData &hoistBlockData = hoistBlock->globOptData;
  16777. Assert(!IsLive(dstVarSym, &hoistBlockData));
  16778. MakeLive(dstSym, &hoistBlockData, lossy);
  16779. Value *newDstValue;
  16780. do
  16781. {
  16782. if(isTransfer)
  16783. {
  16784. if(transferValueOfSym)
  16785. {
  16786. newDstValue = FindValue(hoistBlockData.symToValueMap, transferValueOfSym);
  16787. if(newDstValue && newDstValue->GetValueNumber() == dstValueNumber)
  16788. {
  16789. break;
  16790. }
  16791. }
  16792. // It's a transfer, but we don't have a sym whose value number matches in the target block. Use a new value
  16793. // number since we don't know if there is already a value with the current number for the target block.
  16794. if(dstNewValueNumber == InvalidValueNumber)
  16795. {
  16796. dstNewValueNumber = NewValueNumber();
  16797. }
  16798. newDstValue = CopyValue(dstVal, dstNewValueNumber);
  16799. break;
  16800. }
  16801. newDstValue = CopyValue(dstVal, dstValueNumber);
  16802. } while(false);
  16803. SetValue(&hoistBlockData, newDstValue, dstVarSym);
  16804. }
  16805. return;
  16806. }
  16807. #if DBG
  16808. if(instr->GetSrc1()->IsRegOpnd()) // Type spec conversion may load a constant into a dst sym
  16809. {
  16810. StackSym *const srcSym = instr->GetSrc1()->AsRegOpnd()->m_sym;
  16811. Assert(srcSym != dstSym); // Type spec conversion must be changing the type, so the syms must be different
  16812. StackSym *const srcVarSym = srcSym->IsTypeSpec() ? srcSym->GetVarEquivSym(nullptr) : srcSym;
  16813. Assert(srcVarSym == dstVarSym); // Type spec conversion must be between variants of the same var sym
  16814. }
  16815. #endif
  16816. bool changeValueType = false, changeValueTypeToInt = false;
  16817. if(dstSym->IsTypeSpec())
  16818. {
  16819. if(dst->IsInt32())
  16820. {
  16821. if(!lossy)
  16822. {
  16823. Assert(
  16824. !instr->HasBailOutInfo() ||
  16825. instr->GetBailOutKind() == IR::BailOutIntOnly ||
  16826. instr->GetBailOutKind() == IR::BailOutExpectingInteger);
  16827. changeValueType = changeValueTypeToInt = true;
  16828. }
  16829. }
  16830. else if (dst->IsFloat64())
  16831. {
  16832. if(instr->HasBailOutInfo() && instr->GetBailOutKind() == IR::BailOutNumberOnly)
  16833. {
  16834. changeValueType = true;
  16835. }
  16836. }
  16837. else
  16838. {
  16839. // SIMD_JS
  16840. Assert(dst->IsSimd128());
  16841. if (instr->HasBailOutInfo() &&
  16842. (instr->GetBailOutKind() == IR::BailOutSimd128F4Only || instr->GetBailOutKind() == IR::BailOutSimd128I4Only))
  16843. {
  16844. changeValueType = true;
  16845. }
  16846. }
  16847. }
  16848. ValueInfo *previousValueInfoBeforeUpdate = nullptr, *previousValueInfoAfterUpdate = nullptr;
  16849. for(InvariantBlockBackwardIterator it(
  16850. this,
  16851. block,
  16852. loop->landingPad,
  16853. dstVarSym,
  16854. dstVal->GetValueNumber());
  16855. it.IsValid();
  16856. it.MoveNext())
  16857. {
  16858. BasicBlock *const hoistBlock = it.Block();
  16859. GlobOptBlockData &hoistBlockData = hoistBlock->globOptData;
  16860. #if DBG
  16861. // TODO: There are some odd cases with field hoisting where the sym is invariant in only part of the loop and the info
  16862. // does not flow through all blocks. Un-comment the verification below after PRE replaces field hoisting.
  16863. //// Verify that the src sym is live as the required type, and that the conversion is valid
  16864. //Assert(IsLive(dstVarSym, &hoistBlockData));
  16865. //if(instr->GetSrc1()->IsRegOpnd())
  16866. //{
  16867. // IR::RegOpnd *const src = instr->GetSrc1()->AsRegOpnd();
  16868. // StackSym *const srcSym = instr->GetSrc1()->AsRegOpnd()->m_sym;
  16869. // if(srcSym->IsTypeSpec())
  16870. // {
  16871. // if(src->IsInt32())
  16872. // {
  16873. // Assert(hoistBlockData.liveInt32Syms->Test(dstVarSym->m_id));
  16874. // Assert(!hoistBlockData.liveLossyInt32Syms->Test(dstVarSym->m_id)); // shouldn't try to convert a lossy int32 to anything
  16875. // }
  16876. // else
  16877. // {
  16878. // Assert(src->IsFloat64());
  16879. // Assert(hoistBlockData.liveFloat64Syms->Test(dstVarSym->m_id));
  16880. // if(dstSym->IsTypeSpec() && dst->IsInt32())
  16881. // {
  16882. // Assert(lossy); // shouldn't try to do a lossless conversion from float64 to int32
  16883. // }
  16884. // }
  16885. // }
  16886. // else
  16887. // {
  16888. // Assert(hoistBlockData.liveVarSyms->Test(dstVarSym->m_id));
  16889. // }
  16890. //}
  16891. //if(dstSym->IsTypeSpec() && dst->IsInt32())
  16892. //{
  16893. // // If the sym is already specialized as required in the block to which we are attempting to hoist the conversion,
  16894. // // that info should have flowed into this block
  16895. // if(lossy)
  16896. // {
  16897. // Assert(!hoistBlockData.liveInt32Syms->Test(dstVarSym->m_id));
  16898. // }
  16899. // else
  16900. // {
  16901. // Assert(!IsInt32TypeSpecialized(dstVarSym, hoistBlock));
  16902. // }
  16903. //}
  16904. #endif
  16905. MakeLive(dstSym, &hoistBlockData, lossy);
  16906. if(!changeValueType)
  16907. {
  16908. continue;
  16909. }
  16910. Value *const hoistBlockValue = it.InvariantSymValue();
  16911. ValueInfo *const hoistBlockValueInfo = hoistBlockValue->GetValueInfo();
  16912. if(hoistBlockValueInfo == previousValueInfoBeforeUpdate)
  16913. {
  16914. if(hoistBlockValueInfo != previousValueInfoAfterUpdate)
  16915. {
  16916. HoistInvariantValueInfo(previousValueInfoAfterUpdate, hoistBlockValue, hoistBlock);
  16917. }
  16918. }
  16919. else
  16920. {
  16921. previousValueInfoBeforeUpdate = hoistBlockValueInfo;
  16922. ValueInfo *const newValueInfo =
  16923. changeValueTypeToInt
  16924. ? hoistBlockValueInfo->SpecializeToInt32(alloc)
  16925. : hoistBlockValueInfo->SpecializeToFloat64(alloc);
  16926. previousValueInfoAfterUpdate = newValueInfo;
  16927. ChangeValueInfo(changeValueTypeToInt ? nullptr : hoistBlock, hoistBlockValue, newValueInfo);
  16928. }
  16929. }
  16930. }
  16931. bool
  16932. GlobOpt::TryHoistInvariant(
  16933. IR::Instr *instr,
  16934. BasicBlock *block,
  16935. Value *dstVal,
  16936. Value *src1Val,
  16937. Value *src2Val,
  16938. bool isNotTypeSpecConv,
  16939. const bool lossy,
  16940. const bool forceInvariantHoisting)
  16941. {
  16942. Assert(!this->IsLoopPrePass());
  16943. if (OptIsInvariant(instr, block, block->loop, src1Val, src2Val, isNotTypeSpecConv, forceInvariantHoisting))
  16944. {
  16945. #if DBG
  16946. if (Js::Configuration::Global.flags.Trace.IsEnabled(Js::InvariantsPhase, this->func->GetSourceContextId(), this->func->GetLocalFunctionId()))
  16947. {
  16948. Output::Print(_u(" **** INVARIANT *** "));
  16949. instr->Dump();
  16950. }
  16951. #endif
  16952. #if ENABLE_DEBUG_CONFIG_OPTIONS
  16953. if (Js::Configuration::Global.flags.TestTrace.IsEnabled(Js::InvariantsPhase))
  16954. {
  16955. Output::Print(_u(" **** INVARIANT *** "));
  16956. Output::Print(_u("%s \n"), Js::OpCodeUtil::GetOpCodeName(instr->m_opcode));
  16957. }
  16958. #endif
  16959. Loop *loop = block->loop;
  16960. // Try hoisting from to outer most loop
  16961. while (loop->parent && OptIsInvariant(instr, block, loop->parent, src1Val, src2Val, isNotTypeSpecConv, forceInvariantHoisting))
  16962. {
  16963. loop = loop->parent;
  16964. }
  16965. // Record the byte code use here since we are going to move this instruction up
  16966. if (isNotTypeSpecConv)
  16967. {
  16968. InsertNoImplicitCallUses(instr);
  16969. this->CaptureByteCodeSymUses(instr);
  16970. this->InsertByteCodeUses(instr, true);
  16971. }
  16972. #if DBG
  16973. else
  16974. {
  16975. PropertySym *propertySymUse = NULL;
  16976. NoRecoverMemoryJitArenaAllocator tempAllocator(_u("BE-GlobOpt-Temp"), this->alloc->GetPageAllocator(), Js::Throw::OutOfMemory);
  16977. BVSparse<JitArenaAllocator> * tempByteCodeUse = JitAnew(&tempAllocator, BVSparse<JitArenaAllocator>, &tempAllocator);
  16978. GlobOpt::TrackByteCodeSymUsed(instr, tempByteCodeUse, &propertySymUse);
  16979. Assert(tempByteCodeUse->Count() == 0 && propertySymUse == NULL);
  16980. }
  16981. #endif
  16982. OptHoistInvariant(instr, block, loop, dstVal, src1Val, isNotTypeSpecConv, lossy);
  16983. return true;
  16984. }
  16985. return false;
  16986. }
  16987. InvariantBlockBackwardIterator::InvariantBlockBackwardIterator(
  16988. GlobOpt *const globOpt,
  16989. BasicBlock *const exclusiveBeginBlock,
  16990. BasicBlock *const inclusiveEndBlock,
  16991. StackSym *const invariantSym,
  16992. const ValueNumber invariantSymValueNumber)
  16993. : globOpt(globOpt),
  16994. exclusiveEndBlock(inclusiveEndBlock->prev),
  16995. invariantSym(invariantSym),
  16996. invariantSymValueNumber(invariantSymValueNumber),
  16997. block(exclusiveBeginBlock)
  16998. #if DBG
  16999. ,
  17000. inclusiveEndBlock(inclusiveEndBlock)
  17001. #endif
  17002. {
  17003. Assert(exclusiveBeginBlock);
  17004. Assert(inclusiveEndBlock);
  17005. Assert(!inclusiveEndBlock->isDeleted);
  17006. Assert(exclusiveBeginBlock != inclusiveEndBlock);
  17007. Assert(!invariantSym == (invariantSymValueNumber == InvalidValueNumber));
  17008. MoveNext();
  17009. }
  17010. bool
  17011. InvariantBlockBackwardIterator::IsValid() const
  17012. {
  17013. return block != exclusiveEndBlock;
  17014. }
  17015. void
  17016. InvariantBlockBackwardIterator::MoveNext()
  17017. {
  17018. Assert(IsValid());
  17019. while(true)
  17020. {
  17021. #if DBG
  17022. BasicBlock *const previouslyIteratedBlock = block;
  17023. #endif
  17024. block = block->prev;
  17025. if(!IsValid())
  17026. {
  17027. Assert(previouslyIteratedBlock == inclusiveEndBlock);
  17028. break;
  17029. }
  17030. if(block->isDeleted)
  17031. {
  17032. continue;
  17033. }
  17034. if(!block->globOptData.HasData())
  17035. {
  17036. // This block's info has already been merged with all of its successors
  17037. continue;
  17038. }
  17039. if(!invariantSym)
  17040. {
  17041. break;
  17042. }
  17043. invariantSymValue = globOpt->FindValue(block->globOptData.symToValueMap, invariantSym);
  17044. if(!invariantSymValue || invariantSymValue->GetValueNumber() != invariantSymValueNumber)
  17045. {
  17046. // BailOnNoProfile and throw blocks are not moved outside loops. A sym table cleanup on these paths may delete the
  17047. // values. Field hoisting also has some odd cases where the hoisted stack sym is invariant in only part of the loop.
  17048. continue;
  17049. }
  17050. break;
  17051. }
  17052. }
  17053. BasicBlock *
  17054. InvariantBlockBackwardIterator::Block() const
  17055. {
  17056. Assert(IsValid());
  17057. return block;
  17058. }
  17059. Value *
  17060. InvariantBlockBackwardIterator::InvariantSymValue() const
  17061. {
  17062. Assert(IsValid());
  17063. Assert(invariantSym);
  17064. return invariantSymValue;
  17065. }
  17066. void
  17067. GlobOpt::HoistInvariantValueInfo(
  17068. ValueInfo *const invariantValueInfoToHoist,
  17069. Value *const valueToUpdate,
  17070. BasicBlock *const targetBlock)
  17071. {
  17072. Assert(invariantValueInfoToHoist);
  17073. Assert(valueToUpdate);
  17074. Assert(targetBlock);
  17075. // Why are we trying to change the value type of the type sym value? Asserting here to make sure we don't deep copy the type sym's value info.
  17076. Assert(!invariantValueInfoToHoist->IsJsType());
  17077. Sym *const symStore = valueToUpdate->GetValueInfo()->GetSymStore();
  17078. ValueInfo *newValueInfo;
  17079. if(invariantValueInfoToHoist->GetSymStore() == symStore)
  17080. {
  17081. newValueInfo = invariantValueInfoToHoist;
  17082. }
  17083. else
  17084. {
  17085. newValueInfo = invariantValueInfoToHoist->Copy(alloc);
  17086. newValueInfo->SetSymStore(symStore);
  17087. }
  17088. ChangeValueInfo(targetBlock, valueToUpdate, newValueInfo);
  17089. }
  17090. // static
  17091. bool
  17092. GlobOpt::DoInlineArgsOpt(Func* func)
  17093. {
  17094. Func* topFunc = func->GetTopFunc();
  17095. Assert(topFunc != func);
  17096. bool doInlineArgsOpt =
  17097. !PHASE_OFF(Js::InlineArgsOptPhase, topFunc) &&
  17098. !func->GetHasCalls() &&
  17099. !func->GetHasUnoptimizedArgumentsAcccess() &&
  17100. func->m_canDoInlineArgsOpt;
  17101. return doInlineArgsOpt;
  17102. }
  17103. bool
  17104. GlobOpt::IsSwitchOptEnabled(Func* func)
  17105. {
  17106. Assert(func->IsTopFunc());
  17107. return !PHASE_OFF(Js::SwitchOptPhase, func) && !func->GetProfileInfo()->IsSwitchOptDisabled() && !IsTypeSpecPhaseOff(func)
  17108. && func->DoGlobOpt() && !func->HasTry();
  17109. }
  17110. bool
  17111. GlobOpt::DoEquivObjTypeSpec(Func* func)
  17112. {
  17113. return !PHASE_OFF(Js::ObjTypeSpecPhase, func) && !PHASE_OFF(Js::EquivObjTypeSpecPhase, func) &&
  17114. func->GetProfileInfo()->IsEquivalentObjTypeSpecDisabled();
  17115. }
  17116. bool
  17117. GlobOpt::DoConstFold() const
  17118. {
  17119. return !PHASE_OFF(Js::ConstFoldPhase, func);
  17120. }
  17121. bool
  17122. GlobOpt::IsTypeSpecPhaseOff(Func *func)
  17123. {
  17124. return PHASE_OFF(Js::TypeSpecPhase, func) || func->IsJitInDebugMode() || !func->DoGlobOptsForGeneratorFunc();
  17125. }
  17126. bool
  17127. GlobOpt::DoTypeSpec() const
  17128. {
  17129. return doTypeSpec;
  17130. }
  17131. bool
  17132. GlobOpt::DoAggressiveIntTypeSpec(Func* func)
  17133. {
  17134. return
  17135. !PHASE_OFF(Js::AggressiveIntTypeSpecPhase, func) &&
  17136. !IsTypeSpecPhaseOff(func) &&
  17137. !func->GetProfileInfo()->IsAggressiveIntTypeSpecDisabled(func->IsLoopBody());
  17138. }
  17139. bool
  17140. GlobOpt::DoAggressiveIntTypeSpec() const
  17141. {
  17142. return doAggressiveIntTypeSpec;
  17143. }
  17144. bool
  17145. GlobOpt::DoAggressiveMulIntTypeSpec() const
  17146. {
  17147. return doAggressiveMulIntTypeSpec;
  17148. }
  17149. bool
  17150. GlobOpt::DoDivIntTypeSpec() const
  17151. {
  17152. return doDivIntTypeSpec;
  17153. }
  17154. // static
  17155. bool
  17156. GlobOpt::DoLossyIntTypeSpec(Func* func)
  17157. {
  17158. return
  17159. !PHASE_OFF(Js::LossyIntTypeSpecPhase, func) &&
  17160. !IsTypeSpecPhaseOff(func) &&
  17161. !func->GetProfileInfo()->IsLossyIntTypeSpecDisabled();
  17162. }
  17163. bool
  17164. GlobOpt::DoLossyIntTypeSpec() const
  17165. {
  17166. return doLossyIntTypeSpec;
  17167. }
  17168. // static
  17169. bool
  17170. GlobOpt::DoFloatTypeSpec(Func* func)
  17171. {
  17172. return
  17173. !PHASE_OFF(Js::FloatTypeSpecPhase, func) &&
  17174. !IsTypeSpecPhaseOff(func) &&
  17175. !func->GetProfileInfo()->IsFloatTypeSpecDisabled() &&
  17176. AutoSystemInfo::Data.SSE2Available();
  17177. }
  17178. bool
  17179. GlobOpt::DoFloatTypeSpec() const
  17180. {
  17181. return doFloatTypeSpec;
  17182. }
  17183. bool
  17184. GlobOpt::DoStringTypeSpec(Func* func)
  17185. {
  17186. return !PHASE_OFF(Js::StringTypeSpecPhase, func) && !IsTypeSpecPhaseOff(func);
  17187. }
  17188. // static
  17189. bool
  17190. GlobOpt::DoTypedArrayTypeSpec(Func* func)
  17191. {
  17192. return !PHASE_OFF(Js::TypedArrayTypeSpecPhase, func) &&
  17193. !IsTypeSpecPhaseOff(func) &&
  17194. !func->GetProfileInfo()->IsTypedArrayTypeSpecDisabled(func->IsLoopBody())
  17195. #if defined(_M_IX86)
  17196. && AutoSystemInfo::Data.SSE2Available()
  17197. #endif
  17198. ;
  17199. }
  17200. // static
  17201. bool
  17202. GlobOpt::DoNativeArrayTypeSpec(Func* func)
  17203. {
  17204. return !PHASE_OFF(Js::NativeArrayPhase, func) &&
  17205. !IsTypeSpecPhaseOff(func)
  17206. #if defined(_M_IX86)
  17207. && AutoSystemInfo::Data.SSE2Available()
  17208. #endif
  17209. ;
  17210. }
  17211. bool
  17212. GlobOpt::DoArrayCheckHoist(Func *const func)
  17213. {
  17214. Assert(func->IsTopFunc());
  17215. return
  17216. !PHASE_OFF(Js::ArrayCheckHoistPhase, func) &&
  17217. !func->GetProfileInfo()->IsArrayCheckHoistDisabled(func->IsLoopBody()) &&
  17218. !func->IsJitInDebugMode() && // StElemI fast path is not allowed when in debug mode, so it cannot have bailout
  17219. func->DoGlobOptsForGeneratorFunc();
  17220. }
  17221. bool
  17222. GlobOpt::DoArrayCheckHoist() const
  17223. {
  17224. return doArrayCheckHoist;
  17225. }
  17226. bool
  17227. GlobOpt::DoArrayCheckHoist(const ValueType baseValueType, Loop* loop, IR::Instr *const instr) const
  17228. {
  17229. if(!DoArrayCheckHoist() || instr && !IsLoopPrePass() && instr->DoStackArgsOpt(func))
  17230. {
  17231. return false;
  17232. }
  17233. if(!baseValueType.IsLikelyArrayOrObjectWithArray() ||
  17234. (loop ? ImplicitCallFlagsAllowOpts(loop) : ImplicitCallFlagsAllowOpts(func)))
  17235. {
  17236. return true;
  17237. }
  17238. // The function or loop does not allow disabling implicit calls, which is required to eliminate redundant JS array checks
  17239. #if DBG_DUMP
  17240. if((((loop ? loop->GetImplicitCallFlags() : func->m_fg->implicitCallFlags) & ~Js::ImplicitCall_External) == 0) &&
  17241. Js::Configuration::Global.flags.Trace.IsEnabled(Js::HostOptPhase))
  17242. {
  17243. Output::Print(_u("DoArrayCheckHoist disabled for JS arrays because of external: "));
  17244. func->GetJnFunction()->DumpFullFunctionName();
  17245. Output::Print(_u("\n"));
  17246. Output::Flush();
  17247. }
  17248. #endif
  17249. return false;
  17250. }
  17251. bool
  17252. GlobOpt::DoArrayMissingValueCheckHoist(Func *const func)
  17253. {
  17254. return
  17255. DoArrayCheckHoist(func) &&
  17256. !PHASE_OFF(Js::ArrayMissingValueCheckHoistPhase, func) &&
  17257. !func->GetProfileInfo()->IsArrayMissingValueCheckHoistDisabled(func->IsLoopBody());
  17258. }
  17259. bool
  17260. GlobOpt::DoArrayMissingValueCheckHoist() const
  17261. {
  17262. return doArrayMissingValueCheckHoist;
  17263. }
  17264. bool
  17265. GlobOpt::DoArraySegmentHoist(const ValueType baseValueType, Func *const func)
  17266. {
  17267. Assert(baseValueType.IsLikelyAnyOptimizedArray());
  17268. if(!DoArrayCheckHoist(func) || PHASE_OFF(Js::ArraySegmentHoistPhase, func))
  17269. {
  17270. return false;
  17271. }
  17272. if(!baseValueType.IsLikelyArrayOrObjectWithArray())
  17273. {
  17274. return true;
  17275. }
  17276. return
  17277. !PHASE_OFF(Js::JsArraySegmentHoistPhase, func) &&
  17278. !func->GetProfileInfo()->IsJsArraySegmentHoistDisabled(func->IsLoopBody());
  17279. }
  17280. bool
  17281. GlobOpt::DoArraySegmentHoist(const ValueType baseValueType) const
  17282. {
  17283. Assert(baseValueType.IsLikelyAnyOptimizedArray());
  17284. return baseValueType.IsLikelyArrayOrObjectWithArray() ? doJsArraySegmentHoist : doArraySegmentHoist;
  17285. }
  17286. bool
  17287. GlobOpt::DoTypedArraySegmentLengthHoist(Loop *const loop) const
  17288. {
  17289. if(!DoArraySegmentHoist(ValueType::GetObject(ObjectType::Int32Array)))
  17290. {
  17291. return false;
  17292. }
  17293. if(loop ? ImplicitCallFlagsAllowOpts(loop) : ImplicitCallFlagsAllowOpts(func))
  17294. {
  17295. return true;
  17296. }
  17297. // The function or loop does not allow disabling implicit calls, which is required to eliminate redundant typed array
  17298. // segment length loads.
  17299. #if DBG_DUMP
  17300. if((((loop ? loop->GetImplicitCallFlags() : func->m_fg->implicitCallFlags) & ~Js::ImplicitCall_External) == 0) &&
  17301. Js::Configuration::Global.flags.Trace.IsEnabled(Js::HostOptPhase))
  17302. {
  17303. Output::Print(_u("DoArraySegmentLengthHoist disabled for typed arrays because of external: "));
  17304. func->GetJnFunction()->DumpFullFunctionName();
  17305. Output::Print(_u("\n"));
  17306. Output::Flush();
  17307. }
  17308. #endif
  17309. return false;
  17310. }
  17311. bool
  17312. GlobOpt::DoArrayLengthHoist(Func *const func)
  17313. {
  17314. return
  17315. DoArrayCheckHoist(func) &&
  17316. !PHASE_OFF(Js::Phase::ArrayLengthHoistPhase, func) &&
  17317. !func->GetProfileInfo()->IsArrayLengthHoistDisabled(func->IsLoopBody());
  17318. }
  17319. bool
  17320. GlobOpt::DoArrayLengthHoist() const
  17321. {
  17322. return doArrayLengthHoist;
  17323. }
  17324. bool
  17325. GlobOpt::DoEliminateArrayAccessHelperCall() const
  17326. {
  17327. return doEliminateArrayAccessHelperCall;
  17328. }
  17329. bool
  17330. GlobOpt::DoLdLenIntSpec(IR::Instr *const instr, const ValueType baseValueType) const
  17331. {
  17332. Assert(!instr || instr->m_opcode == Js::OpCode::LdLen_A);
  17333. Assert(!instr || instr->GetDst());
  17334. Assert(!instr || instr->GetSrc1());
  17335. if(PHASE_OFF(Js::LdLenIntSpecPhase, func) ||
  17336. IsTypeSpecPhaseOff(func) ||
  17337. func->GetProfileInfo()->IsLdLenIntSpecDisabled() ||
  17338. instr && !IsLoopPrePass() && instr->DoStackArgsOpt(func))
  17339. {
  17340. return false;
  17341. }
  17342. if(instr &&
  17343. instr->IsProfiledInstr() &&
  17344. (
  17345. !instr->AsProfiledInstr()->u.ldElemInfo->GetElementType().IsLikelyInt() ||
  17346. instr->GetDst()->AsRegOpnd()->m_sym->m_isNotInt
  17347. ))
  17348. {
  17349. return false;
  17350. }
  17351. Assert(!instr || baseValueType == instr->GetSrc1()->GetValueType());
  17352. return
  17353. baseValueType.HasBeenString() ||
  17354. baseValueType.IsLikelyAnyOptimizedArray() && baseValueType.GetObjectType() != ObjectType::ObjectWithArray;
  17355. }
  17356. bool
  17357. GlobOpt::DoPathDependentValues() const
  17358. {
  17359. return !PHASE_OFF(Js::Phase::PathDependentValuesPhase, func);
  17360. }
  17361. bool
  17362. GlobOpt::DoTrackRelativeIntBounds() const
  17363. {
  17364. return doTrackRelativeIntBounds;
  17365. }
  17366. bool
  17367. GlobOpt::DoBoundCheckElimination() const
  17368. {
  17369. return doBoundCheckElimination;
  17370. }
  17371. bool
  17372. GlobOpt::DoBoundCheckHoist() const
  17373. {
  17374. return doBoundCheckHoist;
  17375. }
  17376. bool
  17377. GlobOpt::DoLoopCountBasedBoundCheckHoist() const
  17378. {
  17379. return doLoopCountBasedBoundCheckHoist;
  17380. }
  17381. bool
  17382. GlobOpt::TrackArgumentsObject()
  17383. {
  17384. if (PHASE_OFF(Js::StackArgOptPhase, this->func))
  17385. {
  17386. this->CannotAllocateArgumentsObjectOnStack();
  17387. return false;
  17388. }
  17389. return func->GetHasStackArgs();
  17390. }
  17391. void
  17392. GlobOpt::CannotAllocateArgumentsObjectOnStack()
  17393. {
  17394. func->SetHasStackArgs(false);
  17395. #ifdef ENABLE_DEBUG_CONFIG_OPTIONS
  17396. if (PHASE_TESTTRACE(Js::StackArgOptPhase, this->func))
  17397. {
  17398. char16 debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  17399. Output::Print(_u("Stack args disabled for function %s(%s)\n"), func->GetJnFunction()->GetDisplayName(), func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer));
  17400. Output::Flush();
  17401. }
  17402. #endif
  17403. }
  17404. IR::Instr *
  17405. GlobOpt::PreOptPeep(IR::Instr *instr)
  17406. {
  17407. if (OpCodeAttr::HasDeadFallThrough(instr->m_opcode))
  17408. {
  17409. switch (instr->m_opcode)
  17410. {
  17411. case Js::OpCode::BailOnNoProfile:
  17412. {
  17413. // Handle BailOnNoProfile
  17414. if (instr->HasBailOutInfo())
  17415. {
  17416. if (!this->prePassLoop)
  17417. {
  17418. FillBailOutInfo(this->currentBlock, instr->GetBailOutInfo());
  17419. }
  17420. // Already processed.
  17421. return instr;
  17422. }
  17423. // Convert to bailout instr
  17424. IR::Instr *nextBytecodeOffsetInstr = instr->GetNextRealInstrOrLabel();
  17425. while(nextBytecodeOffsetInstr->GetByteCodeOffset() == Js::Constants::NoByteCodeOffset)
  17426. {
  17427. nextBytecodeOffsetInstr = nextBytecodeOffsetInstr->GetNextRealInstrOrLabel();
  17428. Assert(!nextBytecodeOffsetInstr->IsLabelInstr());
  17429. }
  17430. instr = instr->ConvertToBailOutInstr(nextBytecodeOffsetInstr, IR::BailOutOnNoProfile);
  17431. instr->ClearByteCodeOffset();
  17432. instr->SetByteCodeOffset(nextBytecodeOffsetInstr);
  17433. if (!this->currentBlock->loop)
  17434. {
  17435. FillBailOutInfo(this->currentBlock, instr->GetBailOutInfo());
  17436. }
  17437. else
  17438. {
  17439. Assert(this->prePassLoop);
  17440. }
  17441. break;
  17442. }
  17443. case Js::OpCode::BailOnException:
  17444. {
  17445. Assert(this->func->HasTry() && this->func->DoOptimizeTryCatch() &&
  17446. instr->m_prev->m_opcode == Js::OpCode::Catch &&
  17447. instr->m_prev->m_prev->IsLabelInstr() &&
  17448. instr->m_prev->m_prev->AsLabelInstr()->GetRegion()->GetType() == RegionType::RegionTypeCatch); // Should also handle RegionTypeFinally
  17449. break;
  17450. }
  17451. default:
  17452. {
  17453. if(this->currentBlock->loop && !this->IsLoopPrePass())
  17454. {
  17455. return instr;
  17456. }
  17457. break;
  17458. }
  17459. }
  17460. RemoveCodeAfterNoFallthroughInstr(instr);
  17461. }
  17462. return instr;
  17463. }
  17464. void
  17465. GlobOpt::RemoveCodeAfterNoFallthroughInstr(IR::Instr *instr)
  17466. {
  17467. if (instr != this->currentBlock->GetLastInstr())
  17468. {
  17469. // Remove dead code after bailout
  17470. IR::Instr *instrDead = instr->m_next;
  17471. IR::Instr *instrNext;
  17472. for (; instrDead != this->currentBlock->GetLastInstr(); instrDead = instrNext)
  17473. {
  17474. instrNext = instrDead->m_next;
  17475. if (instrNext->m_opcode == Js::OpCode::FunctionExit)
  17476. {
  17477. break;
  17478. }
  17479. this->func->m_fg->RemoveInstr(instrDead, this);
  17480. }
  17481. IR::Instr *instrNextBlock = instrDead->m_next;
  17482. this->func->m_fg->RemoveInstr(instrDead, this);
  17483. this->currentBlock->SetLastInstr(instrNextBlock->m_prev);
  17484. }
  17485. // Cleanup dead successors
  17486. FOREACH_SUCCESSOR_BLOCK_EDITING(deadBlock, this->currentBlock, iter)
  17487. {
  17488. this->currentBlock->RemoveDeadSucc(deadBlock, this->func->m_fg);
  17489. if (this->currentBlock->GetDataUseCount() > 0)
  17490. {
  17491. this->currentBlock->DecrementDataUseCount();
  17492. }
  17493. } NEXT_SUCCESSOR_BLOCK_EDITING;
  17494. }
  17495. void
  17496. GlobOpt::ProcessTryCatch(IR::Instr* instr)
  17497. {
  17498. Assert(instr->m_next->IsLabelInstr() && instr->m_next->AsLabelInstr()->GetRegion()->GetType() == RegionType::RegionTypeTry);
  17499. Region* tryRegion = instr->m_next->AsLabelInstr()->GetRegion();
  17500. BVSparse<JitArenaAllocator> * writeThroughSymbolsSet = tryRegion->writeThroughSymbolsSet;
  17501. ToVar(writeThroughSymbolsSet, this->currentBlock);
  17502. }
  17503. void
  17504. GlobOpt::InsertToVarAtDefInTryRegion(IR::Instr * instr, IR::Opnd * dstOpnd)
  17505. {
  17506. if (this->currentRegion->GetType() == RegionTypeTry && dstOpnd->IsRegOpnd() && dstOpnd->AsRegOpnd()->m_sym->HasByteCodeRegSlot())
  17507. {
  17508. StackSym * sym = dstOpnd->AsRegOpnd()->m_sym;
  17509. if (sym->IsVar())
  17510. {
  17511. return;
  17512. }
  17513. StackSym * varSym = sym->GetVarEquivSym(nullptr);
  17514. if (this->currentRegion->writeThroughSymbolsSet->Test(varSym->m_id))
  17515. {
  17516. IR::RegOpnd * regOpnd = IR::RegOpnd::New(varSym, IRType::TyVar, instr->m_func);
  17517. this->ToVar(instr->m_next, regOpnd, this->currentBlock, NULL, false);
  17518. }
  17519. }
  17520. }
  17521. void
  17522. GlobOpt::RemoveFlowEdgeToCatchBlock(IR::Instr * instr)
  17523. {
  17524. Assert(instr->IsBranchInstr());
  17525. BasicBlock * catchBlock = nullptr;
  17526. BasicBlock * predBlock = nullptr;
  17527. if (instr->m_opcode == Js::OpCode::BrOnException)
  17528. {
  17529. catchBlock = instr->AsBranchInstr()->GetTarget()->GetBasicBlock();
  17530. predBlock = this->currentBlock;
  17531. }
  17532. else if (instr->m_opcode == Js::OpCode::BrOnNoException)
  17533. {
  17534. IR::Instr * nextInstr = instr->GetNextRealInstrOrLabel();
  17535. Assert(nextInstr->IsLabelInstr());
  17536. IR::LabelInstr * nextLabel = nextInstr->AsLabelInstr();
  17537. if (nextLabel->GetRegion() && nextLabel->GetRegion()->GetType() == RegionTypeCatch)
  17538. {
  17539. catchBlock = nextLabel->GetBasicBlock();
  17540. predBlock = this->currentBlock;
  17541. }
  17542. else
  17543. {
  17544. Assert(nextLabel->m_next->IsBranchInstr() && nextLabel->m_next->AsBranchInstr()->IsUnconditional());
  17545. BasicBlock * nextBlock = nextLabel->GetBasicBlock();
  17546. IR::BranchInstr * branchToCatchBlock = nextLabel->m_next->AsBranchInstr();
  17547. IR::LabelInstr * catchBlockLabel = branchToCatchBlock->GetTarget();
  17548. Assert(catchBlockLabel->GetRegion()->GetType() == RegionTypeCatch);
  17549. catchBlock = catchBlockLabel->GetBasicBlock();
  17550. predBlock = nextBlock;
  17551. }
  17552. }
  17553. Assert(catchBlock);
  17554. Assert(predBlock);
  17555. if (this->func->m_fg->FindEdge(predBlock, catchBlock))
  17556. {
  17557. predBlock->RemoveDeadSucc(catchBlock, this->func->m_fg);
  17558. if (predBlock == this->currentBlock)
  17559. {
  17560. predBlock->DecrementDataUseCount();
  17561. }
  17562. }
  17563. }
  17564. IR::Instr *
  17565. GlobOpt::OptPeep(IR::Instr *instr, Value *src1Val, Value *src2Val)
  17566. {
  17567. IR::Opnd *dst, *src1, *src2;
  17568. if (this->IsLoopPrePass())
  17569. {
  17570. return instr;
  17571. }
  17572. switch (instr->m_opcode)
  17573. {
  17574. case Js::OpCode::DeadBrEqual:
  17575. case Js::OpCode::DeadBrRelational:
  17576. case Js::OpCode::DeadBrSrEqual:
  17577. src1 = instr->GetSrc1();
  17578. src2 = instr->GetSrc2();
  17579. // These branches were turned into dead branches because they were unnecessary (branch to next, ...).
  17580. // The DeadBr are necessary in case the evaluation of the sources have side-effects.
  17581. // If we know for sure the srcs are primitive or have been type specialized, we don't need these instructions
  17582. if (((src1Val && src1Val->GetValueInfo()->IsPrimitive()) || (src1->IsRegOpnd() && this->IsTypeSpecialized(src1->AsRegOpnd()->m_sym, this->currentBlock))) &&
  17583. ((src2Val && src2Val->GetValueInfo()->IsPrimitive()) || (src2->IsRegOpnd() && this->IsTypeSpecialized(src2->AsRegOpnd()->m_sym, this->currentBlock))))
  17584. {
  17585. this->CaptureByteCodeSymUses(instr);
  17586. instr->m_opcode = Js::OpCode::Nop;
  17587. }
  17588. break;
  17589. case Js::OpCode::DeadBrOnHasProperty:
  17590. src1 = instr->GetSrc1();
  17591. if (((src1Val && src1Val->GetValueInfo()->IsPrimitive()) || (src1->IsRegOpnd() && this->IsTypeSpecialized(src1->AsRegOpnd()->m_sym, this->currentBlock))))
  17592. {
  17593. this->CaptureByteCodeSymUses(instr);
  17594. instr->m_opcode = Js::OpCode::Nop;
  17595. }
  17596. break;
  17597. case Js::OpCode::Ld_A:
  17598. case Js::OpCode::Ld_I4:
  17599. src1 = instr->GetSrc1();
  17600. dst = instr->GetDst();
  17601. if (dst->IsRegOpnd() && dst->IsEqual(src1))
  17602. {
  17603. dst = instr->UnlinkDst();
  17604. if (!dst->GetIsJITOptimizedReg())
  17605. {
  17606. IR::ByteCodeUsesInstr *bytecodeUse = IR::ByteCodeUsesInstr::New(this->func);
  17607. bytecodeUse->SetDst(dst);
  17608. instr->InsertAfter(bytecodeUse);
  17609. }
  17610. instr->FreeSrc1();
  17611. instr->m_opcode = Js::OpCode::Nop;
  17612. }
  17613. break;
  17614. }
  17615. return instr;
  17616. }
  17617. void
  17618. GlobOpt::OptimizeIndirUses(IR::IndirOpnd *indirOpnd, IR::Instr * *pInstr, Value **indirIndexValRef)
  17619. {
  17620. IR::Instr * &instr = *pInstr;
  17621. Assert(!indirIndexValRef || !*indirIndexValRef);
  17622. // Update value types and copy-prop the base
  17623. OptSrc(indirOpnd->GetBaseOpnd(), &instr, nullptr, indirOpnd);
  17624. IR::RegOpnd *indexOpnd = indirOpnd->GetIndexOpnd();
  17625. if (!indexOpnd)
  17626. {
  17627. return;
  17628. }
  17629. // Update value types and copy-prop the index
  17630. Value *indexVal = OptSrc(indexOpnd, &instr, nullptr, indirOpnd);
  17631. if(indirIndexValRef)
  17632. {
  17633. *indirIndexValRef = indexVal;
  17634. }
  17635. }
  17636. bool
  17637. ValueInfo::IsGeneric() const
  17638. {
  17639. return structureKind == ValueStructureKind::Generic;
  17640. }
  17641. bool
  17642. ValueInfo::IsIntConstant() const
  17643. {
  17644. return IsInt() && structureKind == ValueStructureKind::IntConstant;
  17645. }
  17646. const IntConstantValueInfo *
  17647. ValueInfo::AsIntConstant() const
  17648. {
  17649. Assert(IsIntConstant());
  17650. return static_cast<const IntConstantValueInfo *>(this);
  17651. }
  17652. bool
  17653. ValueInfo::IsIntRange() const
  17654. {
  17655. return IsInt() && structureKind == ValueStructureKind::IntRange;
  17656. }
  17657. const IntRangeValueInfo *
  17658. ValueInfo::AsIntRange() const
  17659. {
  17660. Assert(IsIntRange());
  17661. return static_cast<const IntRangeValueInfo *>(this);
  17662. }
  17663. bool
  17664. ValueInfo::IsIntBounded() const
  17665. {
  17666. const bool isIntBounded = IsLikelyInt() && structureKind == ValueStructureKind::IntBounded;
  17667. // Bounds for definitely int values should have relative bounds, otherwise those values should use one of the other value
  17668. // infos
  17669. Assert(!isIntBounded || static_cast<const IntBoundedValueInfo *>(this)->Bounds()->RequiresIntBoundedValueInfo(Type()));
  17670. return isIntBounded;
  17671. }
  17672. const IntBoundedValueInfo *
  17673. ValueInfo::AsIntBounded() const
  17674. {
  17675. Assert(IsIntBounded());
  17676. return static_cast<const IntBoundedValueInfo *>(this);
  17677. }
  17678. bool
  17679. ValueInfo::IsFloatConstant() const
  17680. {
  17681. return IsFloat() && structureKind == ValueStructureKind::FloatConstant;
  17682. }
  17683. FloatConstantValueInfo *
  17684. ValueInfo::AsFloatConstant()
  17685. {
  17686. Assert(IsFloatConstant());
  17687. return static_cast<FloatConstantValueInfo *>(this);
  17688. }
  17689. const FloatConstantValueInfo *
  17690. ValueInfo::AsFloatConstant() const
  17691. {
  17692. Assert(IsFloatConstant());
  17693. return static_cast<const FloatConstantValueInfo *>(this);
  17694. }
  17695. bool
  17696. ValueInfo::IsVarConstant() const
  17697. {
  17698. return structureKind == ValueStructureKind::VarConstant;
  17699. }
  17700. VarConstantValueInfo *
  17701. ValueInfo::AsVarConstant()
  17702. {
  17703. Assert(IsVarConstant());
  17704. return static_cast<VarConstantValueInfo *>(this);
  17705. }
  17706. bool
  17707. ValueInfo::IsJsType() const
  17708. {
  17709. Assert(!(structureKind == ValueStructureKind::JsType && !IsUninitialized()));
  17710. return structureKind == ValueStructureKind::JsType;
  17711. }
  17712. JsTypeValueInfo *
  17713. ValueInfo::AsJsType()
  17714. {
  17715. Assert(IsJsType());
  17716. return static_cast<JsTypeValueInfo *>(this);
  17717. }
  17718. const JsTypeValueInfo *
  17719. ValueInfo::AsJsType() const
  17720. {
  17721. Assert(IsJsType());
  17722. return static_cast<const JsTypeValueInfo *>(this);
  17723. }
  17724. bool
  17725. ValueInfo::IsArrayValueInfo() const
  17726. {
  17727. return IsAnyOptimizedArray() && structureKind == ValueStructureKind::Array;
  17728. }
  17729. const
  17730. ArrayValueInfo *ValueInfo::AsArrayValueInfo() const
  17731. {
  17732. Assert(IsArrayValueInfo());
  17733. return static_cast<const ArrayValueInfo *>(this);
  17734. }
  17735. ArrayValueInfo *
  17736. ValueInfo::AsArrayValueInfo()
  17737. {
  17738. Assert(IsArrayValueInfo());
  17739. return static_cast<ArrayValueInfo *>(this);
  17740. }
  17741. ValueInfo *
  17742. ValueInfo::SpecializeToInt32(JitArenaAllocator *const allocator, const bool isForLoopBackEdgeCompensation)
  17743. {
  17744. // Int specialization in some uncommon loop cases involving dependencies, needs to allow specializing values of arbitrary
  17745. // types, even values that are definitely not int, to compensate for aggressive assumptions made by a loop prepass. In all
  17746. // other cases, only values that are likely int may be int-specialized.
  17747. Assert(IsUninitialized() || IsLikelyInt() || isForLoopBackEdgeCompensation);
  17748. if(IsInt())
  17749. {
  17750. return this;
  17751. }
  17752. if(!IsIntBounded())
  17753. {
  17754. ValueInfo *const newValueInfo = CopyWithGenericStructureKind(allocator);
  17755. newValueInfo->Type() = ValueType::GetInt(true);
  17756. return newValueInfo;
  17757. }
  17758. const IntBoundedValueInfo *const boundedValueInfo = AsIntBounded();
  17759. const IntBounds *const bounds = boundedValueInfo->Bounds();
  17760. const IntConstantBounds constantBounds = bounds->ConstantBounds();
  17761. if(bounds->RequiresIntBoundedValueInfo())
  17762. {
  17763. IntBoundedValueInfo *const newValueInfo = boundedValueInfo->Copy(allocator);
  17764. newValueInfo->Type() = constantBounds.GetValueType();
  17765. return newValueInfo;
  17766. }
  17767. ValueInfo *const newValueInfo =
  17768. constantBounds.IsConstant()
  17769. ? static_cast<ValueInfo *>(IntConstantValueInfo::New(allocator, constantBounds.LowerBound()))
  17770. : IntRangeValueInfo::New(allocator, constantBounds.LowerBound(), constantBounds.UpperBound(), false);
  17771. newValueInfo->SetSymStore(GetSymStore());
  17772. return newValueInfo;
  17773. }
  17774. ValueInfo *
  17775. ValueInfo::SpecializeToFloat64(JitArenaAllocator *const allocator)
  17776. {
  17777. if(IsNumber())
  17778. {
  17779. return this;
  17780. }
  17781. ValueInfo *const newValueInfo = CopyWithGenericStructureKind(allocator);
  17782. // If the value type was likely int, after float-specializing, it's preferable to use Int_Number rather than Float, as the
  17783. // former is also likely int and allows int specialization later.
  17784. newValueInfo->Type() = IsLikelyInt() ? Type().ToDefiniteAnyNumber() : Type().ToDefiniteAnyFloat();
  17785. return newValueInfo;
  17786. }
  17787. // SIMD_JS
  17788. ValueInfo *
  17789. ValueInfo::SpecializeToSimd128(IRType type, JitArenaAllocator *const allocator)
  17790. {
  17791. switch (type)
  17792. {
  17793. case TySimd128F4:
  17794. return SpecializeToSimd128F4(allocator);
  17795. case TySimd128I4:
  17796. return SpecializeToSimd128I4(allocator);
  17797. default:
  17798. Assert(UNREACHED);
  17799. return false;
  17800. }
  17801. }
  17802. ValueInfo *
  17803. ValueInfo::SpecializeToSimd128F4(JitArenaAllocator *const allocator)
  17804. {
  17805. if (IsSimd128Float32x4())
  17806. {
  17807. return this;
  17808. }
  17809. ValueInfo *const newValueInfo = CopyWithGenericStructureKind(allocator);
  17810. newValueInfo->Type() = ValueType::GetSimd128(ObjectType::Simd128Float32x4);
  17811. return newValueInfo;
  17812. }
  17813. ValueInfo *
  17814. ValueInfo::SpecializeToSimd128I4(JitArenaAllocator *const allocator)
  17815. {
  17816. if (IsSimd128Int32x4())
  17817. {
  17818. return this;
  17819. }
  17820. ValueInfo *const newValueInfo = CopyWithGenericStructureKind(allocator);
  17821. newValueInfo->Type() = ValueType::GetSimd128(ObjectType::Simd128Int32x4);
  17822. return newValueInfo;
  17823. }
  17824. bool
  17825. ValueInfo::GetIsShared() const
  17826. {
  17827. return IsJsType() ? AsJsType()->GetIsShared() : false;
  17828. }
  17829. void
  17830. ValueInfo::SetIsShared()
  17831. {
  17832. if (IsJsType()) AsJsType()->SetIsShared();
  17833. }
  17834. ValueInfo *
  17835. ValueInfo::Copy(JitArenaAllocator * allocator)
  17836. {
  17837. if(IsIntConstant())
  17838. {
  17839. return AsIntConstant()->Copy(allocator);
  17840. }
  17841. if(IsIntRange())
  17842. {
  17843. return AsIntRange()->Copy(allocator);
  17844. }
  17845. if(IsIntBounded())
  17846. {
  17847. return AsIntBounded()->Copy(allocator);
  17848. }
  17849. if(IsFloatConstant())
  17850. {
  17851. return AsFloatConstant()->Copy(allocator);
  17852. }
  17853. if(IsJsType())
  17854. {
  17855. return AsJsType()->Copy(allocator);
  17856. }
  17857. if(IsArrayValueInfo())
  17858. {
  17859. return AsArrayValueInfo()->Copy(allocator);
  17860. }
  17861. return CopyWithGenericStructureKind(allocator);
  17862. }
  17863. bool
  17864. ValueInfo::GetIntValMinMax(int *pMin, int *pMax, bool doAggressiveIntTypeSpec)
  17865. {
  17866. IntConstantBounds intConstantBounds;
  17867. if (TryGetIntConstantBounds(&intConstantBounds, doAggressiveIntTypeSpec))
  17868. {
  17869. *pMin = intConstantBounds.LowerBound();
  17870. *pMax = intConstantBounds.UpperBound();
  17871. return true;
  17872. }
  17873. Assert(!IsInt());
  17874. Assert(!doAggressiveIntTypeSpec || !IsLikelyInt());
  17875. return false;
  17876. }
  17877. bool
  17878. GlobOpt::IsDefinedInCurrentLoopIteration(Loop *loop, Value *val) const
  17879. {
  17880. return false;
  17881. }
  17882. bool
  17883. GlobOpt::IsPREInstrCandidateLoad(Js::OpCode opcode)
  17884. {
  17885. switch (opcode)
  17886. {
  17887. case Js::OpCode::LdFld:
  17888. case Js::OpCode::LdFldForTypeOf:
  17889. case Js::OpCode::LdRootFld:
  17890. case Js::OpCode::LdRootFldForTypeOf:
  17891. case Js::OpCode::LdMethodFld:
  17892. case Js::OpCode::LdRootMethodFld:
  17893. case Js::OpCode::LdSlot:
  17894. case Js::OpCode::LdSlotArr:
  17895. return true;
  17896. }
  17897. return false;
  17898. }
  17899. bool
  17900. GlobOpt::IsPREInstrCandidateStore(Js::OpCode opcode)
  17901. {
  17902. switch (opcode)
  17903. {
  17904. case Js::OpCode::StFld:
  17905. case Js::OpCode::StRootFld:
  17906. case Js::OpCode::StSlot:
  17907. return true;
  17908. }
  17909. return false;
  17910. }
  17911. bool
  17912. GlobOpt::ImplicitCallFlagsAllowOpts(Loop *loop)
  17913. {
  17914. return loop->GetImplicitCallFlags() != Js::ImplicitCall_HasNoInfo &&
  17915. (((loop->GetImplicitCallFlags() & ~Js::ImplicitCall_Accessor) | Js::ImplicitCall_None) == Js::ImplicitCall_None);
  17916. }
  17917. bool
  17918. GlobOpt::ImplicitCallFlagsAllowOpts(Func *func)
  17919. {
  17920. return func->m_fg->implicitCallFlags != Js::ImplicitCall_HasNoInfo &&
  17921. (((func->m_fg->implicitCallFlags & ~Js::ImplicitCall_Accessor) | Js::ImplicitCall_None) == Js::ImplicitCall_None);
  17922. }
  17923. #if DBG_DUMP
  17924. void ValueInfo::Dump()
  17925. {
  17926. if(!IsJsType()) // The value type is uninitialized for a type value
  17927. {
  17928. char typeStr[VALUE_TYPE_MAX_STRING_SIZE];
  17929. Type().ToString(typeStr);
  17930. Output::Print(_u("%S"), typeStr);
  17931. }
  17932. IntConstantBounds intConstantBounds;
  17933. if(TryGetIntConstantBounds(&intConstantBounds))
  17934. {
  17935. if(intConstantBounds.IsConstant())
  17936. {
  17937. Output::Print(_u(" constant:%d"), intConstantBounds.LowerBound());
  17938. return;
  17939. }
  17940. Output::Print(_u(" range:%d - %d"), intConstantBounds.LowerBound(), intConstantBounds.UpperBound());
  17941. }
  17942. else if(IsFloatConstant())
  17943. {
  17944. Output::Print(_u(" constant:%g"), AsFloatConstant()->FloatValue());
  17945. }
  17946. else if(IsJsType())
  17947. {
  17948. const Js::Type* type = AsJsType()->GetJsType();
  17949. type != nullptr ? Output::Print(_u("type: 0x%p, "), type) : Output::Print(_u("type: null, "));
  17950. Output::Print(_u("type Set: "));
  17951. Js::EquivalentTypeSet* typeSet = AsJsType()->GetJsTypeSet();
  17952. if (typeSet != nullptr)
  17953. {
  17954. uint16 typeCount = typeSet->GetCount();
  17955. for (uint16 ti = 0; ti < typeCount - 1; ti++)
  17956. {
  17957. Output::Print(_u("0x%p, "), typeSet->GetType(ti));
  17958. }
  17959. Output::Print(_u("0x%p"), typeSet->GetType(typeCount - 1));
  17960. }
  17961. else
  17962. {
  17963. Output::Print(_u("null"));
  17964. }
  17965. }
  17966. else if(IsArrayValueInfo())
  17967. {
  17968. const ArrayValueInfo *const arrayValueInfo = AsArrayValueInfo();
  17969. if(arrayValueInfo->HeadSegmentSym())
  17970. {
  17971. Output::Print(_u(" seg: "));
  17972. arrayValueInfo->HeadSegmentSym()->Dump();
  17973. }
  17974. if(arrayValueInfo->HeadSegmentLengthSym())
  17975. {
  17976. Output::Print(_u(" segLen: "));
  17977. arrayValueInfo->HeadSegmentLengthSym()->Dump();
  17978. }
  17979. if(arrayValueInfo->LengthSym())
  17980. {
  17981. Output::Print(_u(" len: "));
  17982. arrayValueInfo->LengthSym()->Dump();
  17983. }
  17984. }
  17985. if (this->GetSymStore())
  17986. {
  17987. Output::Print(_u("\t\tsym:"));
  17988. this->GetSymStore()->Dump();
  17989. }
  17990. }
  17991. void
  17992. GlobOpt::Dump()
  17993. {
  17994. this->DumpSymToValueMap();
  17995. }
  17996. void
  17997. GlobOpt::DumpSymToValueMap(GlobHashTable* symToValueMap)
  17998. {
  17999. if (symToValueMap != nullptr)
  18000. {
  18001. symToValueMap->Dump(GlobOpt::DumpSym);
  18002. }
  18003. }
  18004. void
  18005. GlobOpt::DumpSymToValueMap(BasicBlock *block)
  18006. {
  18007. Output::Print(_u("\n*** SymToValueMap ***\n"));
  18008. DumpSymToValueMap(block->globOptData.symToValueMap);
  18009. }
  18010. void
  18011. GlobOpt::DumpSymToValueMap()
  18012. {
  18013. DumpSymToValueMap(this->currentBlock);
  18014. }
  18015. void
  18016. GlobOpt::DumpSym(Sym *sym)
  18017. {
  18018. sym->Dump();
  18019. }
  18020. void
  18021. GlobOpt::DumpSymVal(int index)
  18022. {
  18023. SymID id = index;
  18024. extern Func *CurrentFunc;
  18025. Sym *sym = this->func->m_symTable->Find(id);
  18026. AssertMsg(sym, "Sym not found!!!");
  18027. Output::Print(_u("Sym: "));
  18028. sym->Dump();
  18029. Output::Print(_u("\t\tValueNumber: "));
  18030. Value ** pValue = this->blockData.symToValueMap->Get(sym->m_id);
  18031. (*pValue)->Dump();
  18032. Output::Print(_u("\n"));
  18033. }
  18034. void
  18035. GlobOpt::Trace(BasicBlock * block, bool before)
  18036. {
  18037. bool globOptTrace = Js::Configuration::Global.flags.Trace.IsEnabled(Js::GlobOptPhase, this->func->GetSourceContextId(), this->func->GetLocalFunctionId());
  18038. bool typeSpecTrace = Js::Configuration::Global.flags.Trace.IsEnabled(Js::TypeSpecPhase, this->func->GetSourceContextId(), this->func->GetLocalFunctionId());
  18039. bool floatTypeSpecTrace = Js::Configuration::Global.flags.Trace.IsEnabled(Js::FloatTypeSpecPhase, this->func->GetSourceContextId(), this->func->GetLocalFunctionId());
  18040. bool fieldHoistTrace = Js::Configuration::Global.flags.Trace.IsEnabled(Js::FieldHoistPhase, this->func->GetSourceContextId(), this->func->GetLocalFunctionId());
  18041. bool fieldCopyPropTrace = fieldHoistTrace || Js::Configuration::Global.flags.Trace.IsEnabled(Js::FieldCopyPropPhase, this->func->GetSourceContextId(), this->func->GetLocalFunctionId());
  18042. bool objTypeSpecTrace = Js::Configuration::Global.flags.Trace.IsEnabled(Js::ObjTypeSpecPhase, this->func->GetSourceContextId(), this->func->GetLocalFunctionId());
  18043. bool valueTableTrace = Js::Configuration::Global.flags.Trace.IsEnabled(Js::ValueTablePhase, this->func->GetSourceContextId(), this->func->GetLocalFunctionId());
  18044. bool fieldPRETrace = Js::Configuration::Global.flags.Trace.IsEnabled(Js::FieldPREPhase, this->func->GetSourceContextId(), this->func->GetLocalFunctionId());
  18045. bool anyTrace = globOptTrace || typeSpecTrace || floatTypeSpecTrace || fieldCopyPropTrace || fieldHoistTrace || objTypeSpecTrace || valueTableTrace || fieldPRETrace;
  18046. if (!anyTrace)
  18047. {
  18048. return;
  18049. }
  18050. if (fieldPRETrace && this->IsLoopPrePass())
  18051. {
  18052. if (block->isLoopHeader && before)
  18053. {
  18054. Output::Print(_u("==== Loop Prepass block header #%-3d, Visiting Loop block head #%-3d\n"),
  18055. this->prePassLoop->GetHeadBlock()->GetBlockNum(), block->GetBlockNum());
  18056. }
  18057. }
  18058. if (!typeSpecTrace && !floatTypeSpecTrace && !valueTableTrace && !Js::Configuration::Global.flags.Verbose)
  18059. {
  18060. return;
  18061. }
  18062. if (before)
  18063. {
  18064. Output::Print(_u("========================================================================\n"));
  18065. Output::Print(_u("Begin OptBlock: Block #%-3d"), block->GetBlockNum());
  18066. if (block->loop)
  18067. {
  18068. Output::Print(_u(" Loop block header:%-3d currentLoop block head:%-3d %s"),
  18069. block->loop->GetHeadBlock()->GetBlockNum(),
  18070. this->prePassLoop ? this->prePassLoop->GetHeadBlock()->GetBlockNum() : 0,
  18071. this->IsLoopPrePass() ? _u("PrePass") : _u(""));
  18072. }
  18073. Output::Print(_u("\n"));
  18074. }
  18075. else
  18076. {
  18077. Output::Print(_u("-----------------------------------------------------------------------\n"));
  18078. Output::Print(_u("After OptBlock: Block #%-3d\n"), block->GetBlockNum());
  18079. }
  18080. if ((typeSpecTrace || floatTypeSpecTrace) && !block->globOptData.liveVarSyms->IsEmpty())
  18081. {
  18082. Output::Print(_u(" Live var syms: "));
  18083. block->globOptData.liveVarSyms->Dump();
  18084. }
  18085. if (typeSpecTrace && !block->globOptData.liveInt32Syms->IsEmpty())
  18086. {
  18087. Assert(this->tempBv->IsEmpty());
  18088. this->tempBv->Minus(block->globOptData.liveInt32Syms, block->globOptData.liveLossyInt32Syms);
  18089. if(!this->tempBv->IsEmpty())
  18090. {
  18091. Output::Print(_u(" Int32 type specialized (lossless) syms: "));
  18092. this->tempBv->Dump();
  18093. }
  18094. this->tempBv->ClearAll();
  18095. if(!block->globOptData.liveLossyInt32Syms->IsEmpty())
  18096. {
  18097. Output::Print(_u(" Int32 converted (lossy) syms: "));
  18098. block->globOptData.liveLossyInt32Syms->Dump();
  18099. }
  18100. }
  18101. if (floatTypeSpecTrace && !block->globOptData.liveFloat64Syms->IsEmpty())
  18102. {
  18103. Output::Print(_u(" Float64 type specialized syms: "));
  18104. block->globOptData.liveFloat64Syms->Dump();
  18105. }
  18106. if ((fieldCopyPropTrace || objTypeSpecTrace) && this->DoFieldCopyProp(block->loop) && !block->globOptData.liveFields->IsEmpty())
  18107. {
  18108. Output::Print(_u(" Live field syms: "));
  18109. block->globOptData.liveFields->Dump();
  18110. }
  18111. if ((fieldHoistTrace || objTypeSpecTrace) && this->DoFieldHoisting(block->loop) && HasHoistableFields(block))
  18112. {
  18113. Output::Print(_u(" Hoistable field sym: "));
  18114. block->globOptData.hoistableFields->Dump();
  18115. }
  18116. if (objTypeSpecTrace || valueTableTrace)
  18117. {
  18118. Output::Print(_u(" Value table:\n"));
  18119. DumpSymToValueMap(block->globOptData.symToValueMap);
  18120. }
  18121. if (before)
  18122. {
  18123. Output::Print(_u("-----------------------------------------------------------------------\n")); \
  18124. }
  18125. Output::Flush();
  18126. }
  18127. void
  18128. GlobOpt::TraceSettings()
  18129. {
  18130. Output::Print(_u("GlobOpt Settings:\r\n"));
  18131. Output::Print(_u(" FloatTypeSpec: %s\r\n"), this->DoFloatTypeSpec() ? _u("enabled") : _u("disabled"));
  18132. Output::Print(_u(" AggressiveIntTypeSpec: %s\r\n"), this->DoAggressiveIntTypeSpec() ? _u("enabled") : _u("disabled"));
  18133. Output::Print(_u(" LossyIntTypeSpec: %s\r\n"), this->DoLossyIntTypeSpec() ? _u("enabled") : _u("disabled"));
  18134. Output::Print(_u(" ArrayCheckHoist: %s\r\n"), this->func->GetProfileInfo()->IsArrayCheckHoistDisabled(func->IsLoopBody()) ? _u("disabled") : _u("enabled"));
  18135. Output::Print(_u(" ImplicitCallFlags: %s\r\n"), Js::DynamicProfileInfo::GetImplicitCallFlagsString(this->func->m_fg->implicitCallFlags));
  18136. for (Loop * loop = this->func->m_fg->loopList; loop != NULL; loop = loop->next)
  18137. {
  18138. Output::Print(_u(" loop: %d, ImplicitCallFlags: %s\r\n"), loop->GetLoopNumber(),
  18139. Js::DynamicProfileInfo::GetImplicitCallFlagsString(loop->GetImplicitCallFlags()));
  18140. }
  18141. Output::Flush();
  18142. }
  18143. #endif // DBG_DUMP
  18144. IR::Instr *
  18145. GlobOpt::TrackMarkTempObject(IR::Instr * instrStart, IR::Instr * instrLast)
  18146. {
  18147. if (!this->func->GetHasMarkTempObjects())
  18148. {
  18149. return instrLast;
  18150. }
  18151. IR::Instr * instr = instrStart;
  18152. IR::Instr * instrEnd = instrLast->m_next;
  18153. IR::Instr * lastInstr = nullptr;
  18154. GlobOptBlockData& globOptData = this->currentBlock->globOptData;
  18155. do
  18156. {
  18157. bool mayNeedBailOnImplicitCallsPreOp = !this->IsLoopPrePass()
  18158. && instr->HasAnyImplicitCalls()
  18159. && globOptData.maybeTempObjectSyms != nullptr;
  18160. if (mayNeedBailOnImplicitCallsPreOp)
  18161. {
  18162. IR::Opnd * src1 = instr->GetSrc1();
  18163. if (src1)
  18164. {
  18165. instr = GenerateBailOutMarkTempObjectIfNeeded(instr, src1, false);
  18166. IR::Opnd * src2 = instr->GetSrc2();
  18167. if (src2)
  18168. {
  18169. instr = GenerateBailOutMarkTempObjectIfNeeded(instr, src2, false);
  18170. }
  18171. }
  18172. }
  18173. IR::Opnd *dst = instr->GetDst();
  18174. if (dst)
  18175. {
  18176. if (dst->IsRegOpnd())
  18177. {
  18178. TrackTempObjectSyms(instr, dst->AsRegOpnd());
  18179. }
  18180. else if (mayNeedBailOnImplicitCallsPreOp)
  18181. {
  18182. instr = GenerateBailOutMarkTempObjectIfNeeded(instr, dst, true);
  18183. }
  18184. }
  18185. lastInstr = instr;
  18186. instr = instr->m_next;
  18187. }
  18188. while (instr != instrEnd);
  18189. return lastInstr;
  18190. }
  18191. void
  18192. GlobOpt::TrackTempObjectSyms(IR::Instr * instr, IR::RegOpnd * opnd)
  18193. {
  18194. // If it is marked as dstIsTempObject, we should have mark temped it, or type specialized it to Ld_I4.
  18195. Assert(!instr->dstIsTempObject || ObjectTempVerify::CanMarkTemp(instr, nullptr));
  18196. GlobOptBlockData& globOptData = this->currentBlock->globOptData;
  18197. bool canStoreTemp = false;
  18198. bool maybeTemp = false;
  18199. if (OpCodeAttr::TempObjectProducing(instr->m_opcode))
  18200. {
  18201. maybeTemp = instr->dstIsTempObject;
  18202. // We have to make sure that lower will always generate code to do stack allocation
  18203. // before we can store any other stack instance onto it. Otherwise, we would not
  18204. // walk object to box the stack property.
  18205. canStoreTemp = instr->dstIsTempObject && ObjectTemp::CanStoreTemp(instr);
  18206. }
  18207. else if (OpCodeAttr::TempObjectTransfer(instr->m_opcode))
  18208. {
  18209. // Need to check both sources, GetNewScObject has two srcs for transfer.
  18210. // No need to get var equiv sym here as transfer of type spec value does not transfer a mark temp object.
  18211. maybeTemp = globOptData.maybeTempObjectSyms && (
  18212. (instr->GetSrc1()->IsRegOpnd() && globOptData.maybeTempObjectSyms->Test(instr->GetSrc1()->AsRegOpnd()->m_sym->m_id))
  18213. || (instr->GetSrc2() && instr->GetSrc2()->IsRegOpnd() && globOptData.maybeTempObjectSyms->Test(instr->GetSrc2()->AsRegOpnd()->m_sym->m_id)));
  18214. canStoreTemp = globOptData.canStoreTempObjectSyms && (
  18215. (instr->GetSrc1()->IsRegOpnd() && globOptData.canStoreTempObjectSyms->Test(instr->GetSrc1()->AsRegOpnd()->m_sym->m_id))
  18216. && (!instr->GetSrc2() || (instr->GetSrc2()->IsRegOpnd() && globOptData.canStoreTempObjectSyms->Test(instr->GetSrc2()->AsRegOpnd()->m_sym->m_id))));
  18217. Assert(!canStoreTemp || instr->dstIsTempObject);
  18218. Assert(!maybeTemp || instr->dstIsTempObject);
  18219. }
  18220. // Need to get the var equiv sym as assignment of type specialized sym kill the var sym value anyway.
  18221. StackSym * sym = opnd->m_sym;
  18222. if (!sym->IsVar())
  18223. {
  18224. sym = sym->GetVarEquivSym(nullptr);
  18225. if (sym == nullptr)
  18226. {
  18227. return;
  18228. }
  18229. }
  18230. SymID symId = sym->m_id;
  18231. if (maybeTemp)
  18232. {
  18233. // Only var sym should be temp objects
  18234. Assert(opnd->m_sym == sym);
  18235. if (globOptData.maybeTempObjectSyms == nullptr)
  18236. {
  18237. globOptData.maybeTempObjectSyms = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
  18238. }
  18239. globOptData.maybeTempObjectSyms->Set(symId);
  18240. if (canStoreTemp)
  18241. {
  18242. if (instr->m_opcode == Js::OpCode::NewScObjectLiteral && !this->IsLoopPrePass())
  18243. {
  18244. // For object literal, we install the final type up front.
  18245. // If there are bailout before we finish initializing all the fields, we need to
  18246. // zero out the rest if we stack allocate the literal, so that the boxing would not
  18247. // try to box trash pointer in the properties.
  18248. // Although object Literal initialization can be done lexically, BailOnNoProfile may cause some path
  18249. // to disappear. Do it is flow base make it easier to stop propagate those entries.
  18250. IR::IntConstOpnd * propertyArrayIdOpnd = instr->GetSrc1()->AsIntConstOpnd();
  18251. const Js::PropertyIdArray * propIds = Js::ByteCodeReader::ReadPropertyIdArrayWithLock(propertyArrayIdOpnd->AsUint32(), instr->m_func->GetJnFunction());
  18252. // Duplicates are removed by parser
  18253. Assert(!propIds->hadDuplicates);
  18254. if (globOptData.stackLiteralInitFldDataMap == nullptr)
  18255. {
  18256. globOptData.stackLiteralInitFldDataMap = JitAnew(alloc, StackLiteralInitFldDataMap, alloc);
  18257. }
  18258. else
  18259. {
  18260. Assert(!globOptData.stackLiteralInitFldDataMap->ContainsKey(sym));
  18261. }
  18262. StackLiteralInitFldData data = { propIds, 0};
  18263. globOptData.stackLiteralInitFldDataMap->AddNew(sym, data);
  18264. }
  18265. if (globOptData.canStoreTempObjectSyms == nullptr)
  18266. {
  18267. globOptData.canStoreTempObjectSyms = JitAnew(this->alloc, BVSparse<JitArenaAllocator>, this->alloc);
  18268. }
  18269. globOptData.canStoreTempObjectSyms->Set(symId);
  18270. }
  18271. else if (globOptData.canStoreTempObjectSyms)
  18272. {
  18273. globOptData.canStoreTempObjectSyms->Clear(symId);
  18274. }
  18275. }
  18276. else
  18277. {
  18278. Assert(!canStoreTemp);
  18279. if (globOptData.maybeTempObjectSyms)
  18280. {
  18281. if (globOptData.canStoreTempObjectSyms)
  18282. {
  18283. globOptData.canStoreTempObjectSyms->Clear(symId);
  18284. }
  18285. globOptData.maybeTempObjectSyms->Clear(symId);
  18286. }
  18287. else
  18288. {
  18289. Assert(!globOptData.canStoreTempObjectSyms);
  18290. }
  18291. // The symbol is being assigned to, the sym shouldn't still be in the stackLiteralInitFldDataMap
  18292. Assert(this->IsLoopPrePass() ||
  18293. globOptData.stackLiteralInitFldDataMap == nullptr
  18294. || globOptData.stackLiteralInitFldDataMap->Count() == 0
  18295. || !globOptData.stackLiteralInitFldDataMap->ContainsKey(sym));
  18296. }
  18297. }
  18298. IR::Instr *
  18299. GlobOpt::GenerateBailOutMarkTempObjectIfNeeded(IR::Instr * instr, IR::Opnd * opnd, bool isDst)
  18300. {
  18301. Assert(opnd);
  18302. Assert(isDst == (opnd == instr->GetDst()));
  18303. Assert(opnd != instr->GetDst() || !opnd->IsRegOpnd());
  18304. Assert(!this->IsLoopPrePass());
  18305. Assert(instr->HasAnyImplicitCalls());
  18306. // Only dst reg opnd opcode or ArgOut_A should have dstIsTempObject marked
  18307. Assert(!isDst || !instr->dstIsTempObject || instr->m_opcode == Js::OpCode::ArgOut_A);
  18308. // Post-op implicit call shouldn't have installed yet
  18309. Assert(!instr->HasBailOutInfo() || (instr->GetBailOutKind() & IR::BailOutKindBits) != IR::BailOutOnImplicitCalls);
  18310. GlobOptBlockData& globOptData = this->currentBlock->globOptData;
  18311. Assert(globOptData.maybeTempObjectSyms != nullptr);
  18312. IR::PropertySymOpnd * propertySymOpnd = nullptr;
  18313. StackSym * stackSym = ObjectTemp::GetStackSym(opnd, &propertySymOpnd);
  18314. // It is okay to not get the var equiv sym here, as use of a type specialized sym is not use of the temp object
  18315. // so no need to add mark temp bailout.
  18316. // TempObjectSysm doesn't contain any type spec sym, so we will get false here for all type spec sym.
  18317. if (stackSym && globOptData.maybeTempObjectSyms->Test(stackSym->m_id))
  18318. {
  18319. if (instr->HasBailOutInfo())
  18320. {
  18321. instr->SetBailOutKind(instr->GetBailOutKind() | IR::BailOutMarkTempObject);
  18322. }
  18323. else
  18324. {
  18325. // On insert the pre op bailout if it is not Direct field access do nothing, don't check the dst yet.
  18326. // SetTypeCheckBailout will clear this out if it is direct field access.
  18327. if (isDst
  18328. || (instr->m_opcode == Js::OpCode::FromVar && !opnd->GetValueType().IsPrimitive())
  18329. || propertySymOpnd == nullptr
  18330. || !propertySymOpnd->IsTypeCheckProtected())
  18331. {
  18332. this->GenerateBailAtOperation(&instr, IR::BailOutMarkTempObject);
  18333. }
  18334. }
  18335. if (!opnd->IsRegOpnd() && (!isDst || (globOptData.canStoreTempObjectSyms && globOptData.canStoreTempObjectSyms->Test(stackSym->m_id))))
  18336. {
  18337. // If this opnd is a dst, that means that the object pointer is a stack object,
  18338. // and we can store temp object/number on it.
  18339. // If the opnd is a src, that means that the object pointer may be a stack object
  18340. // so the load may be a temp object/number and we need to track its use.
  18341. // Don't mark start of indir as can store temp, because we don't actually know
  18342. // what it is assigning to.
  18343. if (!isDst || !opnd->IsIndirOpnd())
  18344. {
  18345. opnd->SetCanStoreTemp();
  18346. }
  18347. if (propertySymOpnd)
  18348. {
  18349. // Track initfld of stack literals
  18350. if (isDst && instr->m_opcode == Js::OpCode::InitFld)
  18351. {
  18352. const Js::PropertyId propertyId = propertySymOpnd->m_sym->AsPropertySym()->m_propertyId;
  18353. // We don't need to track numeric properties init
  18354. if (!this->func->GetScriptContext()->GetPropertyNameLocked(propertyId)->IsNumeric())
  18355. {
  18356. DebugOnly(bool found = false);
  18357. globOptData.stackLiteralInitFldDataMap->RemoveIf(stackSym,
  18358. [&](StackSym * key, StackLiteralInitFldData & data)
  18359. {
  18360. DebugOnly(found = true);
  18361. Assert(key == stackSym);
  18362. Assert(data.currentInitFldCount < data.propIds->count);
  18363. if (data.propIds->elements[data.currentInitFldCount] != propertyId)
  18364. {
  18365. #if DBG
  18366. bool duplicate = false;
  18367. for (uint i = 0; i < data.currentInitFldCount; i++)
  18368. {
  18369. if (data.propIds->elements[i] == propertyId)
  18370. {
  18371. duplicate = true;
  18372. break;
  18373. }
  18374. }
  18375. Assert(duplicate);
  18376. #endif
  18377. // duplicate initialization
  18378. return false;
  18379. }
  18380. bool finished = (++data.currentInitFldCount == data.propIds->count);
  18381. #if DBG
  18382. if (finished)
  18383. {
  18384. // We can still track the finished stack literal InitFld lexically.
  18385. this->finishedStackLiteralInitFld->Set(stackSym->m_id);
  18386. }
  18387. #endif
  18388. return finished;
  18389. });
  18390. // We might still see InitFld even we have finished with all the property Id because
  18391. // of duplicate entries at the end
  18392. Assert(found || finishedStackLiteralInitFld->Test(stackSym->m_id));
  18393. }
  18394. }
  18395. }
  18396. }
  18397. }
  18398. return instr;
  18399. }
  18400. void
  18401. GlobOpt::KillStateForGeneratorYield()
  18402. {
  18403. GlobOptBlockData* globOptData = &this->currentBlock->globOptData;
  18404. /*
  18405. TODO[generators][ianhall]: Do a ToVar on any typespec'd syms before the bailout so that we can enable typespec in generators without bailin having to restore typespec'd values
  18406. FOREACH_BITSET_IN_SPARSEBV(symId, globOptData->liveInt32Syms)
  18407. {
  18408. this->ToVar(instr, , this->currentBlock, , );
  18409. }
  18410. NEXT_BITSET_IN_SPARSEBV;
  18411. FOREACH_BITSET_IN_SPARSEBV(symId, globOptData->liveInt32Syms)
  18412. {
  18413. this->ToVar(instr, , this->currentBlock, , );
  18414. }
  18415. NEXT_BITSET_IN_SPARSEBV;
  18416. */
  18417. FOREACH_GLOBHASHTABLE_ENTRY(bucket, globOptData->symToValueMap)
  18418. {
  18419. ValueType type = bucket.element->GetValueInfo()->Type().ToLikely();
  18420. bucket.element = this->NewGenericValue(type);
  18421. }
  18422. NEXT_GLOBHASHTABLE_ENTRY;
  18423. globOptData->exprToValueMap->ClearAll();
  18424. globOptData->liveFields->ClearAll();
  18425. globOptData->liveArrayValues->ClearAll();
  18426. if (globOptData->maybeWrittenTypeSyms)
  18427. {
  18428. globOptData->maybeWrittenTypeSyms->ClearAll();
  18429. }
  18430. globOptData->isTempSrc->ClearAll();
  18431. globOptData->liveInt32Syms->ClearAll();
  18432. globOptData->liveLossyInt32Syms->ClearAll();
  18433. globOptData->liveFloat64Syms->ClearAll();
  18434. // SIMD_JS
  18435. globOptData->liveSimd128F4Syms->ClearAll();
  18436. globOptData->liveSimd128I4Syms->ClearAll();
  18437. if (globOptData->hoistableFields)
  18438. {
  18439. globOptData->hoistableFields->ClearAll();
  18440. }
  18441. // Keep globOptData->liveVarSyms as is
  18442. // Keep globOptData->argObjSyms as is
  18443. // MarkTemp should be disabled for generator functions for now
  18444. Assert(globOptData->maybeTempObjectSyms == nullptr || globOptData->maybeTempObjectSyms->IsEmpty());
  18445. Assert(globOptData->canStoreTempObjectSyms == nullptr || globOptData->canStoreTempObjectSyms->IsEmpty());
  18446. globOptData->valuesToKillOnCalls->Clear();
  18447. if (globOptData->inductionVariables)
  18448. {
  18449. globOptData->inductionVariables->Clear();
  18450. }
  18451. if (globOptData->availableIntBoundChecks)
  18452. {
  18453. globOptData->availableIntBoundChecks->Clear();
  18454. }
  18455. // Keep bailout data as is
  18456. globOptData->hasCSECandidates = false;
  18457. }
  18458. LoopCount *
  18459. GlobOpt::GetOrGenerateLoopCountForMemOp(Loop *loop)
  18460. {
  18461. LoopCount *loopCount = loop->loopCount;
  18462. if (loopCount && !loopCount->HasGeneratedLoopCountSym())
  18463. {
  18464. Assert(loop->bailOutInfo);
  18465. EnsureBailTarget(loop);
  18466. GenerateLoopCountPlusOne(loop, loopCount);
  18467. }
  18468. return loopCount;
  18469. }
  18470. IR::Opnd *
  18471. GlobOpt::GenerateInductionVariableChangeForMemOp(Loop *loop, byte unroll, IR::Instr *insertBeforeInstr)
  18472. {
  18473. LoopCount *loopCount = loop->loopCount;
  18474. IR::Opnd *sizeOpnd = nullptr;
  18475. Assert(loopCount);
  18476. Assert(loop->memOpInfo->inductionVariableOpndPerUnrollMap);
  18477. if (loop->memOpInfo->inductionVariableOpndPerUnrollMap->TryGetValue(unroll, &sizeOpnd))
  18478. {
  18479. return sizeOpnd;
  18480. }
  18481. Func *localFunc = loop->GetFunc();
  18482. const auto InsertInstr = [&](IR::Instr *instr)
  18483. {
  18484. if (insertBeforeInstr == nullptr)
  18485. {
  18486. loop->landingPad->InsertAfter(instr);
  18487. }
  18488. else
  18489. {
  18490. insertBeforeInstr->InsertBefore(instr);
  18491. }
  18492. };
  18493. if (loopCount->LoopCountMinusOneSym())
  18494. {
  18495. IRType type = loopCount->LoopCountSym()->GetType();
  18496. // Loop count is off by one, so add one
  18497. IR::RegOpnd *loopCountOpnd = IR::RegOpnd::New(loopCount->LoopCountSym(), type, localFunc);
  18498. sizeOpnd = loopCountOpnd;
  18499. if (unroll != 1)
  18500. {
  18501. sizeOpnd = IR::RegOpnd::New(TyUint32, this->func);
  18502. IR::Opnd *unrollOpnd = IR::IntConstOpnd::New(unroll, type, localFunc, true);
  18503. InsertInstr(IR::Instr::New(Js::OpCode::Mul_I4,
  18504. sizeOpnd,
  18505. loopCountOpnd,
  18506. unrollOpnd,
  18507. localFunc));
  18508. }
  18509. }
  18510. else
  18511. {
  18512. uint size = (loopCount->LoopCountMinusOneConstantValue() + 1) * unroll;
  18513. sizeOpnd = IR::IntConstOpnd::New(size, IRType::TyUint32, localFunc, true);
  18514. }
  18515. loop->memOpInfo->inductionVariableOpndPerUnrollMap->Add(unroll, sizeOpnd);
  18516. return sizeOpnd;
  18517. }
  18518. IR::RegOpnd*
  18519. GlobOpt::GenerateStartIndexOpndForMemop(Loop *loop, IR::Opnd *indexOpnd, IR::Opnd *sizeOpnd, bool isInductionVariableChangeIncremental, bool bIndexAlreadyChanged, IR::Instr *insertBeforeInstr)
  18520. {
  18521. IR::RegOpnd *startIndexOpnd = nullptr;
  18522. Func *localFunc = loop->GetFunc();
  18523. IRType type = indexOpnd->GetType();
  18524. const int cacheIndex = ((int)isInductionVariableChangeIncremental << 1) | (int)bIndexAlreadyChanged;
  18525. if (loop->memOpInfo->startIndexOpndCache[cacheIndex])
  18526. {
  18527. return loop->memOpInfo->startIndexOpndCache[cacheIndex];
  18528. }
  18529. const auto InsertInstr = [&](IR::Instr *instr)
  18530. {
  18531. if (insertBeforeInstr == nullptr)
  18532. {
  18533. loop->landingPad->InsertAfter(instr);
  18534. }
  18535. else
  18536. {
  18537. insertBeforeInstr->InsertBefore(instr);
  18538. }
  18539. };
  18540. startIndexOpnd = IR::RegOpnd::New(type, localFunc);
  18541. // If the 2 are different we can simply use indexOpnd
  18542. if (isInductionVariableChangeIncremental != bIndexAlreadyChanged)
  18543. {
  18544. InsertInstr(IR::Instr::New(Js::OpCode::Ld_A,
  18545. startIndexOpnd,
  18546. indexOpnd,
  18547. localFunc));
  18548. }
  18549. else
  18550. {
  18551. // Otherwise add 1 to it
  18552. InsertInstr(IR::Instr::New(Js::OpCode::Add_I4,
  18553. startIndexOpnd,
  18554. indexOpnd,
  18555. IR::IntConstOpnd::New(1, type, localFunc, true),
  18556. localFunc));
  18557. }
  18558. if (!isInductionVariableChangeIncremental)
  18559. {
  18560. InsertInstr(IR::Instr::New(Js::OpCode::Sub_I4,
  18561. startIndexOpnd,
  18562. startIndexOpnd,
  18563. sizeOpnd,
  18564. localFunc));
  18565. }
  18566. loop->memOpInfo->startIndexOpndCache[cacheIndex] = startIndexOpnd;
  18567. return startIndexOpnd;
  18568. }
  18569. IR::Instr*
  18570. GlobOpt::FindUpperBoundsCheckInstr(IR::Instr* fromInstr)
  18571. {
  18572. IR::Instr *upperBoundCheck = fromInstr;
  18573. do
  18574. {
  18575. upperBoundCheck = upperBoundCheck->m_prev;
  18576. Assert(upperBoundCheck);
  18577. Assert(!upperBoundCheck->IsLabelInstr());
  18578. } while (upperBoundCheck->m_opcode != Js::OpCode::BoundCheck);
  18579. return upperBoundCheck;
  18580. }
  18581. IR::Instr*
  18582. GlobOpt::FindArraySegmentLoadInstr(IR::Instr* fromInstr)
  18583. {
  18584. IR::Instr *headSegmentLengthLoad = fromInstr;
  18585. do
  18586. {
  18587. headSegmentLengthLoad = headSegmentLengthLoad->m_prev;
  18588. Assert(headSegmentLengthLoad);
  18589. Assert(!headSegmentLengthLoad->IsLabelInstr());
  18590. } while (headSegmentLengthLoad->m_opcode != Js::OpCode::LdIndir);
  18591. return headSegmentLengthLoad;
  18592. }
  18593. void
  18594. GlobOpt::RemoveMemOpSrcInstr(IR::Instr* memopInstr, IR::Instr* srcInstr, BasicBlock* block)
  18595. {
  18596. Assert(srcInstr && (srcInstr->m_opcode == Js::OpCode::LdElemI_A || srcInstr->m_opcode == Js::OpCode::StElemI_A || srcInstr->m_opcode == Js::OpCode::StElemI_A_Strict));
  18597. Assert(memopInstr && (memopInstr->m_opcode == Js::OpCode::Memcopy || memopInstr->m_opcode == Js::OpCode::Memset));
  18598. Assert(block);
  18599. const bool isDst = srcInstr->m_opcode == Js::OpCode::StElemI_A || srcInstr->m_opcode == Js::OpCode::StElemI_A_Strict;
  18600. IR::RegOpnd* opnd = (isDst ? memopInstr->GetDst() : memopInstr->GetSrc1())->AsIndirOpnd()->GetBaseOpnd();
  18601. IR::ArrayRegOpnd* arrayOpnd = opnd->IsArrayRegOpnd() ? opnd->AsArrayRegOpnd() : nullptr;
  18602. IR::Instr* topInstr = srcInstr;
  18603. if (srcInstr->extractedUpperBoundCheckWithoutHoisting)
  18604. {
  18605. IR::Instr *upperBoundCheck = FindUpperBoundsCheckInstr(srcInstr);
  18606. Assert(upperBoundCheck && upperBoundCheck != srcInstr);
  18607. topInstr = upperBoundCheck;
  18608. }
  18609. if (srcInstr->loadedArrayHeadSegmentLength && arrayOpnd && arrayOpnd->HeadSegmentLengthSym())
  18610. {
  18611. IR::Instr *arrayLoadSegmentHeadLength = FindArraySegmentLoadInstr(topInstr);
  18612. Assert(arrayLoadSegmentHeadLength);
  18613. topInstr = arrayLoadSegmentHeadLength;
  18614. arrayOpnd->RemoveHeadSegmentLengthSym();
  18615. }
  18616. if (srcInstr->loadedArrayHeadSegment && arrayOpnd && arrayOpnd->HeadSegmentSym())
  18617. {
  18618. IR::Instr *arrayLoadSegmentHead = FindArraySegmentLoadInstr(topInstr);
  18619. Assert(arrayLoadSegmentHead);
  18620. topInstr = arrayLoadSegmentHead;
  18621. arrayOpnd->RemoveHeadSegmentSym();
  18622. }
  18623. // If no bounds check are present, simply look up for instruction added for instrumentation
  18624. if(topInstr == srcInstr)
  18625. {
  18626. bool checkPrev = true;
  18627. while (checkPrev)
  18628. {
  18629. switch (topInstr->m_prev->m_opcode)
  18630. {
  18631. case Js::OpCode::NoImplicitCallUses:
  18632. case Js::OpCode::ByteCodeUses:
  18633. topInstr = topInstr->m_prev;
  18634. checkPrev = !!topInstr->m_prev;
  18635. break;
  18636. default:
  18637. checkPrev = false;
  18638. break;
  18639. }
  18640. }
  18641. }
  18642. while (topInstr != srcInstr)
  18643. {
  18644. IR::Instr* removeInstr = topInstr;
  18645. topInstr = topInstr->m_next;
  18646. Assert(
  18647. removeInstr->m_opcode == Js::OpCode::NoImplicitCallUses ||
  18648. removeInstr->m_opcode == Js::OpCode::ByteCodeUses ||
  18649. removeInstr->m_opcode == Js::OpCode::LdIndir ||
  18650. removeInstr->m_opcode == Js::OpCode::BoundCheck
  18651. );
  18652. if (removeInstr->m_opcode != Js::OpCode::ByteCodeUses)
  18653. {
  18654. block->RemoveInstr(removeInstr);
  18655. }
  18656. }
  18657. this->ConvertToByteCodeUses(srcInstr);
  18658. }
  18659. void
  18660. GlobOpt::GetMemOpSrcInfo(Loop* loop, IR::Instr* instr, IR::RegOpnd*& base, IR::RegOpnd*& index, IRType& arrayType)
  18661. {
  18662. Assert(instr && (instr->m_opcode == Js::OpCode::LdElemI_A || instr->m_opcode == Js::OpCode::StElemI_A || instr->m_opcode == Js::OpCode::StElemI_A_Strict));
  18663. IR::Opnd* arrayOpnd = instr->m_opcode == Js::OpCode::LdElemI_A ? instr->GetSrc1() : instr->GetDst();
  18664. Assert(arrayOpnd->IsIndirOpnd());
  18665. IR::IndirOpnd* indirArrayOpnd = arrayOpnd->AsIndirOpnd();
  18666. IR::RegOpnd* baseOpnd = (IR::RegOpnd*)indirArrayOpnd->GetBaseOpnd();
  18667. IR::RegOpnd* indexOpnd = (IR::RegOpnd*)indirArrayOpnd->GetIndexOpnd();
  18668. Assert(baseOpnd);
  18669. Assert(indexOpnd);
  18670. // Process Out Params
  18671. base = baseOpnd;
  18672. index = indexOpnd;
  18673. arrayType = indirArrayOpnd->GetType();
  18674. }
  18675. void
  18676. GlobOpt::EmitMemop(Loop * loop, LoopCount *loopCount, const MemOpEmitData* emitData)
  18677. {
  18678. Assert(emitData);
  18679. Assert(emitData->candidate);
  18680. Assert(emitData->stElemInstr);
  18681. Assert(emitData->stElemInstr->m_opcode == Js::OpCode::StElemI_A || emitData->stElemInstr->m_opcode == Js::OpCode::StElemI_A_Strict);
  18682. IR::BailOutKind bailOutKind = emitData->bailOutKind;
  18683. const byte unroll = emitData->inductionVar.unroll;
  18684. Assert(unroll == 1);
  18685. const bool isInductionVariableChangeIncremental = emitData->inductionVar.isIncremental;
  18686. const bool bIndexAlreadyChanged = emitData->candidate->bIndexAlreadyChanged;
  18687. IR::RegOpnd *baseOpnd = nullptr;
  18688. IR::RegOpnd *indexOpnd = nullptr;
  18689. IRType dstType;
  18690. GetMemOpSrcInfo(loop, emitData->stElemInstr, baseOpnd, indexOpnd, dstType);
  18691. Func *localFunc = loop->GetFunc();
  18692. // Handle bailout info
  18693. EnsureBailTarget(loop);
  18694. Assert(bailOutKind != IR::BailOutInvalid);
  18695. // Keep only Array bits bailOuts. Consider handling these bailouts instead of simply ignoring them
  18696. bailOutKind &= IR::BailOutForArrayBits;
  18697. // Add our custom bailout to handle Op_MemCopy return value.
  18698. bailOutKind |= IR::BailOutOnMemOpError;
  18699. BailOutInfo *const bailOutInfo = loop->bailOutInfo;
  18700. Assert(bailOutInfo);
  18701. IR::Instr *insertBeforeInstr = bailOutInfo->bailOutInstr;
  18702. Assert(insertBeforeInstr);
  18703. IR::Opnd *sizeOpnd = GenerateInductionVariableChangeForMemOp(loop, unroll, insertBeforeInstr);
  18704. IR::RegOpnd *startIndexOpnd = GenerateStartIndexOpndForMemop(loop, indexOpnd, sizeOpnd, isInductionVariableChangeIncremental, bIndexAlreadyChanged, insertBeforeInstr);
  18705. IR::IndirOpnd* dstOpnd = IR::IndirOpnd::New(baseOpnd, startIndexOpnd, dstType, localFunc);
  18706. IR::Opnd *src1;
  18707. const bool isMemset = emitData->candidate->IsMemSet();
  18708. // Get the source according to the memop type
  18709. if (isMemset)
  18710. {
  18711. MemSetEmitData* data = (MemSetEmitData*)emitData;
  18712. const Loop::MemSetCandidate* candidate = data->candidate->AsMemSet();
  18713. if (candidate->srcSym)
  18714. {
  18715. IR::RegOpnd* regSrc = IR::RegOpnd::New(candidate->srcSym, candidate->srcSym->GetType(), func);
  18716. regSrc->SetIsJITOptimizedReg(true);
  18717. src1 = regSrc;
  18718. }
  18719. else
  18720. {
  18721. src1 = IR::AddrOpnd::New(candidate->constant.ToVar(localFunc, func->GetScriptContext()), IR::AddrOpndKindConstant, localFunc);
  18722. }
  18723. }
  18724. else
  18725. {
  18726. Assert(emitData->candidate->IsMemCopy());
  18727. MemCopyEmitData* data = (MemCopyEmitData*)emitData;
  18728. Assert(data->ldElemInstr);
  18729. Assert(data->ldElemInstr->m_opcode == Js::OpCode::LdElemI_A);
  18730. IR::RegOpnd *srcBaseOpnd = nullptr;
  18731. IR::RegOpnd *srcIndexOpnd = nullptr;
  18732. IRType srcType;
  18733. GetMemOpSrcInfo(loop, data->ldElemInstr, srcBaseOpnd, srcIndexOpnd, srcType);
  18734. Assert(GetVarSymID(srcIndexOpnd->GetStackSym()) == GetVarSymID(indexOpnd->GetStackSym()));
  18735. src1 = IR::IndirOpnd::New(srcBaseOpnd, startIndexOpnd, srcType, localFunc);
  18736. }
  18737. // Generate memcopy
  18738. IR::Instr* memopInstr = IR::BailOutInstr::New(isMemset ? Js::OpCode::Memset : Js::OpCode::Memcopy, bailOutKind, bailOutInfo, localFunc);
  18739. memopInstr->SetDst(dstOpnd);
  18740. memopInstr->SetSrc1(src1);
  18741. memopInstr->SetSrc2(sizeOpnd);
  18742. insertBeforeInstr->InsertBefore(memopInstr);
  18743. #if DBG_DUMP
  18744. if (DO_MEMOP_TRACE())
  18745. {
  18746. char valueTypeStr[VALUE_TYPE_MAX_STRING_SIZE];
  18747. baseOpnd->GetValueType().ToString(valueTypeStr);
  18748. const int loopCountBufSize = 16;
  18749. char16 loopCountBuf[loopCountBufSize];
  18750. if (loopCount->LoopCountMinusOneSym())
  18751. {
  18752. _snwprintf_s(loopCountBuf, loopCountBufSize, _u("s%u"), loopCount->LoopCountMinusOneSym()->m_id);
  18753. }
  18754. else
  18755. {
  18756. _snwprintf_s(loopCountBuf, loopCountBufSize, _u("%u"), loopCount->LoopCountMinusOneConstantValue() + 1);
  18757. }
  18758. if (isMemset)
  18759. {
  18760. const Loop::MemSetCandidate* candidate = emitData->candidate->AsMemSet();
  18761. const int constBufSize = 32;
  18762. char16 constBuf[constBufSize];
  18763. if (candidate->srcSym)
  18764. {
  18765. _snwprintf_s(constBuf, constBufSize, _u("s%u"), candidate->srcSym->m_id);
  18766. }
  18767. else
  18768. {
  18769. switch (candidate->constant.type)
  18770. {
  18771. case TyInt8:
  18772. case TyInt16:
  18773. case TyInt32:
  18774. case TyInt64:
  18775. _snwprintf_s(constBuf, constBufSize, sizeof(IntConstType) == 8 ? _u("lld%") : _u("%d"), candidate->constant.u.intConst.value);
  18776. break;
  18777. case TyFloat32:
  18778. case TyFloat64:
  18779. _snwprintf_s(constBuf, constBufSize, _u("%.4f"), candidate->constant.u.floatConst.value);
  18780. break;
  18781. case TyVar:
  18782. _snwprintf_s(constBuf, constBufSize, sizeof(Js::Var) == 8 ? _u("0x%.16llX") : _u("0x%.8X"), candidate->constant.u.varConst.value);
  18783. break;
  18784. default:
  18785. AssertMsg(false, "Unsupported constant type");
  18786. _snwprintf_s(constBuf, constBufSize, _u("Unknown"));
  18787. break;
  18788. }
  18789. }
  18790. TRACE_MEMOP_PHASE(MemSet, loop, emitData->stElemInstr,
  18791. _u("ValueType: %S, Base: s%u, Index: s%u, Constant: %s, LoopCount: %s, IsIndexChangedBeforeUse: %d"),
  18792. valueTypeStr,
  18793. candidate->base,
  18794. candidate->index,
  18795. constBuf,
  18796. loopCountBuf,
  18797. bIndexAlreadyChanged);
  18798. }
  18799. else
  18800. {
  18801. const Loop::MemCopyCandidate* candidate = emitData->candidate->AsMemCopy();
  18802. TRACE_MEMOP_PHASE(MemCopy, loop, emitData->stElemInstr,
  18803. _u("ValueType: %S, StBase: s%u, Index: s%u, LdBase: s%u, LoopCount: %s, IsIndexChangedBeforeUse: %d"),
  18804. valueTypeStr,
  18805. candidate->base,
  18806. candidate->index,
  18807. candidate->ldBase,
  18808. loopCountBuf,
  18809. bIndexAlreadyChanged);
  18810. }
  18811. }
  18812. #endif
  18813. RemoveMemOpSrcInstr(memopInstr, emitData->stElemInstr, emitData->block);
  18814. if (!isMemset)
  18815. {
  18816. RemoveMemOpSrcInstr(memopInstr, ((MemCopyEmitData*)emitData)->ldElemInstr, emitData->block);
  18817. }
  18818. }
  18819. bool
  18820. GlobOpt::InspectInstrForMemSetCandidate(Loop* loop, IR::Instr* instr, MemSetEmitData* emitData, bool& errorInInstr)
  18821. {
  18822. Assert(emitData && emitData->candidate && emitData->candidate->IsMemSet());
  18823. Loop::MemSetCandidate* candidate = (Loop::MemSetCandidate*)emitData->candidate;
  18824. if (instr->m_opcode == Js::OpCode::StElemI_A || instr->m_opcode == Js::OpCode::StElemI_A_Strict)
  18825. {
  18826. if (instr->GetDst()->IsIndirOpnd()
  18827. && (GetVarSymID(instr->GetDst()->AsIndirOpnd()->GetBaseOpnd()->GetStackSym()) == candidate->base)
  18828. && (GetVarSymID(instr->GetDst()->AsIndirOpnd()->GetIndexOpnd()->GetStackSym()) == candidate->index)
  18829. )
  18830. {
  18831. Assert(instr->IsProfiledInstr());
  18832. emitData->stElemInstr = instr;
  18833. emitData->bailOutKind = instr->GetBailOutKind();
  18834. return true;
  18835. }
  18836. TRACE_MEMOP_PHASE_VERBOSE(MemSet, loop, instr, _u("Orphan StElemI_A detected"));
  18837. errorInInstr = true;
  18838. }
  18839. else if (instr->m_opcode == Js::OpCode::LdElemI_A)
  18840. {
  18841. TRACE_MEMOP_PHASE_VERBOSE(MemSet, loop, instr, _u("Orphan LdElemI_A detected"));
  18842. errorInInstr = true;
  18843. }
  18844. return false;
  18845. }
  18846. bool
  18847. GlobOpt::InspectInstrForMemCopyCandidate(Loop* loop, IR::Instr* instr, MemCopyEmitData* emitData, bool& errorInInstr)
  18848. {
  18849. Assert(emitData && emitData->candidate && emitData->candidate->IsMemCopy());
  18850. Loop::MemCopyCandidate* candidate = (Loop::MemCopyCandidate*)emitData->candidate;
  18851. if (instr->m_opcode == Js::OpCode::StElemI_A || instr->m_opcode == Js::OpCode::StElemI_A_Strict)
  18852. {
  18853. if (
  18854. instr->GetDst()->IsIndirOpnd() &&
  18855. (GetVarSymID(instr->GetDst()->AsIndirOpnd()->GetBaseOpnd()->GetStackSym()) == candidate->base) &&
  18856. (GetVarSymID(instr->GetDst()->AsIndirOpnd()->GetIndexOpnd()->GetStackSym()) == candidate->index)
  18857. )
  18858. {
  18859. Assert(instr->IsProfiledInstr());
  18860. emitData->stElemInstr = instr;
  18861. emitData->bailOutKind = instr->GetBailOutKind();
  18862. // Still need to find the LdElem
  18863. return false;
  18864. }
  18865. TRACE_MEMOP_PHASE_VERBOSE(MemCopy, loop, instr, _u("Orphan StElemI_A detected"));
  18866. errorInInstr = true;
  18867. }
  18868. else if (instr->m_opcode == Js::OpCode::LdElemI_A)
  18869. {
  18870. if (
  18871. emitData->stElemInstr &&
  18872. instr->GetSrc1()->IsIndirOpnd() &&
  18873. (GetVarSymID(instr->GetSrc1()->AsIndirOpnd()->GetBaseOpnd()->GetStackSym()) == candidate->ldBase) &&
  18874. (GetVarSymID(instr->GetSrc1()->AsIndirOpnd()->GetIndexOpnd()->GetStackSym()) == candidate->index)
  18875. )
  18876. {
  18877. Assert(instr->IsProfiledInstr());
  18878. emitData->ldElemInstr = instr;
  18879. ValueType stValueType = emitData->stElemInstr->GetDst()->AsIndirOpnd()->GetBaseOpnd()->GetValueType();
  18880. ValueType ldValueType = emitData->ldElemInstr->GetSrc1()->AsIndirOpnd()->GetBaseOpnd()->GetValueType();
  18881. if (stValueType != ldValueType)
  18882. {
  18883. #if DBG_DUMP
  18884. char16 stValueTypeStr[VALUE_TYPE_MAX_STRING_SIZE];
  18885. stValueType.ToString(stValueTypeStr);
  18886. char16 ldValueTypeStr[VALUE_TYPE_MAX_STRING_SIZE];
  18887. ldValueType.ToString(ldValueTypeStr);
  18888. TRACE_MEMOP_PHASE_VERBOSE(MemCopy, loop, instr, _u("for mismatch in Load(%s) and Store(%s) value type"), ldValueTypeStr, stValueTypeStr);
  18889. #endif
  18890. errorInInstr = true;
  18891. return false;
  18892. }
  18893. // We found both instruction for this candidate
  18894. return true;
  18895. }
  18896. TRACE_MEMOP_PHASE_VERBOSE(MemCopy, loop, instr, _u("Orphan LdElemI_A detected"));
  18897. errorInInstr = true;
  18898. }
  18899. return false;
  18900. }
  18901. // The caller is responsible to free the memory allocated between inOrderEmitData[iEmitData -> end]
  18902. bool
  18903. GlobOpt::ValidateMemOpCandidates(Loop * loop, _Out_writes_(iEmitData) MemOpEmitData** inOrderEmitData, int& iEmitData)
  18904. {
  18905. AnalysisAssert(iEmitData == (int)loop->memOpInfo->candidates->Count());
  18906. // We iterate over the second block of the loop only. MemOp Works only if the loop has exactly 2 blocks
  18907. Assert(loop->blockList.HasTwo());
  18908. Loop::MemOpList::Iterator iter(loop->memOpInfo->candidates);
  18909. BasicBlock* bblock = loop->blockList.Head()->next;
  18910. Loop::MemOpCandidate* candidate = nullptr;
  18911. MemOpEmitData* emitData = nullptr;
  18912. // Iterate backward because the list of candidate is reversed
  18913. FOREACH_INSTR_BACKWARD_IN_BLOCK(instr, bblock)
  18914. {
  18915. if (!candidate)
  18916. {
  18917. // Time to check next candidate
  18918. if (!iter.Next())
  18919. {
  18920. // We have been through the whole list of candidates, finish
  18921. break;
  18922. }
  18923. candidate = iter.Data();
  18924. if (!candidate)
  18925. {
  18926. continue;
  18927. }
  18928. // Common check for memset and memcopy
  18929. Loop::InductionVariableChangeInfo inductionVariableChangeInfo = { 0, 0 };
  18930. // Get the inductionVariable changeInfo
  18931. if (!loop->memOpInfo->inductionVariableChangeInfoMap->TryGetValue(candidate->index, &inductionVariableChangeInfo))
  18932. {
  18933. TRACE_MEMOP_VERBOSE(loop, nullptr, _u("MemOp skipped (s%d): no induction variable"), candidate->base);
  18934. return false;
  18935. }
  18936. if (inductionVariableChangeInfo.unroll != candidate->count)
  18937. {
  18938. TRACE_MEMOP_VERBOSE(loop, nullptr, _u("MemOp skipped (s%d): not matching unroll count"), candidate->base);
  18939. return false;
  18940. }
  18941. if (candidate->IsMemSet())
  18942. {
  18943. Assert(!PHASE_OFF(Js::MemSetPhase, this->func));
  18944. emitData = JitAnew(this->alloc, MemSetEmitData);
  18945. }
  18946. else
  18947. {
  18948. Assert(!PHASE_OFF(Js::MemCopyPhase, this->func));
  18949. // Specific check for memcopy
  18950. Assert(candidate->IsMemCopy());
  18951. Loop::MemCopyCandidate* memcopyCandidate = candidate->AsMemCopy();
  18952. if (memcopyCandidate->base == Js::Constants::InvalidSymID
  18953. || memcopyCandidate->ldBase == Js::Constants::InvalidSymID
  18954. || (memcopyCandidate->ldCount != memcopyCandidate->count))
  18955. {
  18956. TRACE_MEMOP_PHASE(MemCopy, loop, nullptr, _u("(s%d): not matching ldElem and stElem"), candidate->base);
  18957. return false;
  18958. }
  18959. emitData = JitAnew(this->alloc, MemCopyEmitData);
  18960. }
  18961. Assert(emitData);
  18962. emitData->block = bblock;
  18963. emitData->inductionVar = inductionVariableChangeInfo;
  18964. emitData->candidate = candidate;
  18965. }
  18966. bool errorInInstr = false;
  18967. bool candidateFound = candidate->IsMemSet() ?
  18968. InspectInstrForMemSetCandidate(loop, instr, (MemSetEmitData*)emitData, errorInInstr)
  18969. : InspectInstrForMemCopyCandidate(loop, instr, (MemCopyEmitData*)emitData, errorInInstr);
  18970. if (errorInInstr)
  18971. {
  18972. JitAdelete(this->alloc, emitData);
  18973. return false;
  18974. }
  18975. if (candidateFound)
  18976. {
  18977. AnalysisAssert(iEmitData > 0);
  18978. if (iEmitData == 0)
  18979. {
  18980. // Explicit for OACR
  18981. break;
  18982. }
  18983. inOrderEmitData[--iEmitData] = emitData;
  18984. candidate = nullptr;
  18985. emitData = nullptr;
  18986. }
  18987. } NEXT_INSTR_BACKWARD_IN_BLOCK;
  18988. if (iter.IsValid())
  18989. {
  18990. TRACE_MEMOP(loop, nullptr, _u("Candidates not found in loop while validating"));
  18991. return false;
  18992. }
  18993. return true;
  18994. }
  18995. void
  18996. GlobOpt::ProcessMemOp()
  18997. {
  18998. FOREACH_LOOP_IN_FUNC_EDITING(loop, this->func)
  18999. {
  19000. if (DoMemOp(loop))
  19001. {
  19002. const int candidateCount = loop->memOpInfo->candidates->Count();
  19003. Assert(candidateCount > 0);
  19004. LoopCount * loopCount = GetOrGenerateLoopCountForMemOp(loop);
  19005. // If loopCount is not available we can not continue with memop
  19006. if (!loopCount || !(loopCount->LoopCountMinusOneSym() || loopCount->LoopCountMinusOneConstantValue()))
  19007. {
  19008. TRACE_MEMOP(loop, nullptr, _u("MemOp skipped for no loop count"));
  19009. loop->memOpInfo->doMemOp = false;
  19010. loop->memOpInfo->candidates->Clear();
  19011. continue;
  19012. }
  19013. // The list is reversed, check them and place them in order in the following array
  19014. MemOpEmitData** inOrderCandidates = JitAnewArray(this->alloc, MemOpEmitData*, candidateCount);
  19015. int i = candidateCount;
  19016. if (ValidateMemOpCandidates(loop, inOrderCandidates, i))
  19017. {
  19018. Assert(i == 0);
  19019. // Process the valid MemOp candidate in order.
  19020. for (; i < candidateCount; ++i)
  19021. {
  19022. // Emit
  19023. EmitMemop(loop, loopCount, inOrderCandidates[i]);
  19024. JitAdelete(this->alloc, inOrderCandidates[i]);
  19025. }
  19026. }
  19027. else
  19028. {
  19029. Assert(i != 0);
  19030. for (; i < candidateCount; ++i)
  19031. {
  19032. JitAdelete(this->alloc, inOrderCandidates[i]);
  19033. }
  19034. // One of the memop candidates did not validate. Do not emit for this loop.
  19035. loop->memOpInfo->doMemOp = false;
  19036. loop->memOpInfo->candidates->Clear();
  19037. }
  19038. // Free memory
  19039. JitAdeleteArray(this->alloc, candidateCount, inOrderCandidates);
  19040. }
  19041. } NEXT_LOOP_EDITING;
  19042. }