BackwardPass.cpp 357 KB

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