Lower.cpp 869 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074
  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. #include "Debug\DebuggingFlags.h"
  7. #include "Debug\DiagProbe.h"
  8. #include "Debug\DebugManager.h"
  9. // Parser includes
  10. #include "RegexCommon.h"
  11. #include "RegexPattern.h"
  12. #include "ExternalLowerer.h"
  13. ///----------------------------------------------------------------------------
  14. ///
  15. /// Lowerer::Lower
  16. ///
  17. /// Lowerer's main entrypoint. Lowers this function..
  18. ///
  19. ///----------------------------------------------------------------------------
  20. void
  21. Lowerer::Lower()
  22. {
  23. this->m_func->StopMaintainByteCodeOffset();
  24. NoRecoverMemoryJitArenaAllocator localAlloc(L"BE-Lower", this->m_func->m_alloc->GetPageAllocator(), Js::Throw::OutOfMemory);
  25. this->m_alloc = &localAlloc;
  26. BVSparse<JitArenaAllocator> localInitializedTempSym(&localAlloc);
  27. this->initializedTempSym = &localInitializedTempSym;
  28. BVSparse<JitArenaAllocator> localAddToLiveOnBackEdgeSyms(&localAlloc);
  29. this->addToLiveOnBackEdgeSyms = &localAddToLiveOnBackEdgeSyms;
  30. Assert(this->m_func->GetCloneMap() == nullptr);
  31. m_lowererMD.Init(this);
  32. bool defaultDoFastPath = this->m_func->DoFastPaths();
  33. bool loopFastPath = this->m_func->DoLoopFastPaths();
  34. if (!loopFastPath || !defaultDoFastPath
  35. #ifdef INLINE_CACHE_STATS
  36. || PHASE_STATS1(Js::PolymorphicInlineCachePhase)
  37. #endif
  38. )
  39. {
  40. //arguments[] access is similar to array fast path hence disable when array fastpath is disabled.
  41. //loopFastPath is always true except explicitly disabled
  42. //defaultDoFastPath can be false when we the source code size is huge
  43. m_func->SetHasStackArgs(false);
  44. }
  45. if (m_func->HasAnyStackNestedFunc())
  46. {
  47. EnsureStackFunctionListStackSym();
  48. }
  49. if (m_func->DoStackFrameDisplay() && !m_func->IsLoopBody())
  50. {
  51. AllocStackClosure();
  52. }
  53. if (m_func->IsJitInDebugMode())
  54. {
  55. // Initialize metadata of local var slots.
  56. // Too late to wait until Register Allocator, as we need the offset when lowerering bailout for debugger.
  57. int32 hasLocalVarChangedOffset = m_func->GetHasLocalVarChangedOffset();
  58. if (hasLocalVarChangedOffset != Js::Constants::InvalidOffset)
  59. {
  60. // MOV [EBP + m_func->GetHasLocalVarChangedOffset()], 0
  61. StackSym* sym = StackSym::New(TyInt8, m_func);
  62. sym->m_offset = hasLocalVarChangedOffset;
  63. sym->m_allocated = true;
  64. IR::Opnd* opnd1 = IR::SymOpnd::New(sym, TyInt8, m_func);
  65. IR::Opnd* opnd2 = IR::IntConstOpnd::New(0, TyInt8, m_func);
  66. LowererMD::CreateAssign(opnd1, opnd2, m_func->GetFunctionEntryInsertionPoint());
  67. #ifdef DBG
  68. // Pre-fill all local slots with a pattern. This will help identify non-initialized/garbage var values.
  69. // Note that in the beginning of the function in bytecode we should initialize all locals to undefined.
  70. uint32 localSlotCount = m_func->GetJnFunction()->GetEndNonTempLocalIndex() - m_func->GetJnFunction()->GetFirstNonTempLocalIndex();
  71. for (uint i = 0; i < localSlotCount; ++i)
  72. {
  73. int offset = m_func->GetLocalVarSlotOffset(i);
  74. IRType opnd1Type;
  75. opnd2;
  76. uint32 slotSize = Func::GetDiagLocalSlotSize();
  77. switch (slotSize)
  78. {
  79. case 4:
  80. opnd1Type = TyInt32;
  81. opnd2 = IR::IntConstOpnd::New(Func::c_debugFillPattern4, opnd1Type, m_func);
  82. break;
  83. case 8:
  84. opnd1Type = TyInt64;
  85. opnd2 = IR::AddrOpnd::New((Js::Var)Func::c_debugFillPattern8, IR::AddrOpndKindConstant, m_func);
  86. break;
  87. default:
  88. AssertMsg(FALSE, "Unsupported slot size!");
  89. opnd1Type = TyIllegal;
  90. opnd2 = nullptr;
  91. }
  92. sym = StackSym::New(opnd1Type, m_func);
  93. sym->m_offset = offset;
  94. sym->m_allocated = true;
  95. opnd1 = IR::SymOpnd::New(sym, TyInt32, m_func);
  96. LowererMD::CreateAssign(opnd1, opnd2, m_func->GetFunctionEntryInsertionPoint());
  97. }
  98. #endif
  99. }
  100. Assert(!m_func->HasAnyStackNestedFunc());
  101. }
  102. this->LowerRange(m_func->m_headInstr, m_func->m_tailInstr, defaultDoFastPath, loopFastPath);
  103. this->m_func->ClearCloneMap();
  104. if (m_func->HasAnyStackNestedFunc())
  105. {
  106. EnsureZeroLastStackFunctionNext();
  107. }
  108. if (!m_func->IsSimpleJit())
  109. {
  110. Js::EntryPointInfo* entryPointInfo = this->m_func->m_workItem->GetEntryPoint();
  111. Assert(entryPointInfo->GetJitTransferData() != nullptr && !entryPointInfo->GetJitTransferData()->GetIsReady());
  112. }
  113. this->initializedTempSym = nullptr;
  114. this->m_alloc = nullptr;
  115. this->m_func->DisableConstandAddressLoadHoist();
  116. }
  117. void
  118. Lowerer::LowerRange(IR::Instr *instrStart, IR::Instr *instrEnd, bool defaultDoFastPath, bool defaultDoLoopFastPath)
  119. {
  120. bool noMathFastPath;
  121. bool noFieldFastPath;
  122. bool fNoLower = false;
  123. noFieldFastPath = !defaultDoFastPath;
  124. noMathFastPath = !defaultDoFastPath;
  125. #if DBG_DUMP
  126. wchar_t * globOptInstrString = nullptr;
  127. #endif
  128. FOREACH_INSTR_BACKWARD_EDITING_IN_RANGE(instr, instrPrev, instrEnd, instrStart)
  129. {
  130. // Try to peep this`
  131. instr = this->PreLowerPeepInstr(instr, &instrPrev);
  132. #if DBG
  133. IR::Instr * verifyLegalizeInstrNext = instr->m_next;
  134. #endif
  135. // If we have debugger bailout as part of real instr (not separate BailForDebugger instr),
  136. // extract/split out BailOutForDebugger into separate instr, if needed.
  137. // The instr can have just debugger bailout, or debugger bailout + other shared bailout.
  138. // Note that by the time we get here, we should not have aux-only bailout (in globopt we promote it to normal bailout).
  139. if (m_func->IsJitInDebugMode() && instr->HasBailOutInfo() &&
  140. ((instr->GetBailOutKind() & IR::BailOutForDebuggerBits) && instr->m_opcode != Js::OpCode::BailForDebugger ||
  141. instr->HasAuxBailOut()))
  142. {
  143. instr = this->SplitBailForDebugger(instr); // Change instr, as returned is the one we need to lower next.
  144. instrPrev = instr->m_prev; // Change just in case if instr got changed.
  145. }
  146. #if DBG_DUMP
  147. if (!instr->IsLowered() && !instr->IsLabelInstr()
  148. && (CONFIG_FLAG(ForcePostLowerGlobOptInstrString) ||
  149. PHASE_DUMP(Js::LowererPhase, m_func) ||
  150. PHASE_DUMP(Js::LinearScanPhase, m_func) ||
  151. PHASE_DUMP(Js::RegAllocPhase, m_func) ||
  152. PHASE_DUMP(Js::PeepsPhase, m_func) ||
  153. PHASE_DUMP(Js::LayoutPhase, m_func) ||
  154. PHASE_DUMP(Js::EmitterPhase, m_func) ||
  155. PHASE_DUMP(Js::EncoderPhase, m_func) ||
  156. PHASE_DUMP(Js::BackEndPhase, m_func)))
  157. {
  158. if(instr->m_next && instr->m_next->m_opcode != Js::OpCode::StatementBoundary && !instr->m_next->IsLabelInstr())
  159. {
  160. instr->m_next->globOptInstrString = globOptInstrString;
  161. }
  162. globOptInstrString = instr->DumpString();
  163. }
  164. #endif
  165. IR::Opnd *src1;
  166. IR::RegOpnd *srcReg1;
  167. IR::RegOpnd *srcReg2;
  168. if (instr->IsBranchInstr() && !instr->AsBranchInstr()->IsMultiBranch() && instr->AsBranchInstr()->GetTarget()->m_isLoopTop)
  169. {
  170. Loop * loop = instr->AsBranchInstr()->GetTarget()->GetLoop();
  171. if (this->outerMostLoopLabel == nullptr && !loop->isProcessed)
  172. {
  173. while (loop && loop->GetLoopTopInstr()) // some loops are optimized away so that they are not loops anymore.
  174. // They do, however, stay in the loop graph but don't have loop top labels assigned to them
  175. {
  176. this->outerMostLoopLabel = loop->GetLoopTopInstr();
  177. Assert(this->outerMostLoopLabel->m_isLoopTop);
  178. // landing pad must fall through to the loop
  179. Assert(this->outerMostLoopLabel->m_prev->HasFallThrough());
  180. loop = loop->parent;
  181. }
  182. this->initializedTempSym->ClearAll();
  183. }
  184. noFieldFastPath = !defaultDoLoopFastPath;
  185. noMathFastPath = !defaultDoLoopFastPath;
  186. }
  187. #ifdef INLINE_CACHE_STATS
  188. if(PHASE_STATS1(Js::PolymorphicInlineCachePhase))
  189. {
  190. // Always use the slow path, so we can track property accesses
  191. noFieldFastPath = true;
  192. }
  193. #endif
  194. switch(instr->m_opcode)
  195. {
  196. case Js::OpCode::LdHandlerScope:
  197. this->LowerUnaryHelperMem(instr, IR::HelperScrObj_LdHandlerScope);
  198. break;
  199. case Js::OpCode::InitSetFld:
  200. instrPrev = this->LowerStFld(instr, IR::HelperOP_InitSetter, IR::HelperOP_InitSetter, false);
  201. break;
  202. case Js::OpCode::InitGetFld:
  203. instrPrev = this->LowerStFld(instr, IR::HelperOP_InitGetter, IR::HelperOP_InitGetter, false);
  204. break;
  205. case Js::OpCode::InitProto:
  206. instrPrev = this->LowerStFld(instr, IR::HelperOP_InitProto, IR::HelperOP_InitProto, false);
  207. break;
  208. case Js::OpCode::LdArgCnt:
  209. this->LoadArgumentCount(instr);
  210. break;
  211. case Js::OpCode::LdStackArgPtr:
  212. this->LoadStackArgPtr(instr);
  213. break;
  214. case Js::OpCode::LdHeapArguments:
  215. case Js::OpCode::LdLetHeapArguments:
  216. instrPrev = m_lowererMD.LoadHeapArguments(instr);
  217. break;
  218. case Js::OpCode::LdArgumentsFromStack:
  219. instrPrev = this->LoadArgumentsFromStack(instr);
  220. break;
  221. case Js::OpCode::LdHeapArgsCached:
  222. case Js::OpCode::LdLetHeapArgsCached:
  223. m_lowererMD.LoadHeapArgsCached(instr);
  224. break;
  225. case Js::OpCode::InvalCachedScope:
  226. this->LowerBinaryHelper(instr, IR::HelperOP_InvalidateCachedScope);
  227. break;
  228. case Js::OpCode::NewScopeObject:
  229. m_lowererMD.ChangeToHelperCallMem(instr, IR::HelperOP_NewScopeObject);
  230. break;
  231. case Js::OpCode::NewStackScopeSlots:
  232. this->LowerNewScopeSlots(instr, m_func->DoStackScopeSlots());
  233. break;
  234. case Js::OpCode::NewScopeSlots:
  235. this->LowerNewScopeSlots(instr, false);
  236. break;
  237. case Js::OpCode::InitLocalClosure:
  238. // Real initialization of the stack pointers happens on entry to the function, so this instruction
  239. // (which exists to provide a def in the IR) can go away.
  240. instr->Remove();
  241. break;
  242. case Js::OpCode::NewScopeSlotsWithoutPropIds:
  243. this->LowerBinaryHelperMemWithFuncBody(instr, IR::HelperOP_NewScopeSlotsWithoutPropIds);
  244. break;
  245. case Js::OpCode::NewBlockScope:
  246. m_lowererMD.ChangeToHelperCallMem(instr, IR::HelperOP_NewBlockScope);
  247. break;
  248. case Js::OpCode::NewPseudoScope:
  249. m_lowererMD.ChangeToHelperCallMem(instr, IR::HelperOP_NewPseudoScope);
  250. break;
  251. case Js::OpCode::CloneInnerScopeSlots:
  252. this->LowerUnaryHelperMem(instr, IR::HelperOP_CloneInnerScopeSlots);
  253. break;
  254. case Js::OpCode::CloneBlockScope:
  255. this->LowerUnaryHelperMem(instr, IR::HelperOP_CloneBlockScope);
  256. break;
  257. case Js::OpCode::GetCachedFunc:
  258. m_lowererMD.LowerGetCachedFunc(instr);
  259. break;
  260. case Js::OpCode::BrFncCachedScopeEq:
  261. case Js::OpCode::BrFncCachedScopeNeq:
  262. this->LowerBrFncCachedScopeEq(instr);
  263. break;
  264. case Js::OpCode::CommitScope:
  265. m_lowererMD.LowerCommitScope(instr);
  266. break;
  267. case Js::OpCode::LdFldForTypeOf:
  268. instrPrev = GenerateCompleteLdFld<false>(instr, !noFieldFastPath, IR::HelperOp_PatchGetValueForTypeOf, IR::HelperOp_PatchGetValuePolymorphicForTypeOf,
  269. IR::HelperOp_PatchGetValueForTypeOf, IR::HelperOp_PatchGetValuePolymorphicForTypeOf);
  270. break;
  271. case Js::OpCode::LdFld:
  272. case Js::OpCode::LdFldForCallApplyTarget:
  273. instrPrev = GenerateCompleteLdFld<false>(instr, !noFieldFastPath, IR::HelperOp_PatchGetValue, IR::HelperOp_PatchGetValuePolymorphic,
  274. IR::HelperOp_PatchGetValue, IR::HelperOp_PatchGetValuePolymorphic);
  275. break;
  276. case Js::OpCode::LdSuperFld:
  277. instrPrev = GenerateCompleteLdFld<false>(instr, !noFieldFastPath, IR::HelperOp_PatchGetValueWithThisPtr, IR::HelperOp_PatchGetValuePolymorphicWithThisPtr,
  278. IR::HelperOp_PatchGetValueWithThisPtr, IR::HelperOp_PatchGetValuePolymorphicWithThisPtr);
  279. break;
  280. case Js::OpCode::LdRootFld:
  281. instrPrev = GenerateCompleteLdFld<true>(instr, !noFieldFastPath, IR::HelperOp_PatchGetRootValue, IR::HelperOp_PatchGetRootValuePolymorphic,
  282. IR::HelperOp_PatchGetRootValue, IR::HelperOp_PatchGetRootValuePolymorphic);
  283. break;
  284. case Js::OpCode::LdRootFldForTypeOf:
  285. instrPrev = GenerateCompleteLdFld<true>(instr, !noFieldFastPath, IR::HelperOp_PatchGetRootValueForTypeOf, IR::HelperOp_PatchGetRootValuePolymorphicForTypeOf,
  286. IR::HelperOp_PatchGetRootValueForTypeOf, IR::HelperOp_PatchGetRootValuePolymorphicForTypeOf);
  287. break;
  288. case Js::OpCode::LdMethodFldPolyInlineMiss:
  289. instrPrev = LowerLdFld(instr, IR::HelperOp_PatchGetMethod, IR::HelperOp_PatchGetMethodPolymorphic, true, nullptr, true);
  290. break;
  291. case Js::OpCode::LdMethodFld:
  292. instrPrev = GenerateCompleteLdFld<false>(instr, !noFieldFastPath, IR::HelperOp_PatchGetMethod, IR::HelperOp_PatchGetMethodPolymorphic,
  293. IR::HelperOp_PatchGetMethod, IR::HelperOp_PatchGetMethodPolymorphic);
  294. break;
  295. case Js::OpCode::LdRootMethodFld:
  296. instrPrev = GenerateCompleteLdFld<true>(instr, !noFieldFastPath, IR::HelperOp_PatchGetRootMethod, IR::HelperOp_PatchGetRootMethodPolymorphic,
  297. IR::HelperOp_PatchGetRootMethod, IR::HelperOp_PatchGetRootMethodPolymorphic);
  298. break;
  299. case Js::OpCode::ScopedLdMethodFld:
  300. // "Scoped" in ScopedLdMethodFld is a bit of a misnomer because it doesn't look through a scope chain.
  301. // Instead the op is to allow for either a LdRootMethodFld or LdMethodFld depending on whether the
  302. // object is the root object or not.
  303. instrPrev = GenerateCompleteLdFld<false>(instr, !noFieldFastPath, IR::HelperOp_ScopedGetMethod, IR::HelperOp_ScopedGetMethodPolymorphic,
  304. IR::HelperOp_ScopedGetMethod, IR::HelperOp_ScopedGetMethodPolymorphic);
  305. break;
  306. case Js::OpCode::LdMethodFromFlags:
  307. {
  308. Assert(instr->HasBailOutInfo());
  309. bool success = m_lowererMD.GenerateFastLdMethodFromFlags(instr);
  310. AssertMsg(success, "Not expected to generate helper block here");
  311. break;
  312. }
  313. case Js::OpCode::CheckFixedFld:
  314. AssertMsg(!PHASE_OFF(Js::FixedMethodsPhase, instr->m_func->GetJnFunction()) || !PHASE_OFF(Js::UseFixedDataPropsPhase, instr->m_func->GetJnFunction()), "CheckFixedFld with fixed prop(Data|Method) phase disabled?");
  315. this->GenerateCheckFixedFld(instr);
  316. break;
  317. case Js::OpCode::CheckPropertyGuardAndLoadType:
  318. instrPrev = this->GeneratePropertyGuardCheckBailoutAndLoadType(instr);
  319. break;
  320. case Js::OpCode::CheckObjType:
  321. this->GenerateCheckObjType(instr);
  322. break;
  323. case Js::OpCode::AdjustObjType:
  324. this->LowerAdjustObjType(instr);
  325. break;
  326. case Js::OpCode::DeleteFld:
  327. instrPrev = this->LowerDelFld(instr, IR::HelperOp_DeleteProperty, false, false);
  328. break;
  329. case Js::OpCode::DeleteRootFld:
  330. instrPrev = this->LowerDelFld(instr, IR::HelperOp_DeleteRootProperty, false, false);
  331. break;
  332. case Js::OpCode::DeleteFldStrict:
  333. instrPrev = this->LowerDelFld(instr, IR::HelperOp_DeleteProperty, false, true);
  334. break;
  335. case Js::OpCode::DeleteRootFldStrict:
  336. instrPrev = this->LowerDelFld(instr, IR::HelperOp_DeleteRootProperty, false, true);
  337. break;
  338. case Js::OpCode::ScopedLdFldForTypeOf:
  339. if (!noFieldFastPath)
  340. {
  341. m_lowererMD.GenerateFastScopedLdFld(instr);
  342. }
  343. instrPrev = this->LowerScopedLdFld(instr, IR::HelperOp_PatchGetPropertyForTypeOfScoped, true);
  344. break;
  345. case Js::OpCode::ScopedLdFld:
  346. if (!noFieldFastPath)
  347. {
  348. m_lowererMD.GenerateFastScopedLdFld(instr);
  349. }
  350. instrPrev = this->LowerScopedLdFld(instr, IR::HelperOp_PatchGetPropertyScoped, true);
  351. break;
  352. case Js::OpCode::ScopedLdInst:
  353. instrPrev = this->LowerScopedLdInst(instr, IR::HelperOp_GetInstanceScoped);
  354. break;
  355. case Js::OpCode::ScopedDeleteFld:
  356. instrPrev = this->LowerScopedDelFld(instr, IR::HelperOp_DeletePropertyScoped, false, false);
  357. break;
  358. case Js::OpCode::ScopedDeleteFldStrict:
  359. instrPrev = this->LowerScopedDelFld(instr, IR::HelperOp_DeletePropertyScoped, false, true);
  360. break;
  361. case Js::OpCode::NewScFunc:
  362. instrPrev = this->LowerNewScFunc(instr);
  363. break;
  364. case Js::OpCode::NewScGenFunc:
  365. instrPrev = this->LowerNewScGenFunc(instr);
  366. break;
  367. case Js::OpCode::StFld:
  368. instrPrev = GenerateCompleteStFld(instr, !noFieldFastPath, IR::HelperOp_PatchPutValueNoLocalFastPath, IR::HelperOp_PatchPutValueNoLocalFastPathPolymorphic,
  369. IR::HelperOp_PatchPutValue, IR::HelperOp_PatchPutValuePolymorphic, true, Js::PropertyOperation_None);
  370. break;
  371. case Js::OpCode::StSuperFld:
  372. instrPrev = GenerateCompleteStFld(instr, !noFieldFastPath, IR::HelperOp_PatchPutValueWithThisPtrNoLocalFastPath, IR::HelperOp_PatchPutValueWithThisPtrNoLocalFastPathPolymorphic,
  373. IR::HelperOp_PatchPutValueWithThisPtr, IR::HelperOp_PatchPutValueWithThisPtrPolymorphic, true, Js::PropertyOperation_None);
  374. break;
  375. case Js::OpCode::StRootFld:
  376. instrPrev = GenerateCompleteStFld(instr, !noFieldFastPath, IR::HelperOp_PatchPutRootValueNoLocalFastPath, IR::HelperOp_PatchPutRootValueNoLocalFastPathPolymorphic,
  377. IR::HelperOp_PatchPutRootValue, IR::HelperOp_PatchPutRootValuePolymorphic, true, Js::PropertyOperation_Root);
  378. break;
  379. case Js::OpCode::StFldStrict:
  380. instrPrev = GenerateCompleteStFld(instr, !noFieldFastPath, IR::HelperOp_PatchPutValueNoLocalFastPath, IR::HelperOp_PatchPutValueNoLocalFastPathPolymorphic,
  381. IR::HelperOp_PatchPutValue, IR::HelperOp_PatchPutValuePolymorphic, true, Js::PropertyOperation_StrictMode);
  382. break;
  383. case Js::OpCode::StRootFldStrict:
  384. instrPrev = GenerateCompleteStFld(instr, !noFieldFastPath, IR::HelperOp_PatchPutRootValueNoLocalFastPath, IR::HelperOp_PatchPutRootValueNoLocalFastPathPolymorphic,
  385. IR::HelperOp_PatchPutRootValue, IR::HelperOp_PatchPutRootValuePolymorphic, true, Js::PropertyOperation_StrictModeRoot);
  386. break;
  387. case Js::OpCode::InitFld:
  388. case Js::OpCode::InitRootFld:
  389. instrPrev = GenerateCompleteStFld(instr, !noFieldFastPath, IR::HelperOp_PatchInitValue, IR::HelperOp_PatchInitValuePolymorphic,
  390. IR::HelperOp_PatchInitValue, IR::HelperOp_PatchInitValuePolymorphic, false, Js::PropertyOperation_None);
  391. break;
  392. case Js::OpCode::ScopedInitFunc:
  393. instrPrev = this->LowerScopedStFld(instr, IR::HelperOp_InitFuncScoped, false);
  394. break;
  395. case Js::OpCode::ScopedStFld:
  396. case Js::OpCode::ScopedStFldStrict:
  397. if (!noFieldFastPath)
  398. {
  399. m_lowererMD.GenerateFastScopedStFld(instr);
  400. }
  401. instrPrev = this->LowerScopedStFld(instr, IR::HelperOp_PatchSetPropertyScoped, true, true,
  402. instr->m_opcode == Js::OpCode::ScopedStFld ? Js::PropertyOperation_None : Js::PropertyOperation_StrictMode);
  403. break;
  404. case Js::OpCode::ConsoleScopedStFld:
  405. {
  406. if (!noFieldFastPath)
  407. {
  408. m_lowererMD.GenerateFastScopedStFld(instr);
  409. }
  410. Js::PropertyOperationFlags flags = static_cast<Js::PropertyOperationFlags>(Js::PropertyOperation_None | Js::PropertyOperation_AllowUndeclInConsoleScope);
  411. instrPrev = this->LowerScopedStFld(instr, IR::HelperOp_ConsolePatchSetPropertyScoped, true, true, flags);
  412. break;
  413. }
  414. case Js::OpCode::LdStr:
  415. m_lowererMD.ChangeToAssign(instr);
  416. break;
  417. case Js::OpCode::CloneStr:
  418. {
  419. GenerateGetImmutableOrScriptUnreferencedString(instr->GetSrc1()->AsRegOpnd(), instr, IR::HelperOp_CompoundStringCloneForAppending, false);
  420. instr->Remove();
  421. break;
  422. }
  423. case Js::OpCode::NewScObjArray:
  424. instrPrev = this->LowerNewScObjArray(instr);
  425. break;
  426. case Js::OpCode::NewScObject:
  427. case Js::OpCode::NewScObjectSpread:
  428. case Js::OpCode::NewScObjArraySpread:
  429. instrPrev = this->LowerNewScObject(instr, true, true);
  430. break;
  431. case Js::OpCode::NewScObjectNoCtor:
  432. instrPrev = this->LowerNewScObject(instr, false, true);
  433. break;
  434. case Js::OpCode::NewScObjectNoCtorFull:
  435. instrPrev = this->LowerNewScObject(instr, false, true, true);
  436. break;
  437. case Js::OpCode::GetNewScObject:
  438. instrPrev = this->LowerGetNewScObject(instr);
  439. break;
  440. case Js::OpCode::UpdateNewScObjectCache:
  441. instrPrev = instr->m_prev;
  442. this->LowerUpdateNewScObjectCache(instr, instr->GetSrc2(), instr->GetSrc1(), true /* isCtorFunction */);
  443. instr->Remove();
  444. break;
  445. case Js::OpCode::NewScObjectSimple:
  446. this->LowerNewScObjectSimple(instr);
  447. break;
  448. case Js::OpCode::NewScObjectLiteral:
  449. this->LowerNewScObjectLiteral(instr);
  450. break;
  451. case Js::OpCode::LdPropIds:
  452. m_lowererMD.ChangeToAssign(instr);
  453. break;
  454. case Js::OpCode::StArrSegItem_A:
  455. instrPrev = this->LowerArraySegmentVars(instr);
  456. break;
  457. case Js::OpCode::InlineMathAcos:
  458. m_lowererMD.GenerateFastInlineBuiltInCall(instr, IR::HelperDirectMath_Acos);
  459. break;
  460. case Js::OpCode::InlineMathAsin:
  461. m_lowererMD.GenerateFastInlineBuiltInCall(instr, IR::HelperDirectMath_Asin);
  462. break;
  463. case Js::OpCode::InlineMathAtan:
  464. m_lowererMD.GenerateFastInlineBuiltInCall(instr, IR::HelperDirectMath_Atan);
  465. break;
  466. case Js::OpCode::InlineMathAtan2:
  467. m_lowererMD.GenerateFastInlineBuiltInCall(instr, IR::HelperDirectMath_Atan2);
  468. break;
  469. case Js::OpCode::InlineMathCos:
  470. m_lowererMD.GenerateFastInlineBuiltInCall(instr, IR::HelperDirectMath_Cos);
  471. break;
  472. case Js::OpCode::InlineMathExp:
  473. m_lowererMD.GenerateFastInlineBuiltInCall(instr, IR::HelperDirectMath_Exp);
  474. break;
  475. case Js::OpCode::InlineMathLog:
  476. m_lowererMD.GenerateFastInlineBuiltInCall(instr, IR::HelperDirectMath_Log);
  477. break;
  478. case Js::OpCode::InlineMathPow:
  479. m_lowererMD.GenerateFastInlineBuiltInCall(instr, IR::HelperDirectMath_Pow);
  480. break;
  481. case Js::OpCode::InlineMathSin:
  482. m_lowererMD.GenerateFastInlineBuiltInCall(instr, IR::HelperDirectMath_Sin);
  483. break;
  484. case Js::OpCode::InlineMathSqrt:
  485. m_lowererMD.GenerateFastInlineBuiltInCall(instr, (IR::JnHelperMethod)0);
  486. break;
  487. case Js::OpCode::InlineMathTan:
  488. m_lowererMD.GenerateFastInlineBuiltInCall(instr, IR::HelperDirectMath_Tan);
  489. break;
  490. case Js::OpCode::InlineMathFloor:
  491. #if _M_X64
  492. if (!AutoSystemInfo::Data.SSE4_1Available() && instr->m_func->GetJnFunction()->GetIsAsmjsMode())
  493. {
  494. m_lowererMD.HelperCallForAsmMathBuiltin(instr, IR::HelperDirectMath_FloorFlt, IR::HelperDirectMath_FloorDb);
  495. break;
  496. }
  497. #endif
  498. m_lowererMD.GenerateFastInlineBuiltInCall(instr, (IR::JnHelperMethod)0);
  499. break;
  500. case Js::OpCode::InlineMathCeil:
  501. #if _M_X64
  502. if (!AutoSystemInfo::Data.SSE4_1Available() && instr->m_func->GetJnFunction()->GetIsAsmjsMode())
  503. {
  504. m_lowererMD.HelperCallForAsmMathBuiltin(instr, IR::HelperDirectMath_CeilFlt, IR::HelperDirectMath_CeilDb);
  505. break;
  506. }
  507. #endif
  508. m_lowererMD.GenerateFastInlineBuiltInCall(instr, (IR::JnHelperMethod)0);
  509. break;
  510. case Js::OpCode::InlineMathRound:
  511. m_lowererMD.GenerateFastInlineBuiltInCall(instr, (IR::JnHelperMethod)0);
  512. break;
  513. case Js::OpCode::InlineMathAbs:
  514. m_lowererMD.GenerateFastInlineBuiltInCall(instr, (IR::JnHelperMethod)0);
  515. break;
  516. case Js::OpCode::InlineMathImul:
  517. GenerateFastInlineMathImul(instr);
  518. break;
  519. case Js::OpCode::InlineMathClz32:
  520. GenerateFastInlineMathClz32(instr);
  521. break;
  522. case Js::OpCode::InlineMathFround:
  523. GenerateFastInlineMathFround(instr);
  524. break;
  525. case Js::OpCode::InlineMathMin:
  526. case Js::OpCode::InlineMathMax:
  527. m_lowererMD.GenerateFastInlineBuiltInCall(instr, (IR::JnHelperMethod)0);
  528. break;
  529. case Js::OpCode::InlineMathRandom:
  530. this->GenerateFastInlineBuiltInMathRandom(instr);
  531. break;
  532. #ifdef ENABLE_DOM_FAST_PATH
  533. case Js::OpCode::DOMFastPathGetter:
  534. this->LowerFastInlineDOMFastPathGetter(instr);
  535. break;
  536. #endif
  537. case Js::OpCode::InlineArrayPush:
  538. this->GenerateFastInlineArrayPush(instr);
  539. break;
  540. case Js::OpCode::InlineArrayPop:
  541. this->GenerateFastInlineArrayPop(instr);
  542. break;
  543. //Now retrieve the function object from the ArgOut_A_InlineSpecialized instruction opcode to push it on the stack after all the other arguments have been pushed.
  544. //The lowering of the direct call to helper is handled by GenerateDirectCall (architecture specific).
  545. case Js::OpCode::CallDirect:
  546. {
  547. IR::Opnd * src1 = instr->GetSrc1();
  548. Assert(src1->IsHelperCallOpnd());
  549. switch (src1->AsHelperCallOpnd()->m_fnHelper)
  550. {
  551. case IR::JnHelperMethod::HelperString_Split:
  552. case IR::JnHelperMethod::HelperString_Match:
  553. GenerateFastInlineStringSplitMatch(instr);
  554. break;
  555. case IR::JnHelperMethod::HelperRegExp_Exec:
  556. GenerateFastInlineRegExpExec(instr);
  557. break;
  558. case IR::JnHelperMethod::HelperGlobalObject_ParseInt:
  559. GenerateFastInlineGlobalObjectParseInt(instr);
  560. break;
  561. case IR::JnHelperMethod::HelperString_FromCharCode:
  562. GenerateFastInlineStringFromCharCode(instr);
  563. break;
  564. case IR::JnHelperMethod::HelperString_FromCodePoint:
  565. GenerateFastInlineStringFromCodePoint(instr);
  566. break;
  567. case IR::JnHelperMethod::HelperString_CharAt:
  568. GenerateFastInlineStringCharCodeAt(instr, Js::BuiltinFunction::String_CharAt);
  569. break;
  570. case IR::JnHelperMethod::HelperString_CharCodeAt:
  571. GenerateFastInlineStringCharCodeAt(instr, Js::BuiltinFunction::String_CharCodeAt);
  572. break;
  573. case IR::JnHelperMethod::HelperString_Replace:
  574. GenerateFastInlineStringReplace(instr);
  575. break;
  576. }
  577. instrPrev = LowerCallDirect(instr);
  578. break;
  579. }
  580. case Js::OpCode::CallIDynamic:
  581. {
  582. Js::CallFlags flags = instr->GetDst() ? Js::CallFlags_Value : Js::CallFlags_NotUsed;
  583. instrPrev = this->LowerCallIDynamic(instr, (ushort)flags);
  584. break;
  585. }
  586. case Js::OpCode::CallIDynamicSpread:
  587. {
  588. Js::CallFlags flags = instr->GetDst() ? Js::CallFlags_Value : Js::CallFlags_NotUsed;
  589. instrPrev = this->LowerCallIDynamicSpread(instr, (ushort)flags);
  590. break;
  591. }
  592. case Js::OpCode::CallI:
  593. case Js::OpCode::CallINew:
  594. case Js::OpCode::CallIFixed:
  595. case Js::OpCode::CallINewTargetNew:
  596. {
  597. Js::CallFlags flags = Js::CallFlags_None;
  598. if (instr->isCtorCall)
  599. {
  600. flags = Js::CallFlags_New;
  601. }
  602. else
  603. {
  604. if (instr->m_opcode == Js::OpCode::CallINew)
  605. {
  606. flags = Js::CallFlags_New;
  607. }
  608. else if (instr->m_opcode == Js::OpCode::CallINewTargetNew)
  609. {
  610. flags = (Js::CallFlags) (Js::CallFlags_New | Js::CallFlags_ExtraArg | Js::CallFlags_NewTarget);
  611. }
  612. if (instr->GetDst())
  613. {
  614. flags = (Js::CallFlags) (flags | Js::CallFlags_Value);
  615. }
  616. else
  617. {
  618. flags = (Js::CallFlags) (flags | Js::CallFlags_NotUsed);
  619. }
  620. }
  621. if (!PHASE_OFF(Js::CallFastPathPhase, this->m_func) && !noMathFastPath)
  622. {
  623. // We shouldn't have turned this instruction into a fixed method call if we're calling one of the
  624. // built-ins we still inline in the lowerer.
  625. Assert(instr->m_opcode != Js::OpCode::CallIFixed || !Func::IsBuiltInInlinedInLowerer(instr->GetSrc1()));
  626. // Disable InlineBuiltInLibraryCall as it does not work well with 2nd chance reg alloc
  627. // and may invalidate live on back edge data by introducing refs across loops. See Winblue Bug: 577641
  628. //// Callee may still be a library built-in; if so, generate it inline.
  629. //if (this->InlineBuiltInLibraryCall(instr))
  630. //{
  631. // m_lowererMD.LowerCallI(instr, (ushort)flags, true /*isHelper*/);
  632. //}
  633. //else
  634. //{
  635. m_lowererMD.LowerCallI(instr, (ushort)flags);
  636. //}
  637. }
  638. else
  639. {
  640. m_lowererMD.LowerCallI(instr, (ushort)flags);
  641. }
  642. break;
  643. }
  644. case Js::OpCode::AsmJsCallI:
  645. m_lowererMD.LowerAsmJsCallI(instr);
  646. break;
  647. case Js::OpCode::AsmJsCallE:
  648. m_lowererMD.LowerAsmJsCallE(instr);
  649. break;
  650. case Js::OpCode::CallIEval:
  651. {
  652. Js::CallFlags flags = (Js::CallFlags)(Js::CallFlags_ExtraArg | (instr->GetDst() ? Js::CallFlags_Value : Js::CallFlags_NotUsed));
  653. if (IsSpreadCall(instr))
  654. {
  655. instrPrev = LowerSpreadCall(instr, flags);
  656. }
  657. else
  658. {
  659. m_lowererMD.LowerCallI(instr, (ushort)flags);
  660. }
  661. #ifdef PERF_HINT
  662. if (PHASE_TRACE1(Js::PerfHintPhase))
  663. {
  664. WritePerfHint(PerfHints::CallsEval, this->m_func->GetJnFunction(), instr->GetByteCodeOffset());
  665. }
  666. #endif
  667. break;
  668. }
  669. case Js::OpCode::CallIPut:
  670. m_lowererMD.LowerCallPut(instr);
  671. break;
  672. case Js::OpCode::CallHelper:
  673. instrPrev = m_lowererMD.LowerCallHelper(instr);
  674. break;
  675. case Js::OpCode::Ret:
  676. if (instr->m_next->m_opcode != Js::OpCode::FunctionExit)
  677. {
  678. // If this RET isn't at the end of the function, insert a branch to
  679. // the epilog.
  680. IR::Instr *exitPrev = m_func->m_exitInstr->m_prev;
  681. if (!exitPrev->IsLabelInstr())
  682. {
  683. exitPrev = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  684. m_func->m_exitInstr->InsertBefore(exitPrev);
  685. }
  686. IR::BranchInstr *exitBr = IR::BranchInstr::New(Js::OpCode::Br,
  687. exitPrev->AsLabelInstr(), m_func);
  688. instr->InsertAfter(exitBr);
  689. m_lowererMD.LowerUncondBranch(exitBr);
  690. }
  691. m_lowererMD.LowerRet(instr);
  692. break;
  693. case Js::OpCode::LdArgumentsFromFrame:
  694. this->LoadArgumentsFromFrame(instr);
  695. break;
  696. case Js::OpCode::LdC_A_I4:
  697. src1 = instr->UnlinkSrc1();
  698. AssertMsg(src1->IsIntConstOpnd(), "Source of LdC_A_I4 should be an IntConst...");
  699. instrPrev = this->LowerLoadVar(instr,
  700. IR::AddrOpnd::NewFromNumber(static_cast<int32>(src1->AsIntConstOpnd()->GetValue()), this->m_func));
  701. src1->Free(this->m_func);
  702. break;
  703. case Js::OpCode::LdC_A_R8:
  704. src1 = instr->UnlinkSrc1();
  705. AssertMsg(src1->IsFloatConstOpnd(), "Source of LdC_A_R8 should be a FloatConst...");
  706. instrPrev = this->LowerLoadVar(instr, src1->AsFloatConstOpnd()->GetAddrOpnd(this->m_func));
  707. src1->Free(this->m_func);
  708. break;
  709. case Js::OpCode::LdC_F8_R8:
  710. src1 = instr->UnlinkSrc1();
  711. AssertMsg(src1->IsFloatConstOpnd(), "Source of LdC_F8_R8 should be a FloatConst...");
  712. instrPrev = m_lowererMD.LoadFloatValue(instr->UnlinkDst()->AsRegOpnd(), src1->AsFloatConstOpnd()->m_value, instr);
  713. src1->Free(this->m_func);
  714. instr->Remove();
  715. break;
  716. case Js::OpCode::NewRegEx:
  717. instrPrev = this->LowerNewRegEx(instr);
  718. break;
  719. case Js::OpCode::Conv_Obj:
  720. this->LowerUnaryHelperMem(instr, IR::HelperOp_ConvObject);
  721. break;
  722. case Js::OpCode::NewWithObject:
  723. this->LowerUnaryHelperMem(instr, IR::HelperOp_NewWithObject);
  724. break;
  725. case Js::OpCode::LdCustomSpreadIteratorList:
  726. this->LowerUnaryHelperMem(instr, IR::HelperOp_ToSpreadedFunctionArgument);
  727. break;
  728. case Js::OpCode::Conv_Num:
  729. this->LowerConvNum(instr, noMathFastPath);
  730. break;
  731. case Js::OpCode::Incr_A:
  732. if (PHASE_OFF(Js::MathFastPathPhase, this->m_func) || noMathFastPath)
  733. {
  734. this->LowerUnaryHelperMem(instr, IR::HelperOp_Increment);
  735. }
  736. else
  737. {
  738. instr->SetSrc2(IR::AddrOpnd::New(Js::TaggedInt::ToVarUnchecked(1), IR::AddrOpndKindConstantVar, this->m_func));
  739. m_lowererMD.GenerateFastAdd(instr);
  740. instr->FreeSrc2();
  741. this->LowerUnaryHelperMemWithTemp2(instr, IR_HELPER_OP_FULL_OR_INPLACE(Increment));
  742. }
  743. break;
  744. case Js::OpCode::Decr_A:
  745. if (PHASE_OFF(Js::MathFastPathPhase, this->m_func) || noMathFastPath)
  746. {
  747. this->LowerUnaryHelperMem(instr, IR::HelperOp_Decrement);
  748. }
  749. else
  750. {
  751. instr->SetSrc2(IR::AddrOpnd::New(Js::TaggedInt::ToVarUnchecked(1), IR::AddrOpndKindConstantVar, this->m_func));
  752. m_lowererMD.GenerateFastSub(instr);
  753. instr->FreeSrc2();
  754. this->LowerUnaryHelperMemWithTemp2(instr, IR_HELPER_OP_FULL_OR_INPLACE(Decrement));
  755. }
  756. break;
  757. case Js::OpCode::Neg_A:
  758. if (instr->GetDst()->IsFloat())
  759. {
  760. Assert(instr->GetSrc1()->IsFloat());
  761. m_lowererMD.LowerToFloat(instr);
  762. }
  763. else if (PHASE_OFF(Js::MathFastPathPhase, this->m_func) || noMathFastPath)
  764. {
  765. this->LowerUnaryHelperMem(instr, IR::HelperOp_Negate);
  766. }
  767. else if (m_lowererMD.GenerateFastNeg(instr))
  768. {
  769. this->LowerUnaryHelperMemWithTemp2(instr, IR_HELPER_OP_FULL_OR_INPLACE(Negate));
  770. }
  771. break;
  772. case Js::OpCode::Not_A:
  773. if (PHASE_OFF(Js::BitopsFastPathPhase, this->m_func) || noMathFastPath)
  774. {
  775. this->LowerUnaryHelperMem(instr, IR::HelperOp_Not);
  776. }
  777. else if (m_lowererMD.GenerateFastNot(instr))
  778. {
  779. this->LowerUnaryHelperMemWithTemp2(instr, IR_HELPER_OP_FULL_OR_INPLACE(Not));
  780. }
  781. break;
  782. case Js::OpCode::BrEq_I4:
  783. case Js::OpCode::BrNeq_I4:
  784. case Js::OpCode::BrGt_I4:
  785. case Js::OpCode::BrGe_I4:
  786. case Js::OpCode::BrLt_I4:
  787. case Js::OpCode::BrLe_I4:
  788. case Js::OpCode::BrUnGt_I4:
  789. case Js::OpCode::BrUnGe_I4:
  790. case Js::OpCode::BrUnLt_I4:
  791. case Js::OpCode::BrUnLe_I4:
  792. {
  793. // See calls to MarkOneFltTmpSym under BrSrEq. This is to handle the case
  794. // where a branch is type-specialized and uses the result of a float pref op,
  795. // which must then be saved to var at the def.
  796. StackSym *sym = instr->GetSrc1()->GetStackSym();
  797. if (sym)
  798. {
  799. sym = sym->GetVarEquivSym(nullptr);
  800. }
  801. sym = instr->GetSrc2()->GetStackSym();
  802. if (sym)
  803. {
  804. sym = sym->GetVarEquivSym(nullptr);
  805. }
  806. }
  807. // FALLTHROUGH
  808. case Js::OpCode::Neg_I4:
  809. case Js::OpCode::Not_I4:
  810. case Js::OpCode::Add_I4:
  811. case Js::OpCode::Sub_I4:
  812. case Js::OpCode::Mul_I4:
  813. case Js::OpCode::Rem_I4:
  814. case Js::OpCode::Or_I4:
  815. case Js::OpCode::Xor_I4:
  816. case Js::OpCode::And_I4:
  817. case Js::OpCode::Shl_I4:
  818. case Js::OpCode::Shr_I4:
  819. case Js::OpCode::ShrU_I4:
  820. case Js::OpCode::BrTrue_I4:
  821. case Js::OpCode::BrFalse_I4:
  822. if(instr->HasBailOutInfo())
  823. {
  824. const auto bailOutKind = instr->GetBailOutKind();
  825. if(bailOutKind & IR::BailOutOnResultConditions ||
  826. bailOutKind == IR::BailOutOnFailedHoistedLoopCountBasedBoundCheck)
  827. {
  828. const auto nonBailOutInstr = SplitBailOnResultCondition(instr);
  829. IR::LabelInstr *bailOutLabel, *skipBailOutLabel;
  830. LowerBailOnResultCondition(instr, &bailOutLabel, &skipBailOutLabel);
  831. LowerInstrWithBailOnResultCondition(nonBailOutInstr, bailOutKind, bailOutLabel, skipBailOutLabel);
  832. }
  833. else if(bailOutKind == IR::BailOnModByPowerOf2)
  834. {
  835. Assert(instr->m_opcode == Js::OpCode::Rem_I4);
  836. bool fastPath = GenerateSimplifiedInt4Rem(instr);
  837. Assert(fastPath);
  838. instr->FreeSrc1();
  839. instr->FreeSrc2();
  840. this->GenerateBailOut(instr);
  841. }
  842. }
  843. else
  844. {
  845. if (instr->m_opcode == Js::OpCode::Rem_I4)
  846. {
  847. // fast path
  848. this->GenerateSimplifiedInt4Rem(instr);
  849. // slow path
  850. this->LowerRemI4(instr);
  851. }
  852. #if defined(_M_IX86) || defined(_M_X64)
  853. else if (instr->m_opcode == Js::OpCode::Mul_I4)
  854. {
  855. if (!LowererMD::GenerateSimplifiedInt4Mul(instr))
  856. {
  857. m_lowererMD.EmitInt4Instr(instr);
  858. }
  859. }
  860. #endif
  861. else
  862. {
  863. m_lowererMD.EmitInt4Instr(instr);
  864. }
  865. }
  866. break;
  867. case Js::OpCode::Div_I4:
  868. this->LowerDivI4(instr);
  869. break;
  870. case Js::OpCode::Add_Ptr:
  871. m_lowererMD.EmitPtrInstr(instr);
  872. break;
  873. case Js::OpCode::Typeof:
  874. this->LowerUnaryHelperMem(instr, IR::HelperOp_Typeof);
  875. break;
  876. case Js::OpCode::TypeofElem:
  877. this->LowerLdElemI(instr, IR::HelperOp_TypeofElem, false);
  878. break;
  879. case Js::OpCode::LdLen_A:
  880. {
  881. bool fastPath = !noMathFastPath;
  882. if(!fastPath && instr->HasBailOutInfo())
  883. {
  884. // Some bailouts are generated around the helper call, and will work even if the fast path is disabled. Other
  885. // bailouts require the fast path.
  886. const IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  887. if(bailOutKind & IR::BailOutKindBits)
  888. {
  889. fastPath = true;
  890. }
  891. else
  892. {
  893. const IR::BailOutKind bailOutKindMinusBits = bailOutKind & ~IR::BailOutKindBits;
  894. fastPath =
  895. bailOutKindMinusBits &&
  896. bailOutKindMinusBits != IR::BailOutOnImplicitCalls &&
  897. bailOutKindMinusBits != IR::BailOutOnImplicitCallsPreOp;
  898. }
  899. }
  900. bool instrIsInHelperBlock;
  901. if(!fastPath)
  902. {
  903. LowerLdLen(instr, false);
  904. }
  905. else if(GenerateFastLdLen(instr, &instrIsInHelperBlock))
  906. {
  907. Assert(
  908. !instr->HasBailOutInfo() ||
  909. (instr->GetBailOutKind() & ~IR::BailOutKindBits) != IR::BailOutOnIrregularLength);
  910. LowerLdLen(instr, instrIsInHelperBlock);
  911. }
  912. break;
  913. }
  914. case Js::OpCode::LdThis:
  915. {
  916. if (noFieldFastPath || !m_lowererMD.GenerateLdThisCheck(instr))
  917. {
  918. IR::JnHelperMethod meth;
  919. if (instr->IsJitProfilingInstr())
  920. {
  921. Assert(instr->AsJitProfilingInstr()->profileId == Js::Constants::NoProfileId);
  922. m_lowererMD.LoadHelperArgument(instr, CreateFunctionBodyOpnd(instr->m_func));
  923. meth = IR::HelperSimpleProfiledLdThis;
  924. this->LowerBinaryHelper(instr, meth);
  925. }
  926. else
  927. {
  928. meth = IR::HelperLdThisNoFastPath;
  929. this->LowerBinaryHelperMem(instr, meth);
  930. }
  931. }
  932. else
  933. {
  934. this->LowerBinaryHelperMem(instr, IR::HelperLdThis);
  935. }
  936. break;
  937. }
  938. case Js::OpCode::StrictLdThis:
  939. if (noFieldFastPath)
  940. {
  941. IR::JnHelperMethod meth;
  942. if (instr->IsJitProfilingInstr())
  943. {
  944. Assert(instr->AsJitProfilingInstr()->profileId == Js::Constants::NoProfileId);
  945. m_lowererMD.LoadHelperArgument(instr, CreateFunctionBodyOpnd(instr->m_func));
  946. meth = IR::HelperSimpleProfiledStrictLdThis;
  947. this->LowerUnaryHelper(instr, meth);
  948. }
  949. else
  950. {
  951. meth = IR::HelperStrictLdThis;
  952. this->LowerUnaryHelperMem(instr, meth);
  953. }
  954. }
  955. else
  956. {
  957. m_lowererMD.GenerateLdThisStrict(instr);
  958. instr->Remove();
  959. }
  960. break;
  961. case Js::OpCode::CheckThis:
  962. m_lowererMD.GenerateLdThisCheck(instr);
  963. instr->FreeSrc1();
  964. this->GenerateBailOut(instr);
  965. break;
  966. case Js::OpCode::StrictCheckThis:
  967. m_lowererMD.GenerateLdThisStrict(instr);
  968. instr->FreeSrc1();
  969. this->GenerateBailOut(instr);
  970. break;
  971. case Js::OpCode::NewScArray:
  972. instrPrev = this->LowerNewScArray(instr);
  973. break;
  974. case Js::OpCode::NewScArrayWithMissingValues:
  975. this->LowerUnaryHelperMem(instr, IR::HelperScrArr_OP_NewScArrayWithMissingValues);
  976. break;
  977. case Js::OpCode::NewScIntArray:
  978. instrPrev = this->LowerNewScIntArray(instr);
  979. break;
  980. case Js::OpCode::NewScFltArray:
  981. instrPrev = this->LowerNewScFltArray(instr);
  982. break;
  983. case Js::OpCode::GetForInEnumerator:
  984. this->LowerUnaryHelperMem(instr, IR::HelperOp_OP_GetForInEnumerator);
  985. break;
  986. case Js::OpCode::ReleaseForInEnumerator:
  987. this->LowerUnaryHelperMem(instr, IR::HelperOp_OP_ReleaseForInEnumerator);
  988. break;
  989. case Js::OpCode::Add_A:
  990. if (instr->GetDst()->IsFloat())
  991. {
  992. Assert(instr->GetSrc1()->IsFloat());
  993. Assert(instr->GetSrc2()->IsFloat());
  994. // we don't want to mix float32 and float64
  995. Assert(instr->GetDst()->GetType() == instr->GetSrc1()->GetType());
  996. Assert(instr->GetDst()->GetType() == instr->GetSrc2()->GetType());
  997. m_lowererMD.LowerToFloat(instr);
  998. }
  999. else if (PHASE_OFF(Js::MathFastPathPhase, this->m_func) || noMathFastPath)
  1000. {
  1001. this->LowerBinaryHelperMem(instr, IR::HelperOp_Add);
  1002. }
  1003. else if (m_lowererMD.TryGenerateFastMulAdd(instr, &instrPrev))
  1004. {
  1005. }
  1006. else
  1007. {
  1008. m_lowererMD.GenerateFastAdd(instr);
  1009. this->LowerBinaryHelperMemWithTemp3(instr, IR_HELPER_OP_FULL_OR_INPLACE(Add), IR::HelperOp_AddLeftDead);
  1010. }
  1011. break;
  1012. case Js::OpCode::Div_A:
  1013. {
  1014. if (instr->IsJitProfilingInstr()) {
  1015. LowerProfiledBinaryOp(instr->AsJitProfilingInstr(), IR::HelperSimpleProfiledDivide);
  1016. }
  1017. else if (instr->GetDst()->IsFloat())
  1018. {
  1019. Assert(instr->GetSrc1()->IsFloat());
  1020. Assert(instr->GetSrc2()->IsFloat());
  1021. Assert(instr->GetDst()->GetType() == instr->GetSrc1()->GetType());
  1022. Assert(instr->GetDst()->GetType() == instr->GetSrc2()->GetType());
  1023. m_lowererMD.LowerToFloat(instr);
  1024. }
  1025. else
  1026. {
  1027. if (!PHASE_OFF(Js::MathFastPathPhase, this->m_func) && !noMathFastPath)
  1028. {
  1029. IR::AddrOpnd *src2 = instr->GetSrc2()->IsAddrOpnd() ? instr->GetSrc2()->AsAddrOpnd() : nullptr;
  1030. if (src2 && src2->IsVar() && Js::TaggedInt::Is(src2->m_address))
  1031. {
  1032. int32 value = Js::TaggedInt::ToInt32(src2->m_address);
  1033. if (Math::IsPow2(value))
  1034. {
  1035. m_lowererMD.GenerateFastDivByPow2(instr);
  1036. }
  1037. }
  1038. }
  1039. this->LowerBinaryHelperMemWithTemp2(instr, IR_HELPER_OP_FULL_OR_INPLACE(Divide));
  1040. }
  1041. break;
  1042. }
  1043. case Js::OpCode::Expo_A:
  1044. {
  1045. if (instr->GetDst()->IsFloat())
  1046. {
  1047. Assert(instr->GetSrc1()->IsFloat());
  1048. Assert(instr->GetSrc2()->IsFloat());
  1049. Assert(instr->GetDst()->GetType() == instr->GetSrc1()->GetType());
  1050. Assert(instr->GetDst()->GetType() == instr->GetSrc2()->GetType());
  1051. m_lowererMD.GenerateFastInlineBuiltInCall(instr, IR::HelperDirectMath_Pow);
  1052. }
  1053. else
  1054. {
  1055. this->LowerBinaryHelperMemWithTemp2(instr, IR_HELPER_OP_FULL_OR_INPLACE(Exponentiation));
  1056. }
  1057. break;
  1058. }
  1059. case Js::OpCode::Mul_A:
  1060. if (instr->GetDst()->IsFloat())
  1061. {
  1062. Assert(instr->GetSrc1()->IsFloat());
  1063. Assert(instr->GetSrc2()->IsFloat());
  1064. Assert(instr->GetDst()->GetType() == instr->GetSrc1()->GetType());
  1065. Assert(instr->GetDst()->GetType() == instr->GetSrc2()->GetType());
  1066. m_lowererMD.LowerToFloat(instr);
  1067. }
  1068. else if (PHASE_OFF(Js::MathFastPathPhase, this->m_func) || noMathFastPath)
  1069. {
  1070. this->LowerBinaryHelperMem(instr, IR::HelperOp_Multiply);
  1071. }
  1072. else if (m_lowererMD.GenerateFastMul(instr))
  1073. {
  1074. this->LowerBinaryHelperMemWithTemp2(instr, IR_HELPER_OP_FULL_OR_INPLACE(Multiply));
  1075. }
  1076. break;
  1077. case Js::OpCode::Rem_A:
  1078. if (instr->GetDst()->IsFloat64())
  1079. {
  1080. this->LowerRemR8(instr);
  1081. }
  1082. else if (instr->IsJitProfilingInstr())
  1083. {
  1084. this->LowerProfiledBinaryOp(instr->AsJitProfilingInstr(), IR::HelperSimpleProfiledRemainder);
  1085. }
  1086. else
  1087. {
  1088. this->LowerBinaryHelperMemWithTemp2(instr, IR_HELPER_OP_FULL_OR_INPLACE(Modulus));
  1089. }
  1090. break;
  1091. case Js::OpCode::Sub_A:
  1092. if (instr->GetDst()->IsFloat())
  1093. {
  1094. Assert(instr->GetSrc1()->IsFloat());
  1095. Assert(instr->GetSrc2()->IsFloat());
  1096. Assert(instr->GetDst()->GetType() == instr->GetSrc1()->GetType());
  1097. Assert(instr->GetDst()->GetType() == instr->GetSrc2()->GetType());
  1098. m_lowererMD.LowerToFloat(instr);
  1099. }
  1100. else if (PHASE_OFF(Js::MathFastPathPhase, this->m_func) || noMathFastPath)
  1101. {
  1102. this->LowerBinaryHelperMem(instr, IR::HelperOp_Subtract);
  1103. }
  1104. else if (m_lowererMD.TryGenerateFastMulAdd(instr, &instrPrev))
  1105. {
  1106. }
  1107. else
  1108. {
  1109. m_lowererMD.GenerateFastSub(instr);
  1110. this->LowerBinaryHelperMemWithTemp2(instr, IR_HELPER_OP_FULL_OR_INPLACE(Subtract));
  1111. }
  1112. break;
  1113. case Js::OpCode::And_A:
  1114. if (PHASE_OFF(Js::BitopsFastPathPhase, this->m_func) || noMathFastPath)
  1115. {
  1116. this->LowerBinaryHelperMem(instr, IR::HelperOp_And);
  1117. }
  1118. else if (m_lowererMD.GenerateFastAnd(instr))
  1119. {
  1120. this->LowerBinaryHelperMemWithTemp2(instr, IR_HELPER_OP_FULL_OR_INPLACE(And));
  1121. }
  1122. break;
  1123. case Js::OpCode::Or_A:
  1124. if (PHASE_OFF(Js::BitopsFastPathPhase, this->m_func) || noMathFastPath)
  1125. {
  1126. this->LowerBinaryHelperMem(instr, IR::HelperOp_Or);
  1127. }
  1128. else if (m_lowererMD.GenerateFastOr(instr))
  1129. {
  1130. this->LowerBinaryHelperMemWithTemp2(instr, IR_HELPER_OP_FULL_OR_INPLACE(Or));
  1131. }
  1132. break;
  1133. case Js::OpCode::Xor_A:
  1134. if (PHASE_OFF(Js::BitopsFastPathPhase, this->m_func) || noMathFastPath || m_lowererMD.GenerateFastXor(instr))
  1135. {
  1136. this->LowerBinaryHelperMemWithTemp2(instr, IR_HELPER_OP_FULL_OR_INPLACE(Xor));
  1137. }
  1138. break;
  1139. case Js::OpCode::Shl_A:
  1140. if (PHASE_OFF(Js::BitopsFastPathPhase, this->m_func) || noMathFastPath || m_lowererMD.GenerateFastShiftLeft(instr))
  1141. {
  1142. this->LowerBinaryHelperMem(instr, IR::HelperOp_ShiftLeft);
  1143. }
  1144. break;
  1145. case Js::OpCode::Shr_A:
  1146. if (PHASE_OFF(Js::BitopsFastPathPhase, this->m_func) || noMathFastPath || m_lowererMD.GenerateFastShiftRight(instr))
  1147. {
  1148. this->LowerBinaryHelperMem(instr, IR::HelperOp_ShiftRight);
  1149. }
  1150. break;
  1151. case Js::OpCode::ShrU_A:
  1152. if (PHASE_OFF(Js::BitopsFastPathPhase, this->m_func) || noMathFastPath || m_lowererMD.GenerateFastShiftRight(instr))
  1153. {
  1154. this->LowerBinaryHelperMem(instr, IR::HelperOp_ShiftRightU);
  1155. }
  1156. break;
  1157. case Js::OpCode::CmEq_A:
  1158. if (instr->GetSrc1()->IsFloat())
  1159. {
  1160. Assert(instr->GetSrc1()->GetType() == instr->GetSrc2()->GetType());
  1161. this->m_lowererMD.GenerateFastCmXxR8(instr);
  1162. }
  1163. else if (!PHASE_OFF(Js::BranchFastPathPhase, this->m_func) && !noMathFastPath && this->TryGenerateFastBrOrCmTypeOf(instr, &instrPrev, &fNoLower))
  1164. {
  1165. if (!fNoLower)
  1166. {
  1167. this->LowerBinaryHelperMem(instr, IR::HelperOP_CmEq_A);
  1168. }
  1169. }
  1170. else if (PHASE_OFF(Js::BranchFastPathPhase, this->m_func) || noMathFastPath || !m_lowererMD.GenerateFastCmXxTaggedInt(instr))
  1171. {
  1172. this->LowerBinaryHelperMem(instr, IR::HelperOP_CmEq_A);
  1173. }
  1174. break;
  1175. case Js::OpCode::CmNeq_A:
  1176. if (instr->GetSrc1()->IsFloat())
  1177. {
  1178. Assert(instr->GetSrc1()->GetType() == instr->GetSrc2()->GetType());
  1179. this->m_lowererMD.GenerateFastCmXxR8(instr);
  1180. }
  1181. else if (!PHASE_OFF(Js::BranchFastPathPhase, this->m_func) && !noMathFastPath && this->TryGenerateFastBrOrCmTypeOf(instr, &instrPrev, &fNoLower))
  1182. {
  1183. if (!fNoLower)
  1184. {
  1185. this->LowerBinaryHelperMem(instr, IR::HelperOP_CmNeq_A);
  1186. }
  1187. }
  1188. else if (PHASE_OFF(Js::BranchFastPathPhase, this->m_func) || noMathFastPath || !m_lowererMD.GenerateFastCmXxTaggedInt(instr))
  1189. {
  1190. this->LowerBinaryHelperMem(instr, IR::HelperOP_CmNeq_A);
  1191. }
  1192. break;
  1193. case Js::OpCode::CmSrEq_A:
  1194. if (!PHASE_OFF(Js::BranchFastPathPhase, this->m_func) && !noMathFastPath && this->TryGenerateFastBrOrCmTypeOf(instr, &instrPrev, &fNoLower))
  1195. {
  1196. if (!fNoLower)
  1197. {
  1198. this->LowerBinaryHelperMem(instr, IR::HelperOP_CmSrEq_A);
  1199. }
  1200. }
  1201. else if (!PHASE_OFF(Js::BranchFastPathPhase, this->m_func) && !noMathFastPath && this->TryGenerateFastCmSrEq(instr))
  1202. {
  1203. }
  1204. else if (PHASE_OFF(Js::BranchFastPathPhase, this->m_func) || noMathFastPath || !m_lowererMD.GenerateFastCmXxTaggedInt(instr))
  1205. {
  1206. this->LowerBinaryHelperMem(instr, IR::HelperOP_CmSrEq_A);
  1207. }
  1208. break;
  1209. case Js::OpCode::CmSrNeq_A:
  1210. if (!PHASE_OFF(Js::BranchFastPathPhase, this->m_func) && !noMathFastPath && this->TryGenerateFastBrOrCmTypeOf(instr, &instrPrev, &fNoLower))
  1211. {
  1212. if (!fNoLower)
  1213. {
  1214. this->LowerBinaryHelperMem(instr, IR::HelperOP_CmSrNeq_A);
  1215. }
  1216. }
  1217. else if (PHASE_OFF(Js::BranchFastPathPhase, this->m_func) || noMathFastPath || !m_lowererMD.GenerateFastCmXxTaggedInt(instr))
  1218. {
  1219. this->LowerBinaryHelperMem(instr, IR::HelperOP_CmSrNeq_A);
  1220. }
  1221. break;
  1222. case Js::OpCode::CmGt_A:
  1223. if (instr->GetSrc1()->IsFloat())
  1224. {
  1225. Assert(instr->GetSrc1()->GetType() == instr->GetSrc2()->GetType());
  1226. this->m_lowererMD.GenerateFastCmXxR8(instr);
  1227. }
  1228. else if (PHASE_OFF(Js::BranchFastPathPhase, this->m_func) || noMathFastPath || !m_lowererMD.GenerateFastCmXxTaggedInt(instr))
  1229. {
  1230. this->LowerBinaryHelperMem(instr, IR::HelperOP_CmGt_A);
  1231. }
  1232. break;
  1233. case Js::OpCode::CmGe_A:
  1234. if (instr->GetSrc1()->IsFloat())
  1235. {
  1236. Assert(instr->GetSrc1()->GetType() == instr->GetSrc2()->GetType());
  1237. this->m_lowererMD.GenerateFastCmXxR8(instr);
  1238. }
  1239. else if (PHASE_OFF(Js::BranchFastPathPhase, this->m_func) || noMathFastPath || !m_lowererMD.GenerateFastCmXxTaggedInt(instr))
  1240. {
  1241. this->LowerBinaryHelperMem(instr, IR::HelperOP_CmGe_A);
  1242. }
  1243. break;
  1244. case Js::OpCode::CmLt_A:
  1245. if (instr->GetSrc1()->IsFloat())
  1246. {
  1247. Assert(instr->GetSrc1()->GetType() == instr->GetSrc2()->GetType());
  1248. this->m_lowererMD.GenerateFastCmXxR8(instr);
  1249. }
  1250. else if (PHASE_OFF(Js::BranchFastPathPhase, this->m_func) || noMathFastPath || !m_lowererMD.GenerateFastCmXxTaggedInt(instr))
  1251. {
  1252. this->LowerBinaryHelperMem(instr, IR::HelperOP_CmLt_A);
  1253. }
  1254. break;
  1255. case Js::OpCode::CmLe_A:
  1256. if (instr->GetSrc1()->IsFloat())
  1257. {
  1258. Assert(instr->GetSrc1()->GetType() == instr->GetSrc2()->GetType());
  1259. this->m_lowererMD.GenerateFastCmXxR8(instr);
  1260. }
  1261. else if (PHASE_OFF(Js::BranchFastPathPhase, this->m_func) || noMathFastPath || !m_lowererMD.GenerateFastCmXxTaggedInt(instr))
  1262. {
  1263. this->LowerBinaryHelperMem(instr, IR::HelperOP_CmLe_A);
  1264. }
  1265. break;
  1266. case Js::OpCode::CmEq_I4:
  1267. case Js::OpCode::CmNeq_I4:
  1268. case Js::OpCode::CmGe_I4:
  1269. case Js::OpCode::CmGt_I4:
  1270. case Js::OpCode::CmLe_I4:
  1271. case Js::OpCode::CmLt_I4:
  1272. case Js::OpCode::CmUnGe_I4:
  1273. case Js::OpCode::CmUnGt_I4:
  1274. case Js::OpCode::CmUnLe_I4:
  1275. case Js::OpCode::CmUnLt_I4:
  1276. this->m_lowererMD.GenerateFastCmXxI4(instr);
  1277. break;
  1278. case Js::OpCode::Conv_Bool:
  1279. instrPrev = this->m_lowererMD.GenerateConvBool(instr);
  1280. break;
  1281. case Js::OpCode::IsInst:
  1282. m_lowererMD.GenerateFastIsInst(instr);
  1283. instrPrev = this->LowerIsInst(instr, IR::HelperScrObj_OP_IsInst);
  1284. break;
  1285. case Js::OpCode::IsIn:
  1286. this->LowerBinaryHelperMem(instr, IR::HelperOp_IsIn);
  1287. break;
  1288. case Js::OpCode::LdInt8ArrViewElem:
  1289. case Js::OpCode::LdUInt8ArrViewElem:
  1290. case Js::OpCode::LdInt16ArrViewElem:
  1291. case Js::OpCode::LdUInt16ArrViewElem:
  1292. case Js::OpCode::LdInt32ArrViewElem:
  1293. case Js::OpCode::LdUInt32ArrViewElem:
  1294. case Js::OpCode::LdFloat32ArrViewElem:
  1295. case Js::OpCode::LdFloat64ArrViewElem:
  1296. instrPrev = LowerLdArrViewElem(instr);
  1297. break;
  1298. case Js::OpCode::StInt8ArrViewElem:
  1299. case Js::OpCode::StUInt8ArrViewElem:
  1300. case Js::OpCode::StInt16ArrViewElem:
  1301. case Js::OpCode::StUInt16ArrViewElem:
  1302. case Js::OpCode::StInt32ArrViewElem:
  1303. case Js::OpCode::StUInt32ArrViewElem:
  1304. case Js::OpCode::StFloat32ArrViewElem:
  1305. case Js::OpCode::StFloat64ArrViewElem:
  1306. instrPrev = LowerStArrViewElem(instr);
  1307. break;
  1308. case Js::OpCode::Memset:
  1309. case Js::OpCode::Memcopy:
  1310. {
  1311. LowerMemOp(instr);
  1312. break;
  1313. }
  1314. case Js::OpCode::ArrayDetachedCheck:
  1315. instrPrev = LowerArrayDetachedCheck(instr);
  1316. break;
  1317. case Js::OpCode::StElemI_A:
  1318. case Js::OpCode::StElemI_A_Strict:
  1319. {
  1320. // Note: under debugger (Fast F12) don't let GenerateFastStElemI which calls into ToNumber_Helper
  1321. // which takes double, and currently our helper wrapper doesn't support double.
  1322. bool fastPath = !noMathFastPath && !m_func->IsJitInDebugMode();
  1323. if(!fastPath && instr->HasBailOutInfo())
  1324. {
  1325. // Some bailouts are generated around the helper call, and will work even if the fast path is disabled. Other
  1326. // bailouts require the fast path.
  1327. const IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  1328. const IR::BailOutKind bailOutKindBits = bailOutKind & IR::BailOutKindBits;
  1329. if(bailOutKindBits & ~(IR::BailOutOnMissingValue | IR::BailOutConvertedNativeArray))
  1330. {
  1331. fastPath = true;
  1332. }
  1333. else
  1334. {
  1335. const IR::BailOutKind bailOutKindMinusBits = bailOutKind & ~IR::BailOutKindBits;
  1336. fastPath =
  1337. bailOutKindMinusBits &&
  1338. bailOutKindMinusBits != IR::BailOutOnImplicitCalls &&
  1339. bailOutKindMinusBits != IR::BailOutOnImplicitCallsPreOp;
  1340. }
  1341. }
  1342. IR::Opnd * opnd = instr->GetDst();
  1343. IR::Opnd * baseOpnd = opnd->AsIndirOpnd()->GetBaseOpnd();
  1344. ValueType profiledBaseValueType = baseOpnd->AsRegOpnd()->GetValueType();
  1345. if (profiledBaseValueType.IsUninitialized() && baseOpnd->AsRegOpnd()->m_sym->IsSingleDef())
  1346. {
  1347. baseOpnd->SetValueType(baseOpnd->FindProfiledValueType());
  1348. }
  1349. bool instrIsInHelperBlock;
  1350. if (!fastPath)
  1351. {
  1352. this->LowerStElemI(
  1353. instr,
  1354. instr->m_opcode == Js::OpCode::StElemI_A ? Js::PropertyOperation_None : Js::PropertyOperation_StrictMode,
  1355. false);
  1356. }
  1357. else if (GenerateFastStElemI(instr, &instrIsInHelperBlock))
  1358. {
  1359. #if DBG
  1360. if(instr->HasBailOutInfo())
  1361. {
  1362. const IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  1363. Assert(
  1364. (bailOutKind & ~IR::BailOutKindBits) != IR::BailOutConventionalTypedArrayAccessOnly &&
  1365. !(
  1366. bailOutKind &
  1367. (IR::BailOutConventionalNativeArrayAccessOnly | IR::BailOutOnArrayAccessHelperCall)
  1368. ));
  1369. }
  1370. #endif
  1371. this->LowerStElemI(
  1372. instr,
  1373. instr->m_opcode == Js::OpCode::StElemI_A ? Js::PropertyOperation_None : Js::PropertyOperation_StrictMode,
  1374. instrIsInHelperBlock);
  1375. }
  1376. break;
  1377. }
  1378. case Js::OpCode::LdElemI_A:
  1379. case Js::OpCode::LdMethodElem:
  1380. {
  1381. bool fastPath =
  1382. !noMathFastPath &&
  1383. (
  1384. instr->m_opcode != Js::OpCode::LdMethodElem ||
  1385. instr->GetSrc1()->AsIndirOpnd()->GetBaseOpnd()->GetValueType().IsLikelyObject()
  1386. );
  1387. if(!fastPath && instr->HasBailOutInfo())
  1388. {
  1389. // Some bailouts are generated around the helper call, and will work even if the fast path is disabled. Other
  1390. // bailouts require the fast path.
  1391. const IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  1392. if(bailOutKind & IR::BailOutKindBits)
  1393. {
  1394. fastPath = true;
  1395. }
  1396. else
  1397. {
  1398. const IR::BailOutKind bailOutKindMinusBits = bailOutKind & ~IR::BailOutKindBits;
  1399. fastPath =
  1400. bailOutKindMinusBits &&
  1401. bailOutKindMinusBits != IR::BailOutOnImplicitCalls &&
  1402. bailOutKindMinusBits != IR::BailOutOnImplicitCallsPreOp;
  1403. }
  1404. }
  1405. IR::Opnd * opnd = instr->GetSrc1();
  1406. IR::Opnd * baseOpnd = opnd->AsIndirOpnd()->GetBaseOpnd();
  1407. ValueType profiledBaseValueType = baseOpnd->AsRegOpnd()->GetValueType();
  1408. if (profiledBaseValueType.IsUninitialized() && baseOpnd->AsRegOpnd()->m_sym->IsSingleDef())
  1409. {
  1410. baseOpnd->SetValueType(baseOpnd->FindProfiledValueType());
  1411. }
  1412. bool instrIsInHelperBlock;
  1413. if (!fastPath)
  1414. {
  1415. this->LowerLdElemI(
  1416. instr,
  1417. instr->m_opcode == Js::OpCode::LdElemI_A ? IR::HelperOp_GetElementI : IR::HelperOp_GetMethodElement,
  1418. false);
  1419. }
  1420. else if (GenerateFastLdElemI(instr, &instrIsInHelperBlock))
  1421. {
  1422. #if DBG
  1423. if(instr->HasBailOutInfo())
  1424. {
  1425. const IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  1426. Assert(
  1427. (bailOutKind & ~IR::BailOutKindBits) != IR::BailOutConventionalTypedArrayAccessOnly &&
  1428. !(
  1429. bailOutKind &
  1430. (IR::BailOutConventionalNativeArrayAccessOnly | IR::BailOutOnArrayAccessHelperCall)
  1431. ));
  1432. }
  1433. #endif
  1434. this->LowerLdElemI(
  1435. instr,
  1436. instr->m_opcode == Js::OpCode::LdElemI_A ? IR::HelperOp_GetElementI : IR::HelperOp_GetMethodElement,
  1437. instrIsInHelperBlock);
  1438. }
  1439. break;
  1440. }
  1441. case Js::OpCode::InitSetElemI:
  1442. instrPrev = this->LowerStElemI(instr, Js::PropertyOperation_None, false, IR::HelperOP_InitElemSetter);
  1443. break;
  1444. case Js::OpCode::InitGetElemI:
  1445. instrPrev = this->LowerStElemI(instr, Js::PropertyOperation_None, false, IR::HelperOP_InitElemGetter);
  1446. break;
  1447. case Js::OpCode::InitComputedProperty:
  1448. instrPrev = this->LowerStElemI(instr, Js::PropertyOperation_None, false, IR::HelperOP_InitComputedProperty);
  1449. break;
  1450. case Js::OpCode::Delete_A:
  1451. this->LowerUnaryHelperMem(instr, IR::HelperOp_Delete);
  1452. break;
  1453. case Js::OpCode::DeleteElemI_A:
  1454. this->LowerDeleteElemI(instr, false);
  1455. break;
  1456. case Js::OpCode::DeleteElemIStrict_A:
  1457. this->LowerDeleteElemI(instr, true);
  1458. break;
  1459. case Js::OpCode::BytecodeArgOutCapture:
  1460. m_lowererMD.ChangeToAssign(instr);
  1461. break;
  1462. case Js::OpCode::UnwrapWithObj:
  1463. this->LowerUnaryHelper(instr, IR::HelperOp_UnwrapWithObj);
  1464. break;
  1465. case Js::OpCode::Ld_A:
  1466. case Js::OpCode::Ld_I4:
  1467. case Js::OpCode::InitConst:
  1468. if (instr->IsJitProfilingInstr() && instr->AsJitProfilingInstr()->isBeginSwitch) {
  1469. LowerProfiledBeginSwitch(instr->AsJitProfilingInstr());
  1470. break;
  1471. }
  1472. m_lowererMD.ChangeToAssign(instr);
  1473. if(instr->HasBailOutInfo())
  1474. {
  1475. IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  1476. if(bailOutKind == IR::BailOutExpectingString)
  1477. {
  1478. this->LowerBailOnNotString(instr);
  1479. }
  1480. else
  1481. {
  1482. // Should not reach here as there are only 1 BailOutKind (BailOutExpectingString) currently associated with the Load Instr
  1483. Assert(false);
  1484. }
  1485. }
  1486. break;
  1487. case Js::OpCode::LdIndir:
  1488. Assert(instr->GetDst());
  1489. Assert(instr->GetDst()->IsRegOpnd());
  1490. Assert(instr->GetSrc1());
  1491. Assert(instr->GetSrc1()->IsIndirOpnd());
  1492. Assert(!instr->GetSrc2());
  1493. m_lowererMD.ChangeToAssign(instr);
  1494. break;
  1495. case Js::OpCode::FromVar:
  1496. Assert(instr->GetSrc1()->GetType() == TyVar);
  1497. if (instr->GetDst()->GetType() == TyInt32)
  1498. {
  1499. if(m_lowererMD.EmitLoadInt32(instr))
  1500. {
  1501. // Bail out instead of calling a helper
  1502. Assert(instr->GetBailOutKind() == IR::BailOutIntOnly || instr->GetBailOutKind() == IR::BailOutExpectingInteger);
  1503. Assert(!instr->GetSrc1()->GetValueType().IsInt()); // when we know it's an int, it should not have bailout info, to avoid generating a bailout path that will never be taken
  1504. instr->UnlinkSrc1();
  1505. instr->UnlinkDst();
  1506. GenerateBailOut(instr);
  1507. }
  1508. }
  1509. else if (instr->GetDst()->IsFloat())
  1510. {
  1511. if (m_func->GetJnFunction()->GetIsAsmJsFunction())
  1512. {
  1513. m_lowererMD.EmitLoadFloat(instr->GetDst(), instr->GetSrc1(), instr);
  1514. instr->Remove();
  1515. }
  1516. else
  1517. {
  1518. m_lowererMD.EmitLoadFloatFromNumber(instr->GetDst(), instr->GetSrc1(), instr);
  1519. }
  1520. }
  1521. // Support on IA only
  1522. #if defined(_M_IX86) || defined(_M_X64)
  1523. else if (instr->GetDst()->IsSimd128())
  1524. {
  1525. // SIMD_JS
  1526. m_lowererMD.GenerateCheckedSimdLoad(instr);
  1527. }
  1528. #endif
  1529. else
  1530. {
  1531. Assert(UNREACHED);
  1532. }
  1533. break;
  1534. case Js::OpCode::ArgOut_A:
  1535. // I don't know if this can happen in asm.js mode, but if it can, we might want to handle differently
  1536. Assert(!m_func->GetJnFunction()->GetIsAsmjsMode());
  1537. // fall-through
  1538. case Js::OpCode::ArgOut_A_Inline:
  1539. case Js::OpCode::ArgOut_A_Dynamic:
  1540. {
  1541. // ArgOut/StartCall are normally lowered by the lowering of the associated call instr.
  1542. // If the call becomes unreachable, we could end up with an orphan ArgOut or StartCall.
  1543. // Change the ArgOut into a store to the stack for bailouts
  1544. instr->FreeSrc2();
  1545. StackSym *argSym = instr->GetDst()->AsSymOpnd()->m_sym->AsStackSym();
  1546. argSym->m_offset = this->m_func->StackAllocate(sizeof(Js::Var));
  1547. argSym->m_allocated = true;
  1548. argSym->m_isOrphanedArg = true;
  1549. this->m_lowererMD.ChangeToAssign(instr);
  1550. }
  1551. break;
  1552. case Js::OpCode::LoweredStartCall:
  1553. case Js::OpCode::StartCall:
  1554. // ArgOut/StartCall are normally lowered by the lowering of the associated call instr.
  1555. // If the call becomes unreachable, we could end up with an orphan ArgOut or StartCall.
  1556. // We'll just delete these StartCalls during peeps.
  1557. break;
  1558. case Js::OpCode::ToVar:
  1559. Assert(instr->GetDst()->GetType() == TyVar);
  1560. if (instr->GetSrc1()->GetType() == TyInt32)
  1561. {
  1562. m_lowererMD.EmitLoadVar(instr);
  1563. }
  1564. else if (instr->GetSrc1()->GetType() == TyFloat64)
  1565. {
  1566. Assert(instr->GetSrc1()->IsRegOpnd());
  1567. m_lowererMD.SaveDoubleToVar(
  1568. instr->GetDst()->AsRegOpnd(),
  1569. instr->GetSrc1()->AsRegOpnd(), instr, instr);
  1570. instr->Remove();
  1571. }
  1572. #if defined(_M_IX86) || defined(_M_X64)
  1573. else if (IRType_IsSimd128(instr->GetSrc1()->GetType()))
  1574. {
  1575. m_lowererMD.GenerateSimdStore(instr);
  1576. }
  1577. #endif
  1578. else
  1579. {
  1580. Assert(UNREACHED);
  1581. }
  1582. break;
  1583. case Js::OpCode::Conv_Prim:
  1584. if (instr->GetDst()->IsFloat())
  1585. {
  1586. if (instr->GetSrc1()->IsIntConstOpnd())
  1587. {
  1588. LoadFloatFromNonReg(instr->UnlinkSrc1(), instr->UnlinkDst(), instr);
  1589. }
  1590. else if (instr->GetSrc1()->IsInt32())
  1591. {
  1592. m_lowererMD.EmitIntToFloat(instr->GetDst(), instr->GetSrc1(), instr);
  1593. }
  1594. else if (instr->GetSrc1()->IsUInt32())
  1595. {
  1596. Assert(instr->GetDst()->IsFloat64());
  1597. m_lowererMD.EmitUIntToFloat(instr->GetDst(), instr->GetSrc1(), instr);
  1598. }
  1599. else
  1600. {
  1601. Assert(instr->GetDst()->IsFloat64());
  1602. Assert(instr->GetSrc1()->IsFloat32());
  1603. m_lowererMD.EmitFloat32ToFloat64(instr->GetDst(), instr->GetSrc1(), instr);
  1604. }
  1605. }
  1606. else
  1607. {
  1608. Assert(instr->GetDst()->IsInt32());
  1609. Assert(instr->GetSrc1()->IsFloat());
  1610. m_lowererMD.EmitFloatToInt(instr->GetDst(), instr->GetSrc1(), instr);
  1611. }
  1612. instr->Remove();
  1613. break;
  1614. case Js::OpCode::FunctionExit:
  1615. LowerFunctionExit(instr);
  1616. // The rest of Epilog generation happens after reg allocation
  1617. break;
  1618. case Js::OpCode::FunctionEntry:
  1619. LowerFunctionEntry(instr);
  1620. // The rest of Prolog generation happens after reg allocation
  1621. break;
  1622. case Js::OpCode::ArgIn_Rest:
  1623. case Js::OpCode::ArgIn_A:
  1624. if (m_func->GetJnFunction()->GetIsAsmjsMode() && !m_func->IsLoopBody())
  1625. {
  1626. instrPrev = LowerArgInAsmJs(instr);
  1627. }
  1628. else
  1629. {
  1630. instrPrev = LowerArgIn(instr);
  1631. }
  1632. break;
  1633. case Js::OpCode::Label:
  1634. if (instr->AsLabelInstr()->m_isLoopTop)
  1635. {
  1636. if (this->outerMostLoopLabel == instr)
  1637. {
  1638. noFieldFastPath = !defaultDoFastPath;
  1639. noMathFastPath = !defaultDoFastPath;
  1640. this->outerMostLoopLabel = nullptr;
  1641. instr->AsLabelInstr()->GetLoop()->isProcessed = true;
  1642. }
  1643. this->m_func->MarkConstantAddressSyms(instr->AsLabelInstr()->GetLoop()->regAlloc.liveOnBackEdgeSyms);
  1644. instr->AsLabelInstr()->GetLoop()->regAlloc.liveOnBackEdgeSyms->Or(this->addToLiveOnBackEdgeSyms);
  1645. }
  1646. break;
  1647. case Js::OpCode::Br:
  1648. m_lowererMD.LowerUncondBranch(instr);
  1649. break;
  1650. case Js::OpCode::BrFncEqApply:
  1651. LowerBrFncApply(instr,IR::HelperOp_OP_BrFncEqApply);
  1652. break;
  1653. case Js::OpCode::BrFncNeqApply:
  1654. LowerBrFncApply(instr,IR::HelperOp_OP_BrFncNeqApply);
  1655. break;
  1656. case Js::OpCode::BrHasSideEffects:
  1657. case Js::OpCode::BrNotHasSideEffects:
  1658. m_lowererMD.GenerateFastBrS(instr->AsBranchInstr());
  1659. break;
  1660. case Js::OpCode::BrFalse_A:
  1661. case Js::OpCode::BrTrue_A:
  1662. if (instr->GetSrc1()->IsFloat())
  1663. {
  1664. GenerateFastBrBool(instr->AsBranchInstr());
  1665. }
  1666. else if (PHASE_OFF(Js::BranchFastPathPhase, this->m_func) ||
  1667. noMathFastPath ||
  1668. GenerateFastBrBool(instr->AsBranchInstr()))
  1669. {
  1670. this->LowerBrBMem(instr, IR::HelperConv_ToBoolean);
  1671. }
  1672. break;
  1673. case Js::OpCode::BrOnObject_A:
  1674. if (PHASE_OFF(Js::BranchFastPathPhase, this->m_func) || noMathFastPath)
  1675. {
  1676. this->LowerBrOnObject(instr, IR::HelperOp_IsObject);
  1677. }
  1678. else
  1679. {
  1680. GenerateFastBrOnObject(instr);
  1681. }
  1682. break;
  1683. case Js::OpCode::BrOnClassConstructor:
  1684. this->LowerBrOnClassConstructor(instr, IR::HelperOp_IsClassConstructor);
  1685. break;
  1686. case Js::OpCode::BrAddr_A:
  1687. case Js::OpCode::BrNotAddr_A:
  1688. case Js::OpCode::BrNotNull_A:
  1689. m_lowererMD.LowerCondBranch(instr);
  1690. break;
  1691. case Js::OpCode::BrEq_A:
  1692. case Js::OpCode::BrNotNeq_A:
  1693. if (instr->GetSrc1()->IsFloat())
  1694. {
  1695. Assert(instr->GetSrc1()->GetType() == instr->GetSrc2()->GetType());
  1696. m_lowererMD.LowerToFloat(instr);
  1697. }
  1698. else if (!PHASE_OFF(Js::BranchFastPathPhase, this->m_func) && !noMathFastPath)
  1699. {
  1700. bool needHelper = true;
  1701. if (this->TryGenerateFastBrOrCmTypeOf(instr, &instrPrev, &fNoLower))
  1702. {
  1703. if (!fNoLower)
  1704. {
  1705. this->LowerBrCMem(instr, IR::HelperOp_Equal, false, false /*isHelper*/);
  1706. }
  1707. }
  1708. else if (this->TryGenerateFastBrEq(instr))
  1709. {
  1710. }
  1711. else if (m_lowererMD.GenerateFastBrString(instr->AsBranchInstr()) || this->GenerateFastBrEqLikely(instr->AsBranchInstr(), &needHelper))
  1712. {
  1713. if (needHelper)
  1714. {
  1715. this->LowerBrCMem(instr, IR::HelperOp_Equal, false);
  1716. }
  1717. }
  1718. else
  1719. {
  1720. if (needHelper)
  1721. {
  1722. this->LowerBrCMem(instr, IR::HelperOp_Equal, false, false /*isHelper*/);
  1723. }
  1724. }
  1725. if (!needHelper)
  1726. {
  1727. instr->Remove();
  1728. }
  1729. }
  1730. else
  1731. {
  1732. this->LowerBrCMem(instr, IR::HelperOp_Equal, true, false /*isHelper*/);
  1733. }
  1734. break;
  1735. case Js::OpCode::BrGe_A:
  1736. case Js::OpCode::BrNotGe_A:
  1737. if (instr->GetSrc1()->IsFloat())
  1738. {
  1739. Assert(instr->GetSrc1()->GetType() == instr->GetSrc2()->GetType());
  1740. m_lowererMD.LowerToFloat(instr);
  1741. }
  1742. else if (!PHASE_OFF(Js::BranchFastPathPhase, this->m_func) && !noMathFastPath)
  1743. {
  1744. this->LowerBrCMem(instr, IR::HelperOp_GreaterEqual, false, false /*isHelper*/);
  1745. }
  1746. else
  1747. {
  1748. this->LowerBrCMem(instr, IR::HelperOp_GreaterEqual, true, false /*isHelper*/);
  1749. }
  1750. break;
  1751. case Js::OpCode::BrGt_A:
  1752. case Js::OpCode::BrNotGt_A:
  1753. if (instr->GetSrc1()->IsFloat())
  1754. {
  1755. Assert(instr->GetSrc1()->GetType() == instr->GetSrc2()->GetType());
  1756. m_lowererMD.LowerToFloat(instr);
  1757. }
  1758. else if (!PHASE_OFF(Js::BranchFastPathPhase, this->m_func) && !noMathFastPath)
  1759. {
  1760. this->LowerBrCMem(instr, IR::HelperOp_Greater, false, false /*isHelper*/);
  1761. }
  1762. else
  1763. {
  1764. this->LowerBrCMem(instr, IR::HelperOp_Greater, true, false /*isHelper*/);
  1765. }
  1766. break;
  1767. case Js::OpCode::BrLt_A:
  1768. case Js::OpCode::BrNotLt_A:
  1769. if (instr->GetSrc1()->IsFloat())
  1770. {
  1771. Assert(instr->GetSrc1()->GetType() == instr->GetSrc2()->GetType());
  1772. m_lowererMD.LowerToFloat(instr);
  1773. }
  1774. else if (!PHASE_OFF(Js::BranchFastPathPhase, this->m_func) && !noMathFastPath)
  1775. {
  1776. this->LowerBrCMem(instr, IR::HelperOp_Less, false, false /*isHelper*/);
  1777. }
  1778. else
  1779. {
  1780. this->LowerBrCMem(instr, IR::HelperOp_Less, true, false /*isHelper*/);
  1781. }
  1782. break;
  1783. case Js::OpCode::BrLe_A:
  1784. case Js::OpCode::BrNotLe_A:
  1785. if (instr->GetSrc1()->IsFloat())
  1786. {
  1787. Assert(instr->GetSrc1()->GetType() == instr->GetSrc2()->GetType());
  1788. m_lowererMD.LowerToFloat(instr);
  1789. }
  1790. else if (!PHASE_OFF(Js::BranchFastPathPhase, this->m_func) && !noMathFastPath)
  1791. {
  1792. this->LowerBrCMem(instr, IR::HelperOp_LessEqual, false, false /*isHelper*/);
  1793. }
  1794. else
  1795. {
  1796. this->LowerBrCMem(instr, IR::HelperOp_LessEqual, true, false /*isHelper*/);
  1797. }
  1798. break;
  1799. case Js::OpCode::BrNeq_A:
  1800. case Js::OpCode::BrNotEq_A:
  1801. if (instr->GetSrc1()->IsFloat())
  1802. {
  1803. Assert(instr->GetSrc1()->GetType() == instr->GetSrc2()->GetType());
  1804. m_lowererMD.LowerToFloat(instr);
  1805. }
  1806. else if (!PHASE_OFF(Js::BranchFastPathPhase, this->m_func) && !noMathFastPath)
  1807. {
  1808. bool needHelper = true;
  1809. if (this->TryGenerateFastBrOrCmTypeOf(instr, &instrPrev, &fNoLower))
  1810. {
  1811. if (!fNoLower)
  1812. {
  1813. this->LowerBrCMem(instr, IR::HelperOp_NotEqual, false, false /*isHelper*/);
  1814. }
  1815. }
  1816. else if (this->TryGenerateFastBrNeq(instr))
  1817. {
  1818. }
  1819. else if (m_lowererMD.GenerateFastBrString(instr->AsBranchInstr()) || this->GenerateFastBrEqLikely(instr->AsBranchInstr(), &needHelper))
  1820. {
  1821. this->LowerBrCMem(instr, IR::HelperOp_NotEqual, false);
  1822. }
  1823. else
  1824. {
  1825. this->LowerBrCMem(instr, IR::HelperOp_NotEqual, false, false /*isHelper*/);
  1826. }
  1827. }
  1828. else
  1829. {
  1830. this->LowerBrCMem(instr, IR::HelperOp_NotEqual, true, false /*isHelper*/);
  1831. }
  1832. break;
  1833. case Js::OpCode::MultiBr:
  1834. {
  1835. IR::MultiBranchInstr * multiBranchInstr = instr->AsBranchInstr()->AsMultiBrInstr();
  1836. switch (multiBranchInstr->m_kind)
  1837. {
  1838. case IR::MultiBranchInstr::StrDictionary:
  1839. this->GenerateSwitchStringLookup(instr);
  1840. break;
  1841. case IR::MultiBranchInstr::SingleCharStrJumpTable:
  1842. this->GenerateSingleCharStrJumpTableLookup(instr);
  1843. m_func->m_totalJumpTableSizeInBytesForSwitchStatements += (multiBranchInstr->GetBranchJumpTable()->tableSize * sizeof(void*));
  1844. break;
  1845. case IR::MultiBranchInstr::IntJumpTable:
  1846. this->LowerMultiBr(instr);
  1847. m_func->m_totalJumpTableSizeInBytesForSwitchStatements += (multiBranchInstr->GetBranchJumpTable()->tableSize * sizeof(void*));
  1848. break;
  1849. default:
  1850. Assert(false);
  1851. }
  1852. break;
  1853. }
  1854. case Js::OpCode::BrSrEq_A:
  1855. case Js::OpCode::BrSrNotNeq_A:
  1856. {
  1857. srcReg1 = instr->GetSrc1()->IsRegOpnd() ? instr->GetSrc1()->AsRegOpnd() : nullptr;
  1858. srcReg2 = instr->GetSrc2()->IsRegOpnd() ? instr->GetSrc2()->AsRegOpnd() : nullptr;
  1859. if (instr->GetSrc1()->IsFloat())
  1860. {
  1861. Assert(instr->GetSrc1()->GetType() == instr->GetSrc2()->GetType());
  1862. m_lowererMD.LowerToFloat(instr);
  1863. }
  1864. else if (!PHASE_OFF(Js::BranchFastPathPhase, this->m_func) && !noMathFastPath && this->TryGenerateFastBrOrCmTypeOf(instr, &instrPrev, &fNoLower))
  1865. {
  1866. if (!fNoLower)
  1867. {
  1868. this->LowerBrCMem(instr, IR::HelperOp_StrictEqual, false, false /*isHelper*/);
  1869. }
  1870. }
  1871. else if (!PHASE_OFF(Js::BranchFastPathPhase, this->m_func) && !noMathFastPath && this->GenerateFastBrSrEq(instr, srcReg1, srcReg2, &instrPrev, noMathFastPath))
  1872. {
  1873. }
  1874. else
  1875. {
  1876. bool needHelper = true;
  1877. if (!PHASE_OFF(Js::BranchFastPathPhase, this->m_func) && !noMathFastPath)
  1878. {
  1879. if (m_lowererMD.GenerateFastBrString(instr->AsBranchInstr()) || this->GenerateFastBrEqLikely(instr->AsBranchInstr(), &needHelper))
  1880. {
  1881. if (needHelper)
  1882. {
  1883. this->LowerBrCMem(instr, IR::HelperOp_StrictEqual, false);
  1884. }
  1885. }
  1886. else
  1887. {
  1888. if (needHelper)
  1889. {
  1890. this->LowerBrCMem(instr, IR::HelperOp_StrictEqual, false, false /*isHelper*/);
  1891. }
  1892. }
  1893. if (!needHelper)
  1894. {
  1895. instr->Remove();
  1896. }
  1897. }
  1898. else
  1899. {
  1900. this->LowerBrCMem(instr, IR::HelperOp_StrictEqual, true, false /*isHelper*/);
  1901. }
  1902. }
  1903. break;
  1904. }
  1905. case Js::OpCode::BrSrNeq_A:
  1906. case Js::OpCode::BrSrNotEq_A:
  1907. if (instr->GetSrc1()->IsFloat())
  1908. {
  1909. Assert(instr->GetSrc1()->GetType() == instr->GetSrc2()->GetType());
  1910. m_lowererMD.LowerToFloat(instr);
  1911. }
  1912. else if (!PHASE_OFF(Js::BranchFastPathPhase, this->m_func) && !noMathFastPath)
  1913. {
  1914. bool needHelper = true;
  1915. if (this->TryGenerateFastBrOrCmTypeOf(instr, &instrPrev, &fNoLower))
  1916. {
  1917. if (!fNoLower)
  1918. {
  1919. this->LowerBrCMem(instr, IR::HelperOp_NotStrictEqual, false, false /*isHelper*/);
  1920. }
  1921. }
  1922. else if (this->GenerateFastBrSrNeq(instr, &instrPrev))
  1923. {
  1924. }
  1925. else if (m_lowererMD.GenerateFastBrString(instr->AsBranchInstr()) || this->GenerateFastBrEqLikely(instr->AsBranchInstr(), &needHelper))
  1926. {
  1927. if (needHelper)
  1928. {
  1929. this->LowerBrCMem(instr, IR::HelperOp_NotStrictEqual, false);
  1930. }
  1931. }
  1932. else
  1933. {
  1934. if (needHelper)
  1935. {
  1936. this->LowerBrCMem(instr, IR::HelperOp_NotStrictEqual, false, false /*isHelper*/);
  1937. }
  1938. }
  1939. if (!needHelper)
  1940. {
  1941. instr->Remove();
  1942. }
  1943. }
  1944. else
  1945. {
  1946. this->LowerBrCMem(instr, IR::HelperOp_NotStrictEqual, true, false /*isHelper*/);
  1947. }
  1948. break;
  1949. case Js::OpCode::BrOnEmpty:
  1950. case Js::OpCode::BrOnNotEmpty:
  1951. if (!PHASE_OFF(Js::BranchFastPathPhase, this->m_func))
  1952. {
  1953. m_lowererMD.GenerateFastBrBReturn(instr);
  1954. this->LowerBrBReturn(instr, IR::HelperOp_OP_BrOnEmpty, true);
  1955. }
  1956. else
  1957. {
  1958. this->LowerBrBReturn(instr, IR::HelperOp_OP_BrOnEmpty, false);
  1959. }
  1960. break;
  1961. case Js::OpCode::BrOnHasProperty:
  1962. case Js::OpCode::BrOnNoProperty:
  1963. this->LowerBrProperty(instr, IR::HelperOp_HasProperty);
  1964. break;
  1965. case Js::OpCode::BrOnException:
  1966. Assert(!this->m_func->DoGlobOpt());
  1967. instr->Remove();
  1968. break;
  1969. case Js::OpCode::BrOnNoException:
  1970. instr->m_opcode = LowererMD::MDUncondBranchOpcode;
  1971. break;
  1972. case Js::OpCode::StSlot:
  1973. this->LowerStSlot(instr);
  1974. break;
  1975. case Js::OpCode::StSlotChkUndecl:
  1976. this->LowerStSlotChkUndecl(instr);
  1977. break;
  1978. case Js::OpCode::ProfiledLoopStart:
  1979. {
  1980. Assert(m_func->DoSimpleJitDynamicProfile());
  1981. Assert(instr->IsJitProfilingInstr());
  1982. // Check for the helper instr from IRBuilding (it won't be there if there are no LoopEnds due to an infinite loop)
  1983. auto prev = instr->m_prev;
  1984. if (prev->IsJitProfilingInstr() && prev->AsJitProfilingInstr()->isLoopHelper)
  1985. {
  1986. auto saveOpnd = prev->UnlinkDst();
  1987. instrPrev = prev->m_prev;
  1988. prev->Remove();
  1989. const auto starFlag = GetImplicitCallFlagsOpnd();
  1990. IR::AutoReuseOpnd a(starFlag, m_func);
  1991. this->InsertMove(saveOpnd, starFlag, instr);
  1992. this->InsertMove(starFlag, CreateClearImplicitCallFlagsOpnd(), instr);
  1993. }
  1994. else
  1995. {
  1996. #if DBG
  1997. // Double check that we indeed do not have a LoopEnd that is part of the same loop for the rest of the function
  1998. auto cur = instr;
  1999. auto loopNumber = instr->AsJitProfilingInstr()->loopNumber;
  2000. while (cur)
  2001. {
  2002. Assert(cur->m_opcode != Js::OpCode::ProfiledLoopEnd || cur->IsJitProfilingInstr() && cur->AsJitProfilingInstr()->loopNumber != loopNumber);
  2003. cur = cur->m_next;
  2004. }
  2005. #endif
  2006. }
  2007. // If we turned off fulljit, there's no reason to do this.
  2008. if (!m_func->GetJnFunction()->DoFullJit())
  2009. {
  2010. instr->Remove();
  2011. }
  2012. else
  2013. {
  2014. Assert(instr->GetDst());
  2015. instr->SetSrc1(IR::HelperCallOpnd::New(IR::HelperSimpleGetScheduledEntryPoint, m_func));
  2016. m_lowererMD.LoadHelperArgument(instr, IR::Opnd::CreateUint32Opnd(instr->AsJitProfilingInstr()->loopNumber, m_func));
  2017. m_lowererMD.LoadHelperArgument(instr, IR::Opnd::CreateFramePointerOpnd(m_func));
  2018. this->m_lowererMD.LowerCall(instr, 0);
  2019. }
  2020. break;
  2021. }
  2022. case Js::OpCode::ProfiledLoopBodyStart:
  2023. {
  2024. Assert(m_func->DoSimpleJitDynamicProfile());
  2025. const auto loopNum = instr->AsJitProfilingInstr()->loopNumber;
  2026. Assert(loopNum < m_func->GetJnFunction()->GetLoopCount());
  2027. auto entryPointOpnd = instr->UnlinkSrc1();
  2028. auto dobailout = instr->UnlinkDst();
  2029. const auto dobailoutType = TyUint8;
  2030. Assert(dobailout->GetType() == TyUint8 && sizeof(decltype(Js::SimpleJitHelpers::IsLoopCodeGenDone(nullptr))) == 1);
  2031. m_lowererMD.LoadHelperArgument(instr, IR::IntConstOpnd::New(0, TyUint32, m_func)); // zero indicates that we do not want to add flags back in
  2032. m_lowererMD.LoadHelperArgument(instr, IR::IntConstOpnd::New(loopNum, TyUint32, m_func));
  2033. m_lowererMD.LoadHelperArgument(instr, IR::Opnd::CreateFramePointerOpnd(m_func));
  2034. instr->SetSrc1(IR::HelperCallOpnd::New(IR::HelperSimpleRecordLoopImplicitCallFlags, m_func));
  2035. m_lowererMD.LowerCall(instr, 0);
  2036. // Outline of JITed code:
  2037. //
  2038. // LoopStart:
  2039. // entryPoint = GetScheduledEntryPoint(framePtr, loopNum)
  2040. // LoopBodyStart:
  2041. // uint8 dobailout;
  2042. // if (entryPoint) {
  2043. // dobailout = IsLoopCodeGenDone(entryPoint)
  2044. // } else {
  2045. // dobailout = ++interpretCount >= threshold
  2046. // }
  2047. // // already exists from IRBuilding:
  2048. // if (dobailout) {
  2049. // Bailout
  2050. // }
  2051. if (!m_func->GetJnFunction()->DoFullJit() || !m_func->GetJnFunction()->DoJITLoopBody())
  2052. {
  2053. // If we're not doing fulljit, we've turned off JitLoopBodies, or if we don't have loop headers allocated (the function has a Try, etc)
  2054. // just move false to dobailout
  2055. this->InsertMove(dobailout, IR::IntConstOpnd::New(0, dobailoutType, m_func, true), instr->m_next);
  2056. }
  2057. else if (m_func->GetJnFunction()->ForceJITLoopBody())
  2058. {
  2059. // If we're forcing jit loop bodies, move true to dobailout
  2060. this->InsertMove(dobailout, IR::IntConstOpnd::New(1, dobailoutType, m_func, true), instr->m_next);
  2061. }
  2062. else
  2063. {
  2064. // Put in the labels
  2065. auto entryPointIsNull = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  2066. auto checkDoBailout = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  2067. instr->InsertAfter(checkDoBailout);
  2068. instr->InsertAfter(entryPointIsNull);
  2069. this->InsertCompareBranch(entryPointOpnd, IR::AddrOpnd::New(nullptr, IR::AddrOpndKindDynamicMisc, m_func), Js::OpCode::BrEq_A, false, entryPointIsNull, instr->m_next);
  2070. // If the entry point is not null
  2071. auto isCodeGenDone = IR::Instr::New(Js::OpCode::Call, dobailout, IR::HelperCallOpnd::New(IR::HelperSimpleIsLoopCodeGenDone, m_func), m_func);
  2072. entryPointIsNull->InsertBefore(isCodeGenDone);
  2073. m_lowererMD.LoadHelperArgument(isCodeGenDone, entryPointOpnd);
  2074. m_lowererMD.LowerCall(isCodeGenDone, 0);
  2075. this->InsertBranch(LowererMD::MDUncondBranchOpcode, true, checkDoBailout, entryPointIsNull);
  2076. // If the entry point is null
  2077. auto head = m_func->GetJnFunction()->GetLoopHeader(loopNum);
  2078. Assert(head);
  2079. static_assert(sizeof(head->interpretCount) == 4, "Change the type in the following line");
  2080. const auto type = TyUint32;
  2081. auto countReg = IR::RegOpnd::New(type, m_func);
  2082. auto countAddr = IR::MemRefOpnd::New(&head->interpretCount, type, m_func);
  2083. IR::AutoReuseOpnd a(countReg, m_func), b(countAddr, m_func);
  2084. this->InsertAdd(false, countReg, countAddr, IR::IntConstOpnd::New(1, type, m_func, true), checkDoBailout);
  2085. this->InsertMove(countAddr, countReg, checkDoBailout);
  2086. this->InsertMove(dobailout, IR::IntConstOpnd::New(0, dobailoutType, m_func, true), checkDoBailout);
  2087. // GetLoopInterpretCount() is a dynamic quantity. It's computed at simple-JIT time here, but that's okay
  2088. // because there would have been sufficient iterations in interpreted mode to get a reasonable value.
  2089. const auto threshold = instr->m_func->GetJnFunction()->GetLoopInterpretCount(head);
  2090. this->InsertCompareBranch(countReg, IR::IntConstOpnd::New(threshold, type, m_func), Js::OpCode::BrLt_A, checkDoBailout, checkDoBailout);
  2091. this->InsertMove(dobailout, IR::IntConstOpnd::New(1, dobailoutType, m_func, true), checkDoBailout);
  2092. // fallthrough
  2093. // Label checkDoBailout (inserted above)
  2094. }
  2095. }
  2096. break;
  2097. case Js::OpCode::ProfiledLoopEnd:
  2098. {
  2099. Assert(m_func->DoSimpleJitDynamicProfile());
  2100. // This is set up in IRBuilding
  2101. Assert(instr->GetSrc1());
  2102. IR::Opnd* savedFlags = instr->UnlinkSrc1();
  2103. m_lowererMD.LoadHelperArgument(instr, savedFlags);
  2104. m_lowererMD.LoadHelperArgument(instr, IR::Opnd::CreateUint32Opnd(instr->AsJitProfilingInstr()->loopNumber, m_func));
  2105. m_lowererMD.LoadHelperArgument(instr, IR::Opnd::CreateFramePointerOpnd(m_func));
  2106. instr->SetSrc1(IR::HelperCallOpnd::New(IR::HelperSimpleRecordLoopImplicitCallFlags, m_func));
  2107. m_lowererMD.LowerCall(instr, 0);
  2108. }
  2109. break;
  2110. case Js::OpCode::InitLoopBodyCount:
  2111. Assert(this->m_func->IsLoopBody());
  2112. instr->SetSrc1(IR::IntConstOpnd::New(0, TyUint32, this->m_func));
  2113. this->m_lowererMD.ChangeToAssign(instr);
  2114. break;
  2115. case Js::OpCode::StLoopBodyCount:
  2116. Assert(this->m_func->IsLoopBody());
  2117. this->LowerStLoopBodyCount(instr);
  2118. break;
  2119. case Js::OpCode::IncrLoopBodyCount:
  2120. Assert(this->m_func->IsLoopBody());
  2121. instr->m_opcode = Js::OpCode::Add_I4;
  2122. instr->SetSrc2(IR::IntConstOpnd::New(1, TyUint32, this->m_func));
  2123. this->m_lowererMD.EmitInt4Instr(instr);
  2124. break;
  2125. #if !FLOATVAR
  2126. case Js::OpCode::StSlotBoxTemp:
  2127. this->LowerStSlotBoxTemp(instr);
  2128. break;
  2129. #endif
  2130. case Js::OpCode::LdSlot:
  2131. case Js::OpCode::LdSlotArr:
  2132. {
  2133. Js::ProfileId profileId;
  2134. IR::Instr *profileBeforeInstr;
  2135. if(instr->IsJitProfilingInstr())
  2136. {
  2137. profileId = instr->AsJitProfilingInstr()->profileId;
  2138. Assert(profileId != Js::Constants::NoProfileId);
  2139. profileBeforeInstr = instr->m_next;
  2140. }
  2141. else
  2142. {
  2143. profileId = Js::Constants::NoProfileId;
  2144. profileBeforeInstr = nullptr;
  2145. }
  2146. this->LowerLdSlot(instr);
  2147. if(profileId != Js::Constants::NoProfileId)
  2148. {
  2149. LowerProfileLdSlot(instr->GetDst(), instr->m_func, profileId, profileBeforeInstr);
  2150. }
  2151. break;
  2152. }
  2153. case Js::OpCode::LdAsmJsSlot:
  2154. this->LowerLdSlot(instr);
  2155. break;
  2156. case Js::OpCode::StAsmJsSlot:
  2157. this->LowerStSlot(instr);
  2158. break;
  2159. case Js::OpCode::ChkUndecl:
  2160. instrPrev = this->LowerChkUndecl(instr);
  2161. break;
  2162. case Js::OpCode::LdArrHead:
  2163. this->LowerLdArrHead(instr);
  2164. break;
  2165. case Js::OpCode::StElemC:
  2166. case Js::OpCode::StArrSegElemC:
  2167. this->LowerStElemC(instr);
  2168. break;
  2169. case Js::OpCode::LdEnv:
  2170. instrPrev = this->LowerLdEnv(instr);
  2171. break;
  2172. case Js::OpCode::LdAsmJsEnv:
  2173. instrPrev = this->LowerLdAsmJsEnv(instr);
  2174. break;
  2175. case Js::OpCode::LdElemUndef:
  2176. this->LowerLdElemUndef(instr);
  2177. break;
  2178. case Js::OpCode::LdElemUndefScoped:
  2179. this->LowerElementUndefinedScopedMem(instr, IR::HelperOp_LdElemUndefScoped);
  2180. break;
  2181. case Js::OpCode::EnsureNoRootFld:
  2182. this->LowerElementUndefined(instr, IR::HelperOp_EnsureNoRootProperty);
  2183. break;
  2184. case Js::OpCode::EnsureNoRootRedeclFld:
  2185. this->LowerElementUndefined(instr, IR::HelperOp_EnsureNoRootRedeclProperty);
  2186. break;
  2187. case Js::OpCode::ScopedEnsureNoRedeclFld:
  2188. this->LowerElementUndefinedScoped(instr, IR::HelperOp_EnsureNoRedeclPropertyScoped);
  2189. break;
  2190. case Js::OpCode::LdFuncExpr:
  2191. // src = function Expression
  2192. m_lowererMD.LoadFuncExpression(instr);
  2193. this->GenerateGetCurrentFunctionObject(instr);
  2194. break;
  2195. case Js::OpCode::LdNewTarget:
  2196. this->GenerateLoadNewTarget(instr);
  2197. break;
  2198. case Js::OpCode::ChkNewCallFlag:
  2199. this->GenerateCheckForCallFlagNew(instr);
  2200. break;
  2201. case Js::OpCode::StFuncExpr:
  2202. // object.propid = src
  2203. LowerStFld(instr, IR::HelperOp_StFunctionExpression, IR::HelperOp_StFunctionExpression, false);
  2204. break;
  2205. case Js::OpCode::InitLetFld:
  2206. case Js::OpCode::InitRootLetFld:
  2207. LowerStFld(instr, IR::HelperOp_InitLetFld, IR::HelperOp_InitLetFld, false);
  2208. break;
  2209. case Js::OpCode::InitConstFld:
  2210. case Js::OpCode::InitRootConstFld:
  2211. LowerStFld(instr, IR::HelperOp_InitConstFld, IR::HelperOp_InitConstFld, false);
  2212. break;
  2213. case Js::OpCode::InitUndeclRootLetFld:
  2214. LowerElementUndefined(instr, IR::HelperOp_InitUndeclRootLetFld);
  2215. break;
  2216. case Js::OpCode::InitUndeclRootConstFld:
  2217. LowerElementUndefined(instr, IR::HelperOp_InitUndeclRootConstFld);
  2218. break;
  2219. case Js::OpCode::InitUndeclConsoleLetFld:
  2220. LowerElementUndefined(instr, IR::HelperOp_InitUndeclConsoleLetFld);
  2221. break;
  2222. case Js::OpCode::InitUndeclConsoleConstFld:
  2223. LowerElementUndefined(instr, IR::HelperOp_InitUndeclConsoleConstFld);
  2224. break;
  2225. case Js::OpCode::InitClassMember:
  2226. LowerStFld(instr, IR::HelperOp_InitClassMember, IR::HelperOp_InitClassMember, false);
  2227. break;
  2228. case Js::OpCode::InitClassMemberComputedName:
  2229. instrPrev = this->LowerStElemI(instr, Js::PropertyOperation_None, false, IR::HelperOp_InitClassMemberComputedName);
  2230. break;
  2231. case Js::OpCode::InitClassMemberGetComputedName:
  2232. instrPrev = this->LowerStElemI(instr, Js::PropertyOperation_None, false, IR::HelperOp_InitClassMemberGetComputedName);
  2233. break;
  2234. case Js::OpCode::InitClassMemberSetComputedName:
  2235. instrPrev = this->LowerStElemI(instr, Js::PropertyOperation_None, false, IR::HelperOp_InitClassMemberSetComputedName);
  2236. break;
  2237. case Js::OpCode::InitClassMemberGet:
  2238. instrPrev = this->LowerStFld(instr, IR::HelperOp_InitClassMemberGet, IR::HelperOp_InitClassMemberGet, false);
  2239. break;
  2240. case Js::OpCode::InitClassMemberSet:
  2241. instrPrev = this->LowerStFld(instr, IR::HelperOp_InitClassMemberSet, IR::HelperOp_InitClassMemberSet, false);
  2242. break;
  2243. case Js::OpCode::NewStackFrameDisplay:
  2244. this->LowerLdFrameDisplay(instr, m_func->DoStackFrameDisplay());
  2245. break;
  2246. case Js::OpCode::LdFrameDisplay:
  2247. this->LowerLdFrameDisplay(instr, false);
  2248. break;
  2249. case Js::OpCode::LdInnerFrameDisplay:
  2250. this->LowerLdInnerFrameDisplay(instr);
  2251. break;
  2252. case Js::OpCode::Throw:
  2253. case Js::OpCode::InlineThrow:
  2254. case Js::OpCode::EHThrow:
  2255. this->LowerUnaryHelperMem(instr, IR::HelperOp_Throw);
  2256. break;
  2257. case Js::OpCode::TryCatch:
  2258. instrPrev = this->LowerTry(instr, true /*try-catch*/);
  2259. break;
  2260. case Js::OpCode::TryFinally:
  2261. instrPrev = this->LowerTry(instr, false /*try-finally*/);
  2262. break;
  2263. case Js::OpCode::Catch:
  2264. instrPrev = m_lowererMD.LowerCatch(instr);
  2265. break;
  2266. case Js::OpCode::LeaveNull:
  2267. instrPrev = m_lowererMD.LowerLeaveNull(instr);
  2268. break;
  2269. case Js::OpCode::Leave:
  2270. if (this->m_func->HasTry() && this->m_func->DoOptimizeTryCatch())
  2271. {
  2272. // Required in Register Allocator to mark region boundaries
  2273. break;
  2274. }
  2275. instrPrev = m_lowererMD.LowerLeave(instr, instr->AsBranchInstr()->GetTarget(), false /*fromFinalLower*/, instr->AsBranchInstr()->m_isOrphanedLeave);
  2276. break;
  2277. case Js::OpCode::BailOnException:
  2278. instrPrev = this->LowerBailOnException(instr);
  2279. break;
  2280. case Js::OpCode::RuntimeTypeError:
  2281. case Js::OpCode::InlineRuntimeTypeError:
  2282. this->LowerUnaryHelperMem(instr, IR::HelperOp_RuntimeTypeError);
  2283. break;
  2284. case Js::OpCode::RuntimeReferenceError:
  2285. case Js::OpCode::InlineRuntimeReferenceError:
  2286. this->LowerUnaryHelperMem(instr, IR::HelperOp_RuntimeReferenceError);
  2287. break;
  2288. case Js::OpCode::Break:
  2289. // Inline breakpoint: for now do nothing.
  2290. break;
  2291. case Js::OpCode::Nop:
  2292. // This may need support for debugging the JIT, but for now just remove the instruction.
  2293. instr->Remove();
  2294. break;
  2295. case Js::OpCode::Unused:
  2296. // Currently Unused is used with ScopedLdInst to keep the second dst alive, but we don't need to lower it.
  2297. instr->Remove();
  2298. break;
  2299. case Js::OpCode::StatementBoundary:
  2300. // This instruction is merely to help convey source info through the IR
  2301. // and eventually generate the nativeOffset maps.
  2302. break;
  2303. case Js::OpCode::BailOnNotPolymorphicInlinee:
  2304. instrPrev = LowerBailOnNotPolymorphicInlinee(instr);
  2305. break;
  2306. case Js::OpCode::BailOnNoSimdTypeSpec:
  2307. case Js::OpCode::BailOnNoProfile:
  2308. this->GenerateBailOut(instr, nullptr, nullptr);
  2309. break;
  2310. case Js::OpCode::BailOnNotSpreadable:
  2311. instrPrev = this->LowerBailOnNotSpreadable(instr);
  2312. break;
  2313. case Js::OpCode::BailOnNotStackArgs:
  2314. instrPrev = this->LowerBailOnNotStackArgs(instr);
  2315. break;
  2316. case Js::OpCode::BailOnEqual:
  2317. case Js::OpCode::BailOnNotEqual:
  2318. instrPrev = this->LowerBailOnEqualOrNotEqual(instr);
  2319. break;
  2320. case Js::OpCode::BailOnNegative:
  2321. LowerBailOnNegative(instr);
  2322. break;
  2323. case Js::OpCode::BailForDebugger:
  2324. instrPrev = this->LowerBailForDebugger(instr);
  2325. break;
  2326. case Js::OpCode::BailOnNotObject:
  2327. instrPrev = this->LowerBailOnNotObject(instr);
  2328. break;
  2329. case Js::OpCode::BailOnNotBuiltIn:
  2330. instrPrev = this->LowerBailOnNotBuiltIn(instr);
  2331. break;
  2332. case Js::OpCode::BailOnNotArray:
  2333. {
  2334. IR::Instr *bailOnNotArray, *bailOnMissingValue;
  2335. SplitBailOnNotArray(instr, &bailOnNotArray, &bailOnMissingValue);
  2336. IR::RegOpnd *const arrayOpnd = LowerBailOnNotArray(bailOnNotArray);
  2337. if(bailOnMissingValue)
  2338. {
  2339. LowerBailOnMissingValue(bailOnMissingValue, arrayOpnd);
  2340. }
  2341. break;
  2342. }
  2343. case Js::OpCode::BoundCheck:
  2344. case Js::OpCode::UnsignedBoundCheck:
  2345. LowerBoundCheck(instr);
  2346. break;
  2347. case Js::OpCode::BailTarget:
  2348. instrPrev = this->LowerBailTarget(instr);
  2349. break;
  2350. case Js::OpCode::InlineeStart:
  2351. this->LowerInlineeStart(instr);
  2352. break;
  2353. case Js::OpCode::EndCallForPolymorphicInlinee:
  2354. instr->Remove();
  2355. break;
  2356. case Js::OpCode::InlineeEnd:
  2357. this->LowerInlineeEnd(instr);
  2358. break;
  2359. case Js::OpCode::InlineBuiltInEnd:
  2360. case Js::OpCode::InlineNonTrackingBuiltInEnd:
  2361. this->LowerInlineBuiltIn(instr);
  2362. break;
  2363. case Js::OpCode::ExtendArg_A:
  2364. if (instr->GetSrc1()->IsRegOpnd())
  2365. {
  2366. IR::RegOpnd *src1 = instr->GetSrc1()->AsRegOpnd();
  2367. this->addToLiveOnBackEdgeSyms->Clear(src1->m_sym->m_id);
  2368. }
  2369. instr->Remove();
  2370. break;
  2371. case Js::OpCode::InlineBuiltInStart:
  2372. case Js::OpCode::BytecodeArgOutUse:
  2373. case Js::OpCode::ArgOut_A_InlineBuiltIn:
  2374. instr->Remove();
  2375. break;
  2376. case Js::OpCode::DeadBrEqual:
  2377. this->LowerBinaryHelperMem(instr, IR::HelperOp_Equal);
  2378. break;
  2379. case Js::OpCode::DeadBrSrEqual:
  2380. this->LowerBinaryHelperMem(instr, IR::HelperOp_StrictEqual);
  2381. break;
  2382. case Js::OpCode::DeadBrRelational:
  2383. this->LowerBinaryHelperMem(instr, IR::HelperOp_Greater);
  2384. break;
  2385. case Js::OpCode::DeadBrOnHasProperty:
  2386. this->LowerUnaryHelperMem(instr, IR::HelperOp_HasProperty);
  2387. break;
  2388. case Js::OpCode::DeletedNonHelperBranch:
  2389. break;
  2390. case Js::OpCode::InitClass:
  2391. instrPrev = this->LowerInitClass(instr);
  2392. break;
  2393. case Js::OpCode::NewConcatStrMulti:
  2394. this->LowerNewConcatStrMulti(instr);
  2395. break;
  2396. case Js::OpCode::NewConcatStrMultiBE:
  2397. this->LowerNewConcatStrMultiBE(instr);
  2398. break;
  2399. case Js::OpCode::SetConcatStrMultiItem:
  2400. this->LowerSetConcatStrMultiItem(instr);
  2401. break;
  2402. case Js::OpCode::SetConcatStrMultiItemBE:
  2403. Assert(instr->GetSrc1()->IsRegOpnd());
  2404. this->addToLiveOnBackEdgeSyms->Clear(instr->GetSrc1()->GetStackSym()->m_id);
  2405. // code corresponding to it should already have been generated while lowering NewConcatStrMultiBE
  2406. instr->Remove();
  2407. break;
  2408. case Js::OpCode::Conv_Str:
  2409. this->LowerConvStr(instr);
  2410. break;
  2411. case Js::OpCode::Coerse_Str:
  2412. this->LowerCoerseStr(instr);
  2413. break;
  2414. case Js::OpCode::Coerse_StrOrRegex:
  2415. this->LowerCoerseStrOrRegex(instr);
  2416. break;
  2417. case Js::OpCode::Coerse_Regex:
  2418. this->LowerCoerseRegex(instr);
  2419. break;
  2420. case Js::OpCode::Conv_PrimStr:
  2421. this->LowerConvPrimStr(instr);
  2422. break;
  2423. case Js::OpCode::ObjectFreeze:
  2424. this->LowerUnaryHelper(instr, IR::HelperOP_Freeze);
  2425. break;
  2426. case Js::OpCode::ClearAttributes:
  2427. this->LowerBinaryHelper(instr, IR::HelperOP_ClearAttributes);
  2428. break;
  2429. case Js::OpCode::SpreadArrayLiteral:
  2430. this->LowerSpreadArrayLiteral(instr);
  2431. break;
  2432. case Js::OpCode::CallIExtended:
  2433. {
  2434. // Currently, the only use for CallIExtended is a call that uses spread.
  2435. Assert(IsSpreadCall(instr));
  2436. instrPrev = this->LowerSpreadCall(instr, Js::CallFlags_None);
  2437. break;
  2438. }
  2439. case Js::OpCode::CallIExtendedNew:
  2440. {
  2441. // Currently, the only use for CallIExtended is a call that uses spread.
  2442. Assert(IsSpreadCall(instr));
  2443. instrPrev = this->LowerSpreadCall(instr, Js::CallFlags_New);
  2444. break;
  2445. }
  2446. case Js::OpCode::CallIExtendedNewTargetNew:
  2447. {
  2448. // Currently, the only use for CallIExtended is a call that uses spread.
  2449. Assert(IsSpreadCall(instr));
  2450. instrPrev = this->LowerSpreadCall(instr, (Js::CallFlags)(Js::CallFlags_New | Js::CallFlags_ExtraArg | Js::CallFlags_NewTarget));
  2451. break;
  2452. }
  2453. case Js::OpCode::LdSpreadIndices:
  2454. instr->Remove();
  2455. break;
  2456. case Js::OpCode::LdSuper:
  2457. instrPrev = m_lowererMD.LowerLdSuper(instr, IR::HelperLdSuper);
  2458. break;
  2459. case Js::OpCode::LdSuperCtor:
  2460. instrPrev = m_lowererMD.LowerLdSuper(instr, IR::HelperLdSuperCtor);
  2461. break;
  2462. case Js::OpCode::ScopedLdSuper:
  2463. instrPrev = m_lowererMD.LowerLdSuper(instr, IR::HelperScopedLdSuper);
  2464. break;
  2465. case Js::OpCode::ScopedLdSuperCtor:
  2466. instrPrev = m_lowererMD.LowerLdSuper(instr, IR::HelperScopedLdSuperCtor);
  2467. break;
  2468. case Js::OpCode::SetHomeObj:
  2469. {
  2470. IR::Opnd *src2Opnd = instr->UnlinkSrc2();
  2471. IR::Opnd *src1Opnd = instr->UnlinkSrc1();
  2472. m_lowererMD.LoadHelperArgument(instr, src2Opnd);
  2473. m_lowererMD.LoadHelperArgument(instr, src1Opnd);
  2474. m_lowererMD.ChangeToHelperCall(instr, IR::HelperSetHomeObj);
  2475. break;
  2476. }
  2477. case Js::OpCode::SetComputedNameVar:
  2478. {
  2479. IR::Opnd *src2Opnd = instr->UnlinkSrc2();
  2480. IR::Opnd *src1Opnd = instr->UnlinkSrc1();
  2481. m_lowererMD.LoadHelperArgument(instr, src2Opnd);
  2482. m_lowererMD.LoadHelperArgument(instr, src1Opnd);
  2483. m_lowererMD.ChangeToHelperCall(instr, IR::HelperSetComputedNameVar);
  2484. break;
  2485. }
  2486. case Js::OpCode::InlineeMetaArg:
  2487. {
  2488. m_lowererMD.ChangeToAssign(instr);
  2489. break;
  2490. }
  2491. case Js::OpCode::Yield:
  2492. {
  2493. instr->FreeSrc1(); // Source is not actually used by the backend other than to calculate lifetime
  2494. IR::Opnd* dstOpnd = instr->UnlinkDst();
  2495. // prm2 is the ResumeYieldData pointer per calling convention established in JavascriptGenerator::CallGenerator
  2496. // This is the value the bytecode expects to be in the dst register of the Yield opcode after resumption.
  2497. // Load it here after the bail-in.
  2498. StackSym *resumeYieldDataSym = StackSym::NewParamSlotSym(2, m_func);
  2499. m_func->SetArgOffset(resumeYieldDataSym, (LowererMD::GetFormalParamOffset() + 1) * MachPtr);
  2500. IR::SymOpnd * resumeYieldDataOpnd = IR::SymOpnd::New(resumeYieldDataSym, TyMachPtr, m_func);
  2501. AssertMsg(instr->m_next->IsLabelInstr(), "Expect the resume label to immediately follow Yield instruction");
  2502. m_lowererMD.CreateAssign(dstOpnd, resumeYieldDataOpnd, instr->m_next->m_next);
  2503. GenerateBailOut(instr);
  2504. break;
  2505. }
  2506. case Js::OpCode::ResumeYield:
  2507. case Js::OpCode::ResumeYieldStar:
  2508. {
  2509. IR::Opnd *srcOpnd1 = instr->UnlinkSrc1();
  2510. IR::Opnd *srcOpnd2 = instr->m_opcode == Js::OpCode::ResumeYieldStar ? instr->UnlinkSrc2() : IR::AddrOpnd::NewNull(m_func);
  2511. m_lowererMD.LoadHelperArgument(instr, srcOpnd2);
  2512. m_lowererMD.LoadHelperArgument(instr, srcOpnd1);
  2513. m_lowererMD.ChangeToHelperCall(instr, IR::HelperResumeYield);
  2514. break;
  2515. }
  2516. case Js::OpCode::GeneratorResumeJumpTable:
  2517. {
  2518. // Lowered in LowerPrologEpilog so that the jumps introduced are not considered to be part of the flow for the RegAlloc phase.
  2519. // Introduce a BailOutNoSave label if there were yield points that were elided due to optimizations. They could still be hit
  2520. // if an active generator object had been paused at such a yield point when the function body was JITed. So safe guard such a
  2521. // case by having the native code simply jump back to the interpreter for such yield points.
  2522. IR::LabelInstr *bailOutNoSaveLabel = nullptr;
  2523. m_func->MapUntilYieldOffsetResumeLabels([this, &bailOutNoSaveLabel](int, const YieldOffsetResumeLabel& yorl)
  2524. {
  2525. if (yorl.Second() == nullptr)
  2526. {
  2527. if (bailOutNoSaveLabel == nullptr)
  2528. {
  2529. bailOutNoSaveLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  2530. }
  2531. return true;
  2532. }
  2533. return false;
  2534. });
  2535. // Insert the bailoutnosave label somewhere along with a call to BailOutNoSave helper
  2536. if (bailOutNoSaveLabel != nullptr)
  2537. {
  2538. IR::Instr * exitPrevInstr = this->m_func->m_exitInstr->m_prev;
  2539. IR::LabelInstr * exitTargetInstr;
  2540. if (exitPrevInstr->IsLabelInstr())
  2541. {
  2542. exitTargetInstr = exitPrevInstr->AsLabelInstr();
  2543. exitPrevInstr = exitPrevInstr->m_prev;
  2544. }
  2545. else
  2546. {
  2547. exitTargetInstr = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, false);
  2548. exitPrevInstr->InsertAfter(exitTargetInstr);
  2549. }
  2550. bailOutNoSaveLabel->m_hasNonBranchRef = true;
  2551. bailOutNoSaveLabel->isOpHelper = true;
  2552. IR::Instr* bailOutCall = IR::Instr::New(Js::OpCode::Call, m_func);
  2553. exitPrevInstr->InsertAfter(bailOutCall);
  2554. exitPrevInstr->InsertAfter(bailOutNoSaveLabel);
  2555. exitPrevInstr->InsertAfter(IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, exitTargetInstr, m_func));
  2556. IR::RegOpnd * frameRegOpnd = IR::RegOpnd::New(nullptr, LowererMD::GetRegFramePointer(), TyMachPtr, m_func);
  2557. m_lowererMD.LoadHelperArgument(bailOutCall, frameRegOpnd);
  2558. m_lowererMD.ChangeToHelperCall(bailOutCall, IR::HelperNoSaveRegistersBailOutForElidedYield);
  2559. m_func->m_bailOutNoSaveLabel = bailOutNoSaveLabel;
  2560. }
  2561. break;
  2562. }
  2563. case Js::OpCode::AsyncSpawn:
  2564. this->LowerBinaryHelperMem(instr, IR::HelperAsyncSpawn);
  2565. break;
  2566. case Js::OpCode::FrameDisplayCheck:
  2567. instrPrev = this->LowerFrameDisplayCheck(instr);
  2568. break;
  2569. case Js::OpCode::SlotArrayCheck:
  2570. instrPrev = this->LowerSlotArrayCheck(instr);
  2571. break;
  2572. default:
  2573. #if defined(_M_IX86) || defined(_M_X64)
  2574. if (IsSimd128Opcode(instr->m_opcode))
  2575. {
  2576. instrPrev = m_lowererMD.Simd128Instruction(instr);
  2577. break;
  2578. }
  2579. #endif
  2580. AssertMsg(instr->IsLowered(), "Unknown opcode");
  2581. if(!instr->IsLowered())
  2582. {
  2583. Fatal();
  2584. }
  2585. break;
  2586. }
  2587. #if DBG
  2588. LegalizeVerifyRange(instrPrev ? instrPrev->m_next : instrStart,
  2589. verifyLegalizeInstrNext ? verifyLegalizeInstrNext->m_prev : nullptr);
  2590. #endif
  2591. } NEXT_INSTR_BACKWARD_EDITING_IN_RANGE;
  2592. Assert(this->outerMostLoopLabel == nullptr);
  2593. }
  2594. IR::Instr *
  2595. Lowerer::LoadFunctionBody(IR::Instr * instr)
  2596. {
  2597. return m_lowererMD.LoadHelperArgument(instr, LoadFunctionBodyOpnd(instr));
  2598. }
  2599. IR::Instr *
  2600. Lowerer::LoadScriptContext(IR::Instr * instr)
  2601. {
  2602. return m_lowererMD.LoadHelperArgument(instr, LoadScriptContextOpnd(instr));
  2603. }
  2604. IR::Opnd *
  2605. Lowerer::LoadFunctionBodyOpnd(IR::Instr * instr)
  2606. {
  2607. return IR::AddrOpnd::New(instr->m_func->GetJnFunction(), IR::AddrOpndKindDynamicFunctionBody, instr->m_func);
  2608. }
  2609. IR::Opnd *
  2610. Lowerer::LoadScriptContextOpnd(IR::Instr * instr)
  2611. {
  2612. return IR::AddrOpnd::New(this->m_func->GetScriptContext(), IR::AddrOpndKindDynamicScriptContext, this->m_func);
  2613. }
  2614. IR::Opnd *
  2615. Lowerer::LoadScriptContextValueOpnd(IR::Instr * instr, ScriptContextValue valueType)
  2616. {
  2617. Js::ScriptContext *scriptContext = instr->m_func->GetScriptContext();
  2618. switch (valueType)
  2619. {
  2620. case ScriptContextValue::ScriptContextNumberAllocator:
  2621. return IR::AddrOpnd::New(scriptContext->GetNumberAllocator(), IR::AddrOpndKindDynamicMisc, instr->m_func);
  2622. case ScriptContextValue::ScriptContextRecycler:
  2623. return IR::AddrOpnd::New(scriptContext->GetRecycler(), IR::AddrOpndKindDynamicMisc, instr->m_func);
  2624. default:
  2625. Assert(false);
  2626. return nullptr;
  2627. }
  2628. }
  2629. IR::Opnd *
  2630. Lowerer::LoadLibraryValueOpnd(IR::Instr * instr, LibraryValue valueType, RegNum regNum)
  2631. {
  2632. Js::ScriptContext *scriptContext = instr->m_func->GetScriptContext();
  2633. switch (valueType)
  2634. {
  2635. case LibraryValue::ValueEmptyString:
  2636. return IR::AddrOpnd::New(scriptContext->GetLibrary()->GetEmptyString(), IR::AddrOpndKindDynamicVar, instr->m_func, true);
  2637. case LibraryValue::ValueUndeclBlockVar:
  2638. return IR::AddrOpnd::New(scriptContext->GetLibrary()->GetUndeclBlockVar(), IR::AddrOpndKindDynamicVar, instr->m_func, true);
  2639. case LibraryValue::ValueUndefined:
  2640. return IR::AddrOpnd::New(scriptContext->GetLibrary()->GetUndefined(), IR::AddrOpndKindDynamicVar, instr->m_func, true);
  2641. case LibraryValue::ValueNull:
  2642. return IR::AddrOpnd::New(scriptContext->GetLibrary()->GetNull(), IR::AddrOpndKindDynamicVar, instr->m_func, true);
  2643. case LibraryValue::ValueTrue:
  2644. return IR::AddrOpnd::New(scriptContext->GetLibrary()->GetTrue(), IR::AddrOpndKindDynamicVar, instr->m_func, true);
  2645. case LibraryValue::ValueFalse:
  2646. return IR::AddrOpnd::New(scriptContext->GetLibrary()->GetFalse(), IR::AddrOpndKindDynamicVar, instr->m_func, true);
  2647. case LibraryValue::ValueNegativeZero:
  2648. return IR::AddrOpnd::New(scriptContext->GetLibrary()->GetNegativeZero(), IR::AddrOpndKindDynamicVar, instr->m_func, true);
  2649. case LibraryValue::ValueNumberTypeStatic:
  2650. return IR::AddrOpnd::New(scriptContext->GetLibrary()->GetNumberTypeStatic(), IR::AddrOpndKindDynamicType, instr->m_func, true);
  2651. case LibraryValue::ValueStringTypeStatic:
  2652. return IR::AddrOpnd::New(scriptContext->GetLibrary()->GetStringTypeStatic(), IR::AddrOpndKindDynamicType, instr->m_func, true);
  2653. case LibraryValue::ValueObjectType:
  2654. return IR::AddrOpnd::New(scriptContext->GetLibrary()->GetObjectType(), IR::AddrOpndKindDynamicType, instr->m_func);
  2655. case LibraryValue::ValueObjectHeaderInlinedType:
  2656. return IR::AddrOpnd::New(scriptContext->GetLibrary()->GetObjectHeaderInlinedType(), IR::AddrOpndKindDynamicType, instr->m_func);
  2657. case LibraryValue::ValueRegexType:
  2658. return IR::AddrOpnd::New(scriptContext->GetLibrary()->GetRegexType(), IR::AddrOpndKindDynamicType, instr->m_func);
  2659. case LibraryValue::ValueArrayConstructor:
  2660. return IR::AddrOpnd::New(scriptContext->GetLibrary()->GetArrayConstructor(), IR::AddrOpndKindDynamicVar, instr->m_func);
  2661. case LibraryValue::ValueJavascriptArrayType:
  2662. return IR::AddrOpnd::New(Js::JavascriptArray::GetInitialType(scriptContext), IR::AddrOpndKindDynamicType, instr->m_func);
  2663. case LibraryValue::ValueNativeIntArrayType:
  2664. return IR::AddrOpnd::New(Js::JavascriptNativeIntArray::GetInitialType(scriptContext), IR::AddrOpndKindDynamicType, instr->m_func);
  2665. case LibraryValue::ValueNativeFloatArrayType:
  2666. return IR::AddrOpnd::New(Js::JavascriptNativeFloatArray::GetInitialType(scriptContext), IR::AddrOpndKindDynamicType, instr->m_func);
  2667. case LibraryValue::ValueConstructorCacheDefaultInstance:
  2668. return IR::AddrOpnd::New(&Js::ConstructorCache::DefaultInstance, IR::AddrOpndKindDynamicMisc, instr->m_func);
  2669. case LibraryValue::ValueAbsDoubleCst:
  2670. return IR::MemRefOpnd::New((void*)&Js::JavascriptNumber::AbsDoubleCst, TyMachDouble, instr->m_func, IR::AddrOpndKindDynamicDoubleRef);
  2671. case LibraryValue::ValueCharStringCache:
  2672. return IR::AddrOpnd::New((Js::Var)&scriptContext->GetLibrary()->GetCharStringCache(), IR::AddrOpndKindDynamicCharStringCache, instr->m_func);
  2673. default:
  2674. Assert(false);
  2675. return nullptr;
  2676. }
  2677. }
  2678. IR::Opnd *
  2679. Lowerer::LoadVTableValueOpnd(IR::Instr * instr, VTableValue vtableType)
  2680. {
  2681. return IR::AddrOpnd::New((Js::Var)instr->m_func->GetScriptContext()->GetLibrary()->GetVTableAddresses()[vtableType], IR::AddrOpndKindDynamicVtable, this->m_func);
  2682. }
  2683. IR::Opnd *
  2684. Lowerer::LoadOptimizationOverridesValueOpnd(IR::Instr *instr, OptimizationOverridesValue valueType)
  2685. {
  2686. Js::ScriptContext *scriptContext = instr->m_func->GetScriptContext();
  2687. switch (valueType)
  2688. {
  2689. case OptimizationOverridesValue::OptimizationOverridesSideEffects:
  2690. return IR::MemRefOpnd::New(scriptContext->optimizationOverrides.GetAddressOfSideEffects(), TyInt32, instr->m_func);
  2691. case OptimizationOverridesValue::OptimizationOverridesArraySetElementFastPathVtable:
  2692. return IR::MemRefOpnd::New(scriptContext->optimizationOverrides.GetAddressOfArraySetElementFastPathVtable(), TyMachPtr, instr->m_func);
  2693. case OptimizationOverridesValue::OptimizationOverridesIntArraySetElementFastPathVtable:
  2694. return IR::MemRefOpnd::New(scriptContext->optimizationOverrides.GetAddressOfIntArraySetElementFastPathVtable(), TyMachPtr, instr->m_func);
  2695. case OptimizationOverridesValue::OptimizationOverridesFloatArraySetElementFastPathVtable:
  2696. return IR::MemRefOpnd::New(scriptContext->optimizationOverrides.GetAddressOfFloatArraySetElementFastPathVtable(), TyMachPtr, instr->m_func);
  2697. default:
  2698. Assert(false);
  2699. return nullptr;
  2700. }
  2701. }
  2702. IR::Opnd *
  2703. Lowerer::LoadNumberAllocatorValueOpnd(IR::Instr *instr, NumberAllocatorValue valueType)
  2704. {
  2705. Js::ScriptContext *scriptContext = instr->m_func->GetScriptContext();
  2706. bool allowNativeCodeBumpAllocation = scriptContext->GetNumberAllocator()->AllowNativeCodeBumpAllocation();
  2707. switch (valueType)
  2708. {
  2709. case NumberAllocatorValue::NumberAllocatorEndAddress:
  2710. return IR::MemRefOpnd::New(((char *)scriptContext->GetNumberAllocator()) + Js::RecyclerJavascriptNumberAllocator::GetEndAddressOffset(), TyMachPtr, instr->m_func);
  2711. case NumberAllocatorValue::NumberAllocatorFreeObjectList:
  2712. return IR::MemRefOpnd::New(
  2713. ((char *)scriptContext->GetNumberAllocator()) +
  2714. (allowNativeCodeBumpAllocation ? Js::RecyclerJavascriptNumberAllocator::GetFreeObjectListOffset() : Js::RecyclerJavascriptNumberAllocator::GetEndAddressOffset()),
  2715. TyMachPtr, instr->m_func);
  2716. default:
  2717. Assert(false);
  2718. return nullptr;
  2719. }
  2720. }
  2721. IR::Opnd *
  2722. Lowerer::LoadIsInstInlineCacheOpnd(IR::Instr * instr, uint inlineCacheIndex)
  2723. {
  2724. Js::IsInstInlineCache * inlineCache = instr->m_func->GetJnFunction()->GetIsInstInlineCache(inlineCacheIndex);
  2725. return IR::AddrOpnd::New(inlineCache, IR::AddrOpndKindDynamicInlineCache, this->m_func);
  2726. }
  2727. IR::Opnd *
  2728. Lowerer::LoadRuntimeInlineCacheOpnd(IR::Instr * instr, IR::PropertySymOpnd * propertySymOpnd, bool isHelper)
  2729. {
  2730. Assert(propertySymOpnd->m_runtimeInlineCache != nullptr);
  2731. IR::Opnd * inlineCacheOpnd = nullptr;
  2732. if (instr->m_func->GetJnFunction()->GetInlineCachesOnFunctionObject() && !instr->m_func->IsInlinee())
  2733. {
  2734. inlineCacheOpnd = this->GetInlineCacheFromFuncObjectForRuntimeUse(instr, propertySymOpnd, isHelper);
  2735. }
  2736. else
  2737. {
  2738. Js::InlineCache * inlineCache = propertySymOpnd->m_runtimeInlineCache;
  2739. inlineCacheOpnd = IR::AddrOpnd::New(inlineCache, IR::AddrOpndKindDynamicInlineCache, this->m_func, /* dontEncode */ true);
  2740. }
  2741. return inlineCacheOpnd;
  2742. }
  2743. bool
  2744. Lowerer::TryGenerateFastCmSrEq(IR::Instr * instr)
  2745. {
  2746. IR::RegOpnd *srcReg1 = instr->GetSrc1()->IsRegOpnd() ? instr->GetSrc1()->AsRegOpnd() : nullptr;
  2747. IR::RegOpnd *srcReg2 = instr->GetSrc2()->IsRegOpnd() ? instr->GetSrc2()->AsRegOpnd() : nullptr;
  2748. if (srcReg2 && IsConstRegOpnd(srcReg2))
  2749. {
  2750. return m_lowererMD.GenerateFastCmSrEqConst(instr);
  2751. }
  2752. else if (srcReg1 && IsConstRegOpnd(srcReg1))
  2753. {
  2754. instr->SwapOpnds();
  2755. return m_lowererMD.GenerateFastCmSrEqConst(instr);
  2756. }
  2757. else if (srcReg2 && (srcReg2->m_sym->m_isStrConst))
  2758. {
  2759. this->LowerBinaryHelperMem(instr, IR::HelperOP_CmSrEq_String);
  2760. return true;
  2761. }
  2762. else if (srcReg1 && (srcReg1->m_sym->m_isStrConst))
  2763. {
  2764. instr->SwapOpnds();
  2765. this->LowerBinaryHelperMem(instr, IR::HelperOP_CmSrEq_String);
  2766. return true;
  2767. }
  2768. else if (srcReg2 && (srcReg2->m_sym->m_isStrEmpty))
  2769. {
  2770. this->LowerBinaryHelperMem(instr, IR::HelperOP_CmSrEq_EmptyString);
  2771. return true;
  2772. }
  2773. else if (srcReg1 && (srcReg1->m_sym->m_isStrEmpty))
  2774. {
  2775. instr->SwapOpnds();
  2776. this->LowerBinaryHelperMem(instr, IR::HelperOP_CmSrEq_EmptyString);
  2777. return true;
  2778. }
  2779. return false;
  2780. }
  2781. bool
  2782. Lowerer::GenerateFastBrSrEq(IR::Instr * instr, IR::RegOpnd * srcReg1, IR::RegOpnd * srcReg2, IR::Instr ** pInstrPrev, bool noMathFastPath)
  2783. {
  2784. if (srcReg2 && IsConstRegOpnd(srcReg2))
  2785. {
  2786. this->GenerateFastBrConst(instr->AsBranchInstr(), srcReg2->m_sym->GetConstOpnd(), true);
  2787. instr->Remove();
  2788. return true;
  2789. }
  2790. else if (srcReg1 && IsConstRegOpnd(srcReg1))
  2791. {
  2792. instr->SwapOpnds();
  2793. this->GenerateFastBrConst(instr->AsBranchInstr(), srcReg1->m_sym->GetConstOpnd(), true);
  2794. instr->Remove();
  2795. return true;
  2796. }
  2797. else if (srcReg2 && (srcReg2->m_sym->m_isStrConst))
  2798. {
  2799. this->LowerBrCMem(instr, IR::HelperOp_StrictEqualString, noMathFastPath, false);
  2800. return true;
  2801. }
  2802. else if (srcReg1 && (srcReg1->m_sym->m_isStrConst))
  2803. {
  2804. instr->SwapOpnds();
  2805. this->LowerBrCMem(instr, IR::HelperOp_StrictEqualString, noMathFastPath, false);
  2806. return true;
  2807. }
  2808. else if (srcReg2 && (srcReg2->m_sym->m_isStrEmpty))
  2809. {
  2810. this->LowerBrCMem(instr, IR::HelperOp_StrictEqualEmptyString, noMathFastPath, false);
  2811. return true;
  2812. }
  2813. else if (srcReg1 && (srcReg1->m_sym->m_isStrConst))
  2814. {
  2815. instr->SwapOpnds();
  2816. this->LowerBrCMem(instr, IR::HelperOp_StrictEqualEmptyString, noMathFastPath, false);
  2817. return true;
  2818. }
  2819. return false;
  2820. }
  2821. ///----------------------------------------------------------------------------
  2822. ///
  2823. /// Lowerer::GenerateFastBrConst
  2824. ///
  2825. ///----------------------------------------------------------------------------
  2826. IR::BranchInstr *
  2827. Lowerer::GenerateFastBrConst(IR::BranchInstr *branchInstr, IR::Opnd * constOpnd, bool isEqual)
  2828. {
  2829. Assert(constOpnd->IsAddrOpnd() || constOpnd->IsIntConstOpnd());
  2830. //
  2831. // Given:
  2832. // BrSrEq_A $L1, s1, s2
  2833. // where s2 is either 'null', 'undefined', 'true' or 'false'
  2834. //
  2835. // Generate:
  2836. //
  2837. // CMP s1, s2
  2838. // JEQ/JNE $L1
  2839. //
  2840. Assert(this->IsConstRegOpnd(branchInstr->GetSrc2()->AsRegOpnd()));
  2841. IR::Opnd *opnd = branchInstr->GetSrc1();
  2842. if (!opnd->IsRegOpnd())
  2843. {
  2844. IR::RegOpnd *lhsReg = IR::RegOpnd::New(TyVar, m_func);
  2845. LowererMD::CreateAssign(lhsReg, opnd, branchInstr);
  2846. opnd = lhsReg;
  2847. }
  2848. Assert(opnd->IsRegOpnd());
  2849. IR::BranchInstr *newBranch;
  2850. newBranch = InsertCompareBranch(opnd, constOpnd, isEqual ? Js::OpCode::BrEq_A : Js::OpCode::BrNeq_A, branchInstr->GetTarget(), branchInstr);
  2851. return newBranch;
  2852. }
  2853. bool
  2854. Lowerer::TryGenerateFastBrEq(IR::Instr * instr)
  2855. {
  2856. IR::RegOpnd *srcReg1 = instr->GetSrc1()->IsRegOpnd() ? instr->GetSrc1()->AsRegOpnd() : nullptr;
  2857. IR::RegOpnd *srcReg2 = instr->GetSrc2()->IsRegOpnd() ? instr->GetSrc2()->AsRegOpnd() : nullptr;
  2858. bool isConst = false;
  2859. if (srcReg1 && this->IsNullOrUndefRegOpnd(srcReg1))
  2860. {
  2861. instr->SwapOpnds();
  2862. isConst = true;
  2863. }
  2864. // Fast path for == null or == undefined
  2865. // if (src == null || src == undefined)
  2866. if (isConst || srcReg2 && this->IsNullOrUndefRegOpnd(srcReg2))
  2867. {
  2868. IR::BranchInstr *newBranch;
  2869. newBranch = this->GenerateFastBrConst(instr->AsBranchInstr(),
  2870. this->LoadLibraryValueOpnd(instr, LibraryValue::ValueNull),
  2871. true);
  2872. this->GenerateFastBrConst(instr->AsBranchInstr(),
  2873. this->LoadLibraryValueOpnd(instr, LibraryValue::ValueUndefined),
  2874. true);
  2875. instr->Remove();
  2876. return true;
  2877. }
  2878. return false;
  2879. }
  2880. bool
  2881. Lowerer::TryGenerateFastBrNeq(IR::Instr * instr)
  2882. {
  2883. IR::RegOpnd *srcReg1 = instr->GetSrc1()->IsRegOpnd() ? instr->GetSrc1()->AsRegOpnd() : nullptr;
  2884. IR::RegOpnd *srcReg2 = instr->GetSrc2()->IsRegOpnd() ? instr->GetSrc2()->AsRegOpnd() : nullptr;
  2885. bool isConst = false;
  2886. if (srcReg1 && this->IsNullOrUndefRegOpnd(srcReg1))
  2887. {
  2888. instr->SwapOpnds();
  2889. isConst = true;
  2890. }
  2891. // Fast path for != null or != undefined
  2892. // if (src != null && src != undefined)
  2893. //
  2894. // That is:
  2895. // if (src == NULL) goto labelEq
  2896. // if (src != undef) goto target
  2897. // labelEq:
  2898. if (isConst || (srcReg2 && this->IsNullOrUndefRegOpnd(srcReg2)))
  2899. {
  2900. IR::LabelInstr *labelEq = instr->GetOrCreateContinueLabel();
  2901. IR::BranchInstr *newBranch;
  2902. newBranch = this->GenerateFastBrConst(instr->AsBranchInstr(),
  2903. this->LoadLibraryValueOpnd(instr, LibraryValue::ValueNull),
  2904. true);
  2905. newBranch->AsBranchInstr()->SetTarget(labelEq);
  2906. this->GenerateFastBrConst(instr->AsBranchInstr(),
  2907. this->LoadLibraryValueOpnd(instr, LibraryValue::ValueUndefined),
  2908. false);
  2909. instr->Remove();
  2910. return true;
  2911. }
  2912. return false;
  2913. }
  2914. bool
  2915. Lowerer::GenerateFastBrSrNeq(IR::Instr * instr, IR::Instr ** pInstrPrev)
  2916. {
  2917. IR::RegOpnd *srcReg1 = instr->GetSrc1()->IsRegOpnd() ? instr->GetSrc1()->AsRegOpnd() : nullptr;
  2918. IR::RegOpnd *srcReg2 = instr->GetSrc2()->IsRegOpnd() ? instr->GetSrc2()->AsRegOpnd() : nullptr;
  2919. if (srcReg2 && IsConstRegOpnd(srcReg2))
  2920. {
  2921. this->GenerateFastBrConst(instr->AsBranchInstr(), srcReg2->m_sym->GetConstOpnd(), false);
  2922. instr->Remove();
  2923. return true;
  2924. }
  2925. else if (srcReg1 && IsConstRegOpnd(srcReg1))
  2926. {
  2927. instr->SwapOpnds();
  2928. this->GenerateFastBrConst(instr->AsBranchInstr(), srcReg1->m_sym->GetConstOpnd(), false);
  2929. instr->Remove();
  2930. return true;
  2931. }
  2932. return false;
  2933. }
  2934. void
  2935. Lowerer::GenerateDynamicObjectAlloc(IR::Instr * newObjInstr, uint inlineSlotCount, uint slotCount, IR::RegOpnd * newObjDst, IR::Opnd * typeSrc)
  2936. {
  2937. size_t headerAllocSize = sizeof(Js::DynamicObject) + inlineSlotCount * sizeof(Js::Var);
  2938. IR::SymOpnd * tempObjectSymOpnd;
  2939. bool isZeroed = GenerateRecyclerOrMarkTempAlloc(newObjInstr, newObjDst, IR::HelperAllocMemForScObject, headerAllocSize, &tempObjectSymOpnd);
  2940. if (tempObjectSymOpnd && !PHASE_OFF(Js::HoistMarkTempInitPhase, this->m_func) && this->outerMostLoopLabel)
  2941. {
  2942. // Hoist the vtable init to the outer most loop top as it never changes
  2943. InsertMove(tempObjectSymOpnd,
  2944. LoadVTableValueOpnd(this->outerMostLoopLabel, VTableValue::VtableDynamicObject), this->outerMostLoopLabel, false);
  2945. }
  2946. else
  2947. {
  2948. // MOV [newObjDst + offset(vtable)], DynamicObject::vtable
  2949. GenerateMemInit(newObjDst, 0, LoadVTableValueOpnd(newObjInstr, VTableValue::VtableDynamicObject), newObjInstr, isZeroed);
  2950. }
  2951. // MOV [newObjDst + offset(type)], newObjectType
  2952. GenerateMemInit(newObjDst, Js::DynamicObject::GetOffsetOfType(), typeSrc, newObjInstr, isZeroed);
  2953. // CALL JavascriptOperators::AllocMemForVarArray((slotCount - inlineSlotCount) * sizeof(Js::Var))
  2954. if (slotCount > inlineSlotCount)
  2955. {
  2956. size_t auxSlotsAllocSize = (slotCount - inlineSlotCount) * sizeof(Js::Var);
  2957. IR::RegOpnd* auxSlots = IR::RegOpnd::New(TyMachPtr, m_func);
  2958. GenerateRecyclerAllocAligned(IR::HelperAllocMemForVarArray, auxSlotsAllocSize, auxSlots, newObjInstr);
  2959. GenerateMemInit(newObjDst, Js::DynamicObject::GetOffsetOfAuxSlots(), auxSlots, newObjInstr, isZeroed);
  2960. IR::IndirOpnd* newObjAuxSlots = IR::IndirOpnd::New(newObjDst, Js::DynamicObject::GetOffsetOfAuxSlots(), TyMachPtr, m_func);
  2961. this->m_lowererMD.CreateAssign(newObjAuxSlots, auxSlots, newObjInstr);
  2962. }
  2963. else
  2964. {
  2965. GenerateMemInitNull(newObjDst, Js::DynamicObject::GetOffsetOfAuxSlots(), newObjInstr, isZeroed);
  2966. }
  2967. GenerateMemInitNull(newObjDst, Js::DynamicObject::GetOffsetOfObjectArray(), newObjInstr, isZeroed);
  2968. }
  2969. void
  2970. Lowerer::LowerNewScObjectSimple(IR::Instr * instr)
  2971. {
  2972. GenerateDynamicObjectAlloc(
  2973. instr,
  2974. 0,
  2975. 0,
  2976. instr->UnlinkDst()->AsRegOpnd(),
  2977. LoadLibraryValueOpnd(
  2978. instr,
  2979. Js::FunctionBody::DoObjectHeaderInliningForEmptyObjects()
  2980. ? LibraryValue::ValueObjectHeaderInlinedType
  2981. : LibraryValue::ValueObjectType));
  2982. instr->Remove();
  2983. }
  2984. void
  2985. Lowerer::LowerNewScObjectLiteral(IR::Instr *newObjInstr)
  2986. {
  2987. Func * func = m_func;
  2988. IR::IntConstOpnd * literalObjectIdOpnd = newObjInstr->UnlinkSrc2()->AsIntConstOpnd();
  2989. Js::DynamicType ** literalTypeRef = newObjInstr->m_func->GetJnFunction()->GetObjectLiteralTypeRef(literalObjectIdOpnd->AsUint32());
  2990. Js::DynamicType * literalType = *literalTypeRef;
  2991. IR::LabelInstr * helperLabel = nullptr;
  2992. IR::LabelInstr * allocLabel = nullptr;
  2993. IR::Opnd * literalTypeRefOpnd;
  2994. IR::Opnd * literalTypeOpnd;
  2995. IR::Opnd * propertyArrayOpnd;
  2996. IR::IntConstOpnd * propertyArrayIdOpnd = newObjInstr->UnlinkSrc1()->AsIntConstOpnd();
  2997. const Js::PropertyIdArray * propIds = Js::ByteCodeReader::ReadPropertyIdArray(propertyArrayIdOpnd->AsUint32(), newObjInstr->m_func->GetJnFunction());
  2998. Js::ScriptContext *const scriptContext = newObjInstr->m_func->GetJnFunction()->GetScriptContext();
  2999. uint inlineSlotCapacity = Js::JavascriptOperators::GetLiteralInlineSlotCapacity(propIds, scriptContext);
  3000. uint slotCapacity = Js::JavascriptOperators::GetLiteralSlotCapacity(propIds, scriptContext);
  3001. IR::RegOpnd * dstOpnd;
  3002. literalTypeRefOpnd = IR::AddrOpnd::New(literalTypeRef, IR::AddrOpndKindDynamicMisc, this->m_func);
  3003. propertyArrayOpnd = IR::AddrOpnd::New((Js::Var)propIds, IR::AddrOpndKindDynamicMisc, this->m_func);
  3004. if (literalType == nullptr || !literalType->GetIsShared())
  3005. {
  3006. helperLabel = IR::LabelInstr::New(Js::OpCode::Label, func, true);
  3007. allocLabel = IR::LabelInstr::New(Js::OpCode::Label, func);
  3008. literalTypeOpnd = IR::RegOpnd::New(TyMachPtr, func);
  3009. InsertMove(literalTypeOpnd, IR::MemRefOpnd::New(literalTypeRef, TyMachPtr, func), newObjInstr);
  3010. InsertTestBranch(literalTypeOpnd, literalTypeOpnd,
  3011. Js::OpCode::BrEq_A, helperLabel, newObjInstr);
  3012. InsertTestBranch(IR::IndirOpnd::New(literalTypeOpnd->AsRegOpnd(), Js::DynamicType::GetOffsetOfIsShared(), TyInt8, func),
  3013. IR::IntConstOpnd::New(1, TyInt8, func, true), Js::OpCode::BrEq_A, helperLabel, newObjInstr);
  3014. dstOpnd = newObjInstr->GetDst()->AsRegOpnd();
  3015. }
  3016. else
  3017. {
  3018. literalTypeOpnd = IR::AddrOpnd::New(literalType, IR::AddrOpndKindDynamicType, func);
  3019. dstOpnd = newObjInstr->UnlinkDst()->AsRegOpnd();
  3020. Assert(inlineSlotCapacity == literalType->GetTypeHandler()->GetInlineSlotCapacity());
  3021. Assert(slotCapacity == (uint)literalType->GetTypeHandler()->GetSlotCapacity());
  3022. }
  3023. if (helperLabel)
  3024. {
  3025. InsertBranch(Js::OpCode::Br, allocLabel, newObjInstr);
  3026. // Slow path to ensure the type is there
  3027. newObjInstr->InsertBefore(helperLabel);
  3028. IR::HelperCallOpnd * opndHelper = IR::HelperCallOpnd::New(IR::HelperEnsureObjectLiteralType, func);
  3029. m_lowererMD.LoadHelperArgument(newObjInstr, literalTypeRefOpnd);
  3030. m_lowererMD.LoadHelperArgument(newObjInstr, propertyArrayOpnd);
  3031. LoadScriptContext(newObjInstr);
  3032. IR::Instr * ensureTypeInstr = IR::Instr::New(Js::OpCode::Call, literalTypeOpnd, opndHelper, func);
  3033. newObjInstr->InsertBefore(ensureTypeInstr);
  3034. m_lowererMD.LowerCall(ensureTypeInstr, 0);
  3035. newObjInstr->InsertBefore(allocLabel);
  3036. }
  3037. else
  3038. {
  3039. Assert(allocLabel == nullptr);
  3040. }
  3041. // For the next call:
  3042. // inlineSlotCapacity == Number of slots to allocate beyond the DynamicObject header
  3043. // slotCapacity - inlineSlotCapacity == Number of aux slots to allocate
  3044. if(Js::FunctionBody::DoObjectHeaderInliningForObjectLiteral(propIds, scriptContext))
  3045. {
  3046. Assert(inlineSlotCapacity >= Js::DynamicTypeHandler::GetObjectHeaderInlinableSlotCapacity());
  3047. Assert(inlineSlotCapacity == slotCapacity);
  3048. slotCapacity = inlineSlotCapacity -= Js::DynamicTypeHandler::GetObjectHeaderInlinableSlotCapacity();
  3049. }
  3050. GenerateDynamicObjectAlloc(
  3051. newObjInstr,
  3052. inlineSlotCapacity,
  3053. slotCapacity,
  3054. dstOpnd,
  3055. literalTypeOpnd);
  3056. newObjInstr->Remove();
  3057. }
  3058. IR::Instr*
  3059. Lowerer::LowerProfiledNewScArray(IR::JitProfilingInstr* arrInstr)
  3060. {
  3061. IR::Instr *instrPrev = arrInstr->m_prev;
  3062. /*
  3063. JavascriptArray *ProfilingHelpers::ProfiledNewScArray(
  3064. const uint length,
  3065. FunctionBody *const functionBody,
  3066. const ProfileId profileId)
  3067. */
  3068. m_lowererMD.LoadHelperArgument(arrInstr, IR::Opnd::CreateProfileIdOpnd(arrInstr->profileId, m_func));
  3069. m_lowererMD.LoadHelperArgument(arrInstr, CreateFunctionBodyOpnd(arrInstr->m_func));
  3070. m_lowererMD.LoadHelperArgument(arrInstr, arrInstr->UnlinkSrc1());
  3071. arrInstr->SetSrc1(IR::HelperCallOpnd::New(IR::HelperProfiledNewScArray, m_func));
  3072. m_lowererMD.LowerCall(arrInstr, 0);
  3073. return instrPrev;
  3074. }
  3075. IR::Instr *
  3076. Lowerer::LowerNewScArray(IR::Instr *arrInstr)
  3077. {
  3078. if (arrInstr->IsJitProfilingInstr())
  3079. {
  3080. return LowerProfiledNewScArray(arrInstr->AsJitProfilingInstr());
  3081. }
  3082. IR::Instr *instrPrev = arrInstr->m_prev;
  3083. IR::JnHelperMethod helperMethod = IR::HelperScrArr_OP_NewScArray;
  3084. if (arrInstr->IsProfiledInstr() && arrInstr->m_func->HasProfileInfo())
  3085. {
  3086. RecyclerWeakReference<Js::FunctionBody> *weakFuncRef = arrInstr->m_func->GetWeakFuncRef();
  3087. Assert(weakFuncRef);
  3088. Js::ProfileId profileId = static_cast<Js::ProfileId>(arrInstr->AsProfiledInstr()->u.profileId);
  3089. Js::FunctionBody *functionBody = arrInstr->m_func->GetJnFunction();
  3090. Js::DynamicProfileInfo *profileInfo = functionBody->GetAnyDynamicProfileInfo();
  3091. Js::ArrayCallSiteInfo *arrayInfo = profileInfo->GetArrayCallSiteInfo(functionBody, profileId);
  3092. Assert(arrInstr->GetSrc1()->IsConstOpnd());
  3093. GenerateProfiledNewScArrayFastPath(arrInstr, arrayInfo, weakFuncRef, arrInstr->GetSrc1()->AsIntConstOpnd()->AsUint32());
  3094. if (arrInstr->GetDst() && arrInstr->GetDst()->GetValueType().IsLikelyNativeArray())
  3095. {
  3096. m_lowererMD.LoadHelperArgument(arrInstr, IR::AddrOpnd::New(weakFuncRef, IR::AddrOpndKindDynamicFunctionBodyWeakRef, m_func));
  3097. m_lowererMD.LoadHelperArgument(arrInstr, IR::AddrOpnd::New(arrayInfo, IR::AddrOpndKindDynamicArrayCallSiteInfo, m_func));
  3098. helperMethod = IR::HelperScrArr_ProfiledNewScArray;
  3099. }
  3100. }
  3101. LoadScriptContext(arrInstr);
  3102. IR::Opnd *src1Opnd = arrInstr->UnlinkSrc1();
  3103. m_lowererMD.LoadHelperArgument(arrInstr, src1Opnd);
  3104. m_lowererMD.ChangeToHelperCall(arrInstr, helperMethod);
  3105. return instrPrev;
  3106. }
  3107. template <typename ArrayType>
  3108. BOOL Lowerer::IsSmallObject(uint32 length)
  3109. {
  3110. if (ArrayType::HasInlineHeadSegment(length))
  3111. return true;
  3112. uint32 alignedHeadSegmentSize = Js::SparseArraySegment<typename ArrayType::TElement>::GetAlignedSize(length);
  3113. size_t allocSize = sizeof(Js::SparseArraySegment<typename ArrayType::TElement>) + alignedHeadSegmentSize * sizeof(typename ArrayType::TElement);
  3114. return HeapInfo::IsSmallObject(HeapInfo::GetAlignedSizeNoCheck(allocSize));
  3115. }
  3116. void
  3117. Lowerer::GenerateProfiledNewScArrayFastPath(IR::Instr *instr, Js::ArrayCallSiteInfo * arrayInfo, RecyclerWeakReference<Js::FunctionBody> * weakFuncRef, uint32 length)
  3118. {
  3119. if (PHASE_OFF(Js::ArrayCtorFastPathPhase, m_func) || CONFIG_FLAG(ForceES5Array))
  3120. {
  3121. return;
  3122. }
  3123. Func * func = this->m_func;
  3124. IR::LabelInstr * helperLabel = IR::LabelInstr::New(Js::OpCode::Label, func, true);
  3125. uint32 size = length;
  3126. bool isZeroed;
  3127. IR::RegOpnd *dstOpnd = instr->GetDst()->AsRegOpnd();
  3128. IR::RegOpnd *headOpnd;
  3129. uint32 i = length;
  3130. if (instr->GetDst() && instr->GetDst()->GetValueType().IsLikelyNativeIntArray())
  3131. {
  3132. if (!IsSmallObject<Js::JavascriptNativeIntArray>(length))
  3133. {
  3134. return;
  3135. }
  3136. GenerateArrayInfoIsNativeIntArrayTest(instr, arrayInfo, helperLabel);
  3137. Assert(Js::JavascriptNativeIntArray::GetOffsetOfArrayFlags() + sizeof(uint16) == Js::JavascriptNativeIntArray::GetOffsetOfArrayCallSiteIndex());
  3138. headOpnd = GenerateArrayAlloc<Js::JavascriptNativeIntArray>(instr, &size, arrayInfo, &isZeroed);
  3139. const IR::AutoReuseOpnd autoReuseHeadOpnd(headOpnd, func);
  3140. GenerateMemInit(dstOpnd, Js::JavascriptNativeIntArray::GetOffsetOfWeakFuncRef(), IR::AddrOpnd::New(weakFuncRef, IR::AddrOpndKindDynamicFunctionBodyWeakRef, m_func), instr, isZeroed);
  3141. for (; i < size; i++)
  3142. {
  3143. GenerateMemInit(headOpnd, sizeof(Js::SparseArraySegmentBase) + i * sizeof(int32),
  3144. Js::JavascriptNativeIntArray::MissingItem, instr, isZeroed);
  3145. }
  3146. }
  3147. else if (instr->GetDst() && instr->GetDst()->GetValueType().IsLikelyNativeFloatArray())
  3148. {
  3149. if (!IsSmallObject<Js::JavascriptNativeFloatArray>(length))
  3150. {
  3151. return;
  3152. }
  3153. GenerateArrayInfoIsNativeFloatAndNotIntArrayTest(instr, arrayInfo, helperLabel);
  3154. Assert(Js::JavascriptNativeFloatArray::GetOffsetOfArrayFlags() + sizeof(uint16) == Js::JavascriptNativeFloatArray::GetOffsetOfArrayCallSiteIndex());
  3155. headOpnd = GenerateArrayAlloc<Js::JavascriptNativeFloatArray>(instr, &size, arrayInfo, &isZeroed);
  3156. const IR::AutoReuseOpnd autoReuseHeadOpnd(headOpnd, func);
  3157. GenerateMemInit(dstOpnd, Js::JavascriptNativeFloatArray::GetOffsetOfWeakFuncRef(), IR::AddrOpnd::New(weakFuncRef, IR::AddrOpndKindDynamicFunctionBodyWeakRef, m_func), instr, isZeroed);
  3158. // Js::JavascriptArray::MissingItem is a Var, so it may be 32-bit or 64 bit.
  3159. uint const offsetStart = sizeof(Js::SparseArraySegmentBase);
  3160. uint const missingItemCount = size * sizeof(double) / sizeof(Js::JavascriptArray::MissingItem);
  3161. i = i * sizeof(double) / sizeof(Js::JavascriptArray::MissingItem);
  3162. for (; i < missingItemCount; i++)
  3163. {
  3164. GenerateMemInit(
  3165. headOpnd, offsetStart + i * sizeof(Js::JavascriptArray::MissingItem),
  3166. IR::AddrOpnd::New(Js::JavascriptArray::MissingItem, IR::AddrOpndKindConstant, m_func, true),
  3167. instr, isZeroed);
  3168. }
  3169. }
  3170. else
  3171. {
  3172. if (!IsSmallObject<Js::JavascriptArray>(length))
  3173. {
  3174. return;
  3175. }
  3176. uint const offsetStart = sizeof(Js::SparseArraySegmentBase);
  3177. headOpnd = GenerateArrayAlloc<Js::JavascriptArray>(instr, &size, arrayInfo, &isZeroed);
  3178. const IR::AutoReuseOpnd autoReuseHeadOpnd(headOpnd, func);
  3179. for (; i < size; i++)
  3180. {
  3181. GenerateMemInit(
  3182. headOpnd, offsetStart + i * sizeof(Js::Var),
  3183. IR::AddrOpnd::New(Js::JavascriptArray::MissingItem, IR::AddrOpndKindConstant, m_func, true),
  3184. instr, isZeroed);
  3185. }
  3186. }
  3187. // Skip pass the helper call
  3188. IR::LabelInstr * doneLabel = IR::LabelInstr::New(Js::OpCode::Label, func);
  3189. InsertBranch(Js::OpCode::Br, doneLabel, instr);
  3190. instr->InsertBefore(helperLabel);
  3191. instr->InsertAfter(doneLabel);
  3192. }
  3193. void
  3194. Lowerer::GenerateArrayInfoIsNativeIntArrayTest(IR::Instr *instr, Js::ArrayCallSiteInfo * arrayInfo, IR::LabelInstr * helperLabel)
  3195. {
  3196. Func * func = this->m_func;
  3197. InsertTestBranch(IR::MemRefOpnd::New(((char *)arrayInfo) + Js::ArrayCallSiteInfo::GetOffsetOfBits(), TyUint8, func),
  3198. IR::IntConstOpnd::New(Js::ArrayCallSiteInfo::NotNativeIntBit, TyUint8, func), Js::OpCode::BrNeq_A, helperLabel, instr);
  3199. }
  3200. void
  3201. Lowerer::GenerateArrayInfoIsNativeFloatAndNotIntArrayTest(IR::Instr *instr, Js::ArrayCallSiteInfo * arrayInfo, IR::LabelInstr * helperLabel)
  3202. {
  3203. Func * func = this->m_func;
  3204. InsertCompareBranch(IR::MemRefOpnd::New(((char *)arrayInfo) + Js::ArrayCallSiteInfo::GetOffsetOfBits(), TyUint8, func),
  3205. IR::IntConstOpnd::New(Js::ArrayCallSiteInfo::NotNativeIntBit, TyUint8, func), Js::OpCode::BrNeq_A, helperLabel, instr);
  3206. }
  3207. template <typename ArrayType>
  3208. static IR::JnHelperMethod GetArrayAllocMemHelper();
  3209. template <>
  3210. static IR::JnHelperMethod GetArrayAllocMemHelper<Js::JavascriptArray>()
  3211. {
  3212. return IR::HelperAllocMemForJavascriptArray;
  3213. }
  3214. template <>
  3215. static IR::JnHelperMethod GetArrayAllocMemHelper<Js::JavascriptNativeIntArray>()
  3216. {
  3217. return IR::HelperAllocMemForJavascriptNativeIntArray;
  3218. }
  3219. template <>
  3220. static IR::JnHelperMethod GetArrayAllocMemHelper<Js::JavascriptNativeFloatArray>()
  3221. {
  3222. return IR::HelperAllocMemForJavascriptNativeFloatArray;
  3223. }
  3224. template <typename ArrayType>
  3225. IR::RegOpnd *
  3226. Lowerer::GenerateArrayAlloc(IR::Instr *instr, uint32 * psize, Js::ArrayCallSiteInfo * arrayInfo, bool * pIsHeadSegmentZeroed)
  3227. {
  3228. Func * func = this->m_func;
  3229. IR::RegOpnd * dstOpnd = instr->GetDst()->AsRegOpnd();
  3230. // Generate code as in JavascriptArray::NewLiteral
  3231. uint32 count = *psize;
  3232. uint alignedHeadSegmentSize;
  3233. size_t arrayAllocSize;
  3234. IR::RegOpnd * headOpnd = IR::RegOpnd::New(TyMachPtr, func);
  3235. const IR::AutoReuseOpnd autoReuseHeadOpnd(headOpnd, func, false);
  3236. IR::Instr * leaHeadInstr = nullptr;
  3237. bool isHeadSegmentZeroed = false;
  3238. if (ArrayType::HasInlineHeadSegment(count))
  3239. {
  3240. uint32 allocCount = count == 0 ? Js::SparseArraySegmentBase::SMALL_CHUNK_SIZE : count;
  3241. arrayAllocSize = Js::JavascriptArray::DetermineAllocationSize<ArrayType, 0>(allocCount, nullptr, &alignedHeadSegmentSize);
  3242. leaHeadInstr = IR::Instr::New(Js::OpCode::LEA, headOpnd,
  3243. IR::IndirOpnd::New(dstOpnd, sizeof(ArrayType), TyMachPtr, func), func);
  3244. isHeadSegmentZeroed = true;
  3245. }
  3246. else
  3247. {
  3248. // Need to allocate the head segment first so that if it throws,
  3249. // we doesn't have the memory assigned to dstOpnd yet
  3250. // Even if the instruction is marked as dstIsTempObject, we still should not allocate
  3251. // that big of a chunk on the stack.
  3252. alignedHeadSegmentSize = Js::SparseArraySegment<typename ArrayType::TElement>::GetAlignedSize(count);
  3253. GenerateRecyclerAlloc(
  3254. IR::HelperAllocMemForSparseArraySegmentBase,
  3255. sizeof(Js::SparseArraySegment<typename ArrayType::TElement>) +
  3256. alignedHeadSegmentSize * sizeof(typename ArrayType::TElement),
  3257. headOpnd,
  3258. instr);
  3259. arrayAllocSize = sizeof(ArrayType);
  3260. }
  3261. *psize = alignedHeadSegmentSize;
  3262. IR::SymOpnd * tempObjectSymOpnd;
  3263. bool isZeroed = GenerateRecyclerOrMarkTempAlloc(instr, dstOpnd,
  3264. GetArrayAllocMemHelper<ArrayType>(), arrayAllocSize, &tempObjectSymOpnd);
  3265. isHeadSegmentZeroed = isHeadSegmentZeroed & isZeroed;
  3266. if (tempObjectSymOpnd && !PHASE_OFF(Js::HoistMarkTempInitPhase, this->m_func) && this->outerMostLoopLabel)
  3267. {
  3268. // Hoist the vtable init to the outer most loop top as it never changes
  3269. InsertMove(tempObjectSymOpnd,
  3270. this->LoadVTableValueOpnd(this->outerMostLoopLabel, ArrayType::VtableHelper()),
  3271. this->outerMostLoopLabel, false);
  3272. }
  3273. else
  3274. {
  3275. GenerateMemInit(dstOpnd, 0, this->LoadVTableValueOpnd(instr, ArrayType::VtableHelper()), instr, isZeroed);
  3276. }
  3277. GenerateMemInit(dstOpnd, ArrayType::GetOffsetOfType(), this->LoadLibraryValueOpnd(instr, ArrayType::InitialTypeHelper()), instr, isZeroed);
  3278. GenerateMemInitNull(dstOpnd, ArrayType::GetOffsetOfAuxSlots(), instr, isZeroed);
  3279. // Emit the flags and call site index together
  3280. Js::ProfileId arrayCallSiteIndex = (Js::ProfileId)instr->AsProfiledInstr()->u.profileId;
  3281. #if DBG
  3282. if (instr->AsProfiledInstr()->u.profileId < Js::Constants::NoProfileId)
  3283. {
  3284. Js::FunctionBody * functionBody = instr->m_func->GetJnFunction();
  3285. Assert((uint32)(arrayInfo - functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, 0)) == arrayCallSiteIndex);
  3286. }
  3287. else
  3288. {
  3289. Assert(arrayInfo == nullptr);
  3290. }
  3291. #endif
  3292. // The same at this:
  3293. // GenerateMemInit(dstOpnd, ArrayType::GetOffsetOfArrayFlags(), (uint16)Js::DynamicObjectFlags::InitialArrayValue, instr, isZeroed);
  3294. // GenerateMemInit(dstOpnd, ArrayType::GetOffsetOfArrayCallSiteIndex(), arrayCallSiteIndex, instr, isZeroed);
  3295. GenerateMemInit(dstOpnd, ArrayType::GetOffsetOfArrayFlags(), (uint)Js::DynamicObjectFlags::InitialArrayValue | ((uint)arrayCallSiteIndex << 16), instr, isZeroed);
  3296. GenerateMemInit(dstOpnd, ArrayType::GetOffsetOfLength(), count, instr, isZeroed);
  3297. if (leaHeadInstr != nullptr)
  3298. {
  3299. instr->InsertBefore(leaHeadInstr);
  3300. LowererMD::ChangeToLea(leaHeadInstr);
  3301. }
  3302. GenerateMemInit(dstOpnd, ArrayType::GetOffsetOfHead(), headOpnd, instr, isZeroed);
  3303. GenerateMemInit(dstOpnd, ArrayType::GetOffsetOfLastUsedSegmentOrSegmentMap(), headOpnd, instr, isZeroed);
  3304. // Initialize segment head
  3305. GenerateMemInit(headOpnd, Js::SparseArraySegmentBase::GetOffsetOfLeft(), 0, instr, isHeadSegmentZeroed);
  3306. GenerateMemInit(headOpnd, Js::SparseArraySegmentBase::GetOffsetOfLength(), count, instr, isHeadSegmentZeroed);
  3307. GenerateMemInit(headOpnd, Js::SparseArraySegmentBase::GetOffsetOfSize(), alignedHeadSegmentSize, instr, isHeadSegmentZeroed);
  3308. GenerateMemInitNull(headOpnd, Js::SparseArraySegmentBase::GetOffsetOfNext(), instr, isHeadSegmentZeroed);
  3309. *pIsHeadSegmentZeroed = isHeadSegmentZeroed;
  3310. return headOpnd;
  3311. }
  3312. void
  3313. Lowerer::GenerateProfiledNewScObjArrayFastPath(IR::Instr *instr, Js::ArrayCallSiteInfo * arrayInfo, RecyclerWeakReference<Js::FunctionBody> * weakFuncRef, uint32 length)
  3314. {
  3315. if (PHASE_OFF(Js::ArrayCtorFastPathPhase, m_func))
  3316. {
  3317. return;
  3318. }
  3319. Func * func = this->m_func;
  3320. IR::LabelInstr * helperLabel = IR::LabelInstr::New(Js::OpCode::Label, func, true);
  3321. uint32 size = length;
  3322. bool isZeroed;
  3323. IR::RegOpnd *dstOpnd = instr->GetDst()->AsRegOpnd();
  3324. IR::RegOpnd *headOpnd;
  3325. if (arrayInfo && arrayInfo->IsNativeIntArray())
  3326. {
  3327. GenerateArrayInfoIsNativeIntArrayTest(instr, arrayInfo, helperLabel);
  3328. Assert(Js::JavascriptNativeIntArray::GetOffsetOfArrayFlags() + sizeof(uint16) == Js::JavascriptNativeIntArray::GetOffsetOfArrayCallSiteIndex());
  3329. headOpnd = GenerateArrayAlloc<Js::JavascriptNativeIntArray>(instr, &size, arrayInfo, &isZeroed);
  3330. GenerateMemInit(dstOpnd, Js::JavascriptNativeIntArray::GetOffsetOfWeakFuncRef(), IR::AddrOpnd::New(weakFuncRef, IR::AddrOpndKindDynamicFunctionBodyWeakRef, m_func), instr, isZeroed);
  3331. for (uint i = 0; i < size; i++)
  3332. {
  3333. GenerateMemInit(headOpnd, sizeof(Js::SparseArraySegmentBase) + i * sizeof(int32),
  3334. Js::JavascriptNativeIntArray::MissingItem, instr, isZeroed);
  3335. }
  3336. }
  3337. else if (arrayInfo && arrayInfo->IsNativeFloatArray())
  3338. {
  3339. GenerateArrayInfoIsNativeFloatAndNotIntArrayTest(instr, arrayInfo, helperLabel);
  3340. Assert(Js::JavascriptNativeFloatArray::GetOffsetOfArrayFlags() + sizeof(uint16) == Js::JavascriptNativeFloatArray::GetOffsetOfArrayCallSiteIndex());
  3341. headOpnd = GenerateArrayAlloc<Js::JavascriptNativeFloatArray>(instr, &size, arrayInfo, &isZeroed);
  3342. GenerateMemInit(dstOpnd, Js::JavascriptNativeFloatArray::GetOffsetOfWeakFuncRef(), IR::AddrOpnd::New(weakFuncRef, IR::AddrOpndKindDynamicFunctionBodyWeakRef, m_func), instr, isZeroed);
  3343. // Js::JavascriptArray::MissingItem is a Var, so it may be 32-bit or 64 bit.
  3344. uint const offsetStart = sizeof(Js::SparseArraySegmentBase);
  3345. uint const missingItemCount = size * sizeof(double) / sizeof(Js::JavascriptArray::MissingItem);
  3346. for (uint i = 0; i < missingItemCount; i++)
  3347. {
  3348. GenerateMemInit(
  3349. headOpnd, offsetStart + i * sizeof(Js::JavascriptArray::MissingItem),
  3350. IR::AddrOpnd::New(Js::JavascriptArray::MissingItem, IR::AddrOpndKindConstant, m_func, true),
  3351. instr, isZeroed);
  3352. }
  3353. }
  3354. else
  3355. {
  3356. uint const offsetStart = sizeof(Js::SparseArraySegmentBase);
  3357. headOpnd = GenerateArrayAlloc<Js::JavascriptArray>(instr, &size, arrayInfo, &isZeroed);
  3358. for (uint i = 0; i < size; i++)
  3359. {
  3360. GenerateMemInit(
  3361. headOpnd, offsetStart + i * sizeof(Js::Var),
  3362. IR::AddrOpnd::New(Js::JavascriptArray::MissingItem, IR::AddrOpndKindConstant, m_func, true),
  3363. instr, isZeroed);
  3364. }
  3365. }
  3366. // Skip pass the helper call
  3367. IR::LabelInstr * doneLabel = IR::LabelInstr::New(Js::OpCode::Label, func);
  3368. InsertBranch(Js::OpCode::Br, doneLabel, instr);
  3369. instr->InsertBefore(helperLabel);
  3370. instr->InsertAfter(doneLabel);
  3371. }
  3372. void
  3373. Lowerer::GenerateProfiledNewScIntArrayFastPath(IR::Instr *instr, Js::ArrayCallSiteInfo * arrayInfo, RecyclerWeakReference<Js::FunctionBody> * weakFuncRef)
  3374. {
  3375. // Helper will deal with ForceES5ARray
  3376. if (PHASE_OFF(Js::ArrayLiteralFastPathPhase, m_func) || CONFIG_FLAG(ForceES5Array))
  3377. {
  3378. return;
  3379. }
  3380. if (!arrayInfo->IsNativeIntArray())
  3381. {
  3382. return;
  3383. }
  3384. Func * func = this->m_func;
  3385. IR::LabelInstr * helperLabel = IR::LabelInstr::New(Js::OpCode::Label, func, true);
  3386. GenerateArrayInfoIsNativeIntArrayTest(instr, arrayInfo, helperLabel);
  3387. IR::AddrOpnd * elementsOpnd = instr->GetSrc1()->AsAddrOpnd();
  3388. Js::AuxArray<int32> * ints = (Js::AuxArray<int32> *)elementsOpnd->m_address;
  3389. uint32 size = ints->count;
  3390. // Generate code as in JavascriptArray::NewLiteral
  3391. bool isHeadSegmentZeroed;
  3392. IR::RegOpnd * dstOpnd = instr->GetDst()->AsRegOpnd();
  3393. Assert(Js::JavascriptNativeIntArray::GetOffsetOfArrayFlags() + sizeof(uint16) == Js::JavascriptNativeIntArray::GetOffsetOfArrayCallSiteIndex());
  3394. IR::RegOpnd * headOpnd = GenerateArrayAlloc<Js::JavascriptNativeIntArray>(instr, &size, arrayInfo, &isHeadSegmentZeroed);
  3395. const IR::AutoReuseOpnd autoReuseHeadOpnd(headOpnd, func);
  3396. GenerateMemInit(dstOpnd, Js::JavascriptNativeIntArray::GetOffsetOfWeakFuncRef(), IR::AddrOpnd::New(weakFuncRef, IR::AddrOpndKindDynamicMisc, m_func), instr, isHeadSegmentZeroed);
  3397. // Initialize the elements
  3398. uint i = 0;
  3399. if (ints->count > 16)
  3400. {
  3401. // Do memcpy if > 16
  3402. IR::RegOpnd * dstElementsOpnd = IR::RegOpnd::New(TyMachPtr, func);
  3403. const IR::AutoReuseOpnd autoReuseDstElementsOpnd(dstElementsOpnd, func);
  3404. IR::Opnd * srcOpnd = IR::AddrOpnd::New(ints->elements, IR::AddrOpndKindDynamicMisc, func);
  3405. InsertLea(dstElementsOpnd, IR::IndirOpnd::New(headOpnd, sizeof(Js::SparseArraySegmentBase), TyMachPtr, func), instr);
  3406. GenerateMemCopy(dstElementsOpnd, srcOpnd, ints->count * sizeof(int32), instr);
  3407. i = ints->count;
  3408. }
  3409. else
  3410. {
  3411. for (; i < ints->count; i++)
  3412. {
  3413. GenerateMemInit(headOpnd, sizeof(Js::SparseArraySegmentBase) + i * sizeof(int32),
  3414. ints->elements[i], instr, isHeadSegmentZeroed);
  3415. }
  3416. }
  3417. Assert(i == ints->count);
  3418. for (; i < size; i++)
  3419. {
  3420. GenerateMemInit(headOpnd, sizeof(Js::SparseArraySegmentBase) + i * sizeof(int32),
  3421. Js::JavascriptNativeIntArray::MissingItem, instr, isHeadSegmentZeroed);
  3422. }
  3423. // Skip pass the helper call
  3424. IR::LabelInstr * doneLabel = IR::LabelInstr::New(Js::OpCode::Label, func);
  3425. InsertBranch(Js::OpCode::Br, doneLabel, instr);
  3426. instr->InsertBefore(helperLabel);
  3427. instr->InsertAfter(doneLabel);
  3428. }
  3429. void
  3430. Lowerer::GenerateProfiledNewScFloatArrayFastPath(IR::Instr *instr, Js::ArrayCallSiteInfo * arrayInfo, RecyclerWeakReference<Js::FunctionBody> * weakFuncRef)
  3431. {
  3432. if (PHASE_OFF(Js::ArrayLiteralFastPathPhase, m_func) || CONFIG_FLAG(ForceES5Array))
  3433. {
  3434. return;
  3435. }
  3436. if (!arrayInfo->IsNativeFloatArray())
  3437. {
  3438. return;
  3439. }
  3440. Func * func = this->m_func;
  3441. IR::LabelInstr * helperLabel = IR::LabelInstr::New(Js::OpCode::Label, func, true);
  3442. // If the array info hasn't mark as not int array yet, go to the helper and mark it.
  3443. // It really is just for assert purpose in JavascriptNativeFloatArray::ToVarArray
  3444. GenerateArrayInfoIsNativeFloatAndNotIntArrayTest(instr, arrayInfo, helperLabel);
  3445. IR::AddrOpnd * elementsOpnd = instr->GetSrc1()->AsAddrOpnd();
  3446. Js::AuxArray<double> * doubles = (Js::AuxArray<double> *)elementsOpnd->m_address;
  3447. uint32 size = doubles->count;
  3448. // Generate code as in JavascriptArray::NewLiteral
  3449. bool isHeadSegmentZeroed;
  3450. IR::RegOpnd * dstOpnd = instr->GetDst()->AsRegOpnd();
  3451. Assert(Js::JavascriptNativeFloatArray::GetOffsetOfArrayFlags() + sizeof(uint16) == Js::JavascriptNativeFloatArray::GetOffsetOfArrayCallSiteIndex());
  3452. IR::RegOpnd * headOpnd = GenerateArrayAlloc<Js::JavascriptNativeFloatArray>(instr, &size, arrayInfo, &isHeadSegmentZeroed);
  3453. const IR::AutoReuseOpnd autoReuseHeadOpnd(headOpnd, func);
  3454. GenerateMemInit(dstOpnd, Js::JavascriptNativeFloatArray::GetOffsetOfWeakFuncRef(), IR::AddrOpnd::New(weakFuncRef, IR::AddrOpndKindDynamicFunctionBodyWeakRef, m_func), instr, isHeadSegmentZeroed);
  3455. // Initialize the elements
  3456. IR::RegOpnd * dstElementsOpnd = IR::RegOpnd::New(TyMachPtr, func);
  3457. const IR::AutoReuseOpnd autoReuseDstElementsOpnd(dstElementsOpnd, func);
  3458. IR::Opnd * srcOpnd = IR::AddrOpnd::New(doubles->elements, IR::AddrOpndKindDynamicMisc, func);
  3459. InsertLea(dstElementsOpnd, IR::IndirOpnd::New(headOpnd, sizeof(Js::SparseArraySegmentBase), TyMachPtr, func), instr);
  3460. GenerateMemCopy(dstElementsOpnd, srcOpnd, doubles->count * sizeof(double), instr);
  3461. // Js::JavascriptArray::MissingItem is a Var, so it may be 32-bit or 64 bit.
  3462. uint const offsetStart = sizeof(Js::SparseArraySegmentBase) + doubles->count * sizeof(double);
  3463. uint const missingItem = (size - doubles->count) * sizeof(double) / sizeof(Js::JavascriptArray::MissingItem);
  3464. for (uint i = 0; i < missingItem; i++)
  3465. {
  3466. GenerateMemInit(headOpnd, offsetStart + i * sizeof(Js::JavascriptArray::MissingItem),
  3467. IR::AddrOpnd::New(Js::JavascriptArray::MissingItem, IR::AddrOpndKindConstant, m_func, true), instr, isHeadSegmentZeroed);
  3468. }
  3469. // Skip pass the helper call
  3470. IR::LabelInstr * doneLabel = IR::LabelInstr::New(Js::OpCode::Label, func);
  3471. InsertBranch(Js::OpCode::Br, doneLabel, instr);
  3472. instr->InsertBefore(helperLabel);
  3473. instr->InsertAfter(doneLabel);
  3474. }
  3475. IR::Instr *
  3476. Lowerer::LowerNewScIntArray(IR::Instr *arrInstr)
  3477. {
  3478. IR::Instr *instrPrev = arrInstr->m_prev;
  3479. IR::JnHelperMethod helperMethod = IR::HelperScrArr_OP_NewScIntArray;
  3480. if ((arrInstr->IsJitProfilingInstr() || arrInstr->IsProfiledInstr()) && arrInstr->m_func->HasProfileInfo())
  3481. {
  3482. RecyclerWeakReference<Js::FunctionBody> *weakFuncRef = arrInstr->m_func->GetWeakFuncRef();
  3483. if (weakFuncRef)
  3484. {
  3485. Js::FunctionBody *functionBody = arrInstr->m_func->GetJnFunction();
  3486. // Technically a load of the same memory address either way.
  3487. Js::ProfileId profileId =
  3488. arrInstr->IsJitProfilingInstr()
  3489. ? arrInstr->AsJitProfilingInstr()->profileId
  3490. : static_cast<Js::ProfileId>(arrInstr->AsProfiledInstr()->u.profileId);
  3491. Js::ArrayCallSiteInfo *arrayInfo =
  3492. functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, profileId);
  3493. // Only do fast-path if it isn't a JitProfiling instr and not copy-on-access array
  3494. if (arrInstr->IsProfiledInstr()
  3495. && (PHASE_OFF1(Js::Phase::CopyOnAccessArrayPhase) || arrayInfo->isNotCopyOnAccessArray) && !PHASE_FORCE1(Js::Phase::CopyOnAccessArrayPhase))
  3496. {
  3497. GenerateProfiledNewScIntArrayFastPath(arrInstr, arrayInfo, weakFuncRef);
  3498. }
  3499. m_lowererMD.LoadHelperArgument(arrInstr, IR::AddrOpnd::New(weakFuncRef, IR::AddrOpndKindDynamicFunctionBodyWeakRef, m_func));
  3500. m_lowererMD.LoadHelperArgument(arrInstr, IR::AddrOpnd::New(arrayInfo, IR::AddrOpndKindDynamicArrayCallSiteInfo, m_func));
  3501. helperMethod = IR::HelperScrArr_ProfiledNewScIntArray;
  3502. }
  3503. }
  3504. LoadScriptContext(arrInstr);
  3505. IR::Opnd *elementsOpnd = arrInstr->UnlinkSrc1();
  3506. m_lowererMD.LoadHelperArgument(arrInstr, elementsOpnd);
  3507. m_lowererMD.ChangeToHelperCall(arrInstr, helperMethod);
  3508. return instrPrev;
  3509. }
  3510. IR::Instr *
  3511. Lowerer::LowerNewScFltArray(IR::Instr *arrInstr)
  3512. {
  3513. IR::Instr *instrPrev = arrInstr->m_prev;
  3514. IR::JnHelperMethod helperMethod = IR::HelperScrArr_OP_NewScFltArray;
  3515. if ((arrInstr->IsJitProfilingInstr() || arrInstr->IsProfiledInstr()) && arrInstr->m_func->HasProfileInfo())
  3516. {
  3517. RecyclerWeakReference<Js::FunctionBody> *weakFuncRef = arrInstr->m_func->GetWeakFuncRef();
  3518. if (weakFuncRef)
  3519. {
  3520. Js::ProfileId profileId =
  3521. arrInstr->IsJitProfilingInstr()
  3522. ? arrInstr->AsJitProfilingInstr()->profileId
  3523. : static_cast<Js::ProfileId>(arrInstr->AsProfiledInstr()->u.profileId);
  3524. Js::FunctionBody *functionBody = arrInstr->m_func->GetJnFunction();
  3525. Js::ArrayCallSiteInfo *arrayInfo =
  3526. functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, profileId);
  3527. // Only do fast-path if it isn't a JitProfiling instr
  3528. if (arrInstr->IsProfiledInstr()) {
  3529. GenerateProfiledNewScFloatArrayFastPath(arrInstr, arrayInfo, weakFuncRef);
  3530. }
  3531. m_lowererMD.LoadHelperArgument(arrInstr, IR::AddrOpnd::New(weakFuncRef, IR::AddrOpndKindDynamicFunctionBodyWeakRef, m_func));
  3532. m_lowererMD.LoadHelperArgument(arrInstr, IR::AddrOpnd::New(arrayInfo, IR::AddrOpndKindDynamicArrayCallSiteInfo, m_func));
  3533. helperMethod = IR::HelperScrArr_ProfiledNewScFltArray;
  3534. }
  3535. }
  3536. LoadScriptContext(arrInstr);
  3537. IR::Opnd *elementsOpnd = arrInstr->UnlinkSrc1();
  3538. m_lowererMD.LoadHelperArgument(arrInstr, elementsOpnd);
  3539. m_lowererMD.ChangeToHelperCall(arrInstr, helperMethod);
  3540. return instrPrev;
  3541. }
  3542. IR::Instr *
  3543. Lowerer::LowerArraySegmentVars(IR::Instr *arrayInstr)
  3544. {
  3545. IR::Instr * instrPrev;
  3546. IR::HelperCallOpnd * opndHelper = IR::HelperCallOpnd::New(IR::HelperArraySegmentVars, m_func);
  3547. instrPrev = m_lowererMD.LoadHelperArgument(arrayInstr, arrayInstr->UnlinkSrc2());
  3548. m_lowererMD.LoadHelperArgument(arrayInstr, arrayInstr->UnlinkSrc1());
  3549. arrayInstr->m_opcode = Js::OpCode::Call;
  3550. arrayInstr->SetSrc1(opndHelper);
  3551. m_lowererMD.LowerCall(arrayInstr, 0);
  3552. return instrPrev;
  3553. }
  3554. IR::Instr* Lowerer::LowerProfiledNewArray(IR::JitProfilingInstr* instr, bool hasArgs)
  3555. {
  3556. // Use the special helper which checks whether Array has been overwritten by the user and if
  3557. // it hasn't, possibly allocates a native array
  3558. // Insert a temporary label before the instruction we're about to lower, so that we can return
  3559. // the first instruction above that needs to be lowered after we're done - regardless of argument
  3560. // list, StartCall, etc.
  3561. IR::Instr* startMarkerInstr = InsertLoweredRegionStartMarker(instr);
  3562. Assert(instr->isNewArray);
  3563. Assert(instr->arrayProfileId != Js::Constants::NoProfileId);
  3564. Assert(instr->profileId != Js::Constants::NoProfileId);
  3565. bool isSpreadCall = instr->m_opcode == Js::OpCode::NewScObjectSpread || instr->m_opcode == Js::OpCode::NewScObjArraySpread;
  3566. m_lowererMD.LoadNewScObjFirstArg(instr, IR::AddrOpnd::New(nullptr, IR::AddrOpndKindConstantVar, m_func, true), isSpreadCall ? 1 : 0);
  3567. if (isSpreadCall)
  3568. {
  3569. this->LowerSpreadCall(instr, Js::CallFlags_New, true);
  3570. }
  3571. else
  3572. {
  3573. const int32 argCount = m_lowererMD.LowerCallArgs(instr, Js::CallFlags_New, 4);
  3574. m_lowererMD.LoadHelperArgument(instr, IR::Opnd::CreateProfileIdOpnd(instr->arrayProfileId, m_func));
  3575. m_lowererMD.LoadHelperArgument(instr, IR::Opnd::CreateProfileIdOpnd(instr->profileId, m_func));
  3576. m_lowererMD.LoadHelperArgument(instr, IR::Opnd::CreateFramePointerOpnd(m_func));
  3577. m_lowererMD.LoadHelperArgument(instr, instr->UnlinkSrc1());
  3578. instr->SetSrc1(IR::HelperCallOpnd::New(IR::HelperProfiledNewScObjArray, m_func));
  3579. m_lowererMD.LowerCall(instr, static_cast<Js::ArgSlot>(argCount));
  3580. }
  3581. return RemoveLoweredRegionStartMarker(startMarkerInstr);
  3582. }
  3583. ///----------------------------------------------------------------------------
  3584. ///
  3585. /// Lowerer::LowerNewScObject
  3586. ///
  3587. /// Machine independent lowering of a CallI instr.
  3588. ///
  3589. ///----------------------------------------------------------------------------
  3590. IR::Instr *
  3591. Lowerer::LowerNewScObject(IR::Instr *newObjInstr, bool callCtor, bool hasArgs, bool isBaseClassConstructorNewScObject)
  3592. {
  3593. if (newObjInstr->IsJitProfilingInstr() && newObjInstr->AsJitProfilingInstr()->isNewArray)
  3594. {
  3595. Assert(callCtor);
  3596. return LowerProfiledNewArray(newObjInstr->AsJitProfilingInstr(), hasArgs);
  3597. }
  3598. bool isSpreadCall = newObjInstr->m_opcode == Js::OpCode::NewScObjectSpread ||
  3599. newObjInstr->m_opcode == Js::OpCode::NewScObjArraySpread;
  3600. Func* func = newObjInstr->m_func;
  3601. // Insert a temporary label before the instruction we're about to lower, so that we can return
  3602. // the first instruction above that needs to be lowered after we're done - regardless of argument
  3603. // list, StartCall, etc.
  3604. IR::Instr* startMarkerInstr = InsertLoweredRegionStartMarker(newObjInstr);
  3605. IR::Opnd *ctorOpnd = newObjInstr->GetSrc1();
  3606. IR::RegOpnd *newObjDst = newObjInstr->GetDst()->AsRegOpnd();
  3607. Assert(!callCtor || !hasArgs || (newObjInstr->GetSrc2() != nullptr /*&& newObjInstr->GetSrc2()->IsSymOpnd()*/));
  3608. bool skipNewScObj = false;
  3609. bool returnNewScObj = false;
  3610. bool emitBailOut = false;
  3611. // If we haven't yet split NewScObject into NewScObjectNoCtor and CallI, we will need a temporary register
  3612. // to hold the result of the object allocation.
  3613. IR::RegOpnd* createObjDst = callCtor ? IR::RegOpnd::New(TyVar, func) : newObjDst;
  3614. IR::LabelInstr* helperOrBailoutLabel = IR::LabelInstr::New(Js::OpCode::Label, func, /* isOpHelper = */ true);
  3615. IR::LabelInstr* callCtorLabel = IR::LabelInstr::New(Js::OpCode::Label, func, /* isOpHelper = */ false);
  3616. // Try to emit the fast allocation and construction path.
  3617. bool usedFixedCtorCache = TryLowerNewScObjectWithFixedCtorCache(newObjInstr, createObjDst, helperOrBailoutLabel, callCtorLabel, skipNewScObj, returnNewScObj, emitBailOut);
  3618. AssertMsg(!skipNewScObj || callCtor, "What will we return if we skip the default new object and don't call the ctor?");
  3619. Assert(!skipNewScObj || !returnNewScObj);
  3620. Assert(usedFixedCtorCache || !skipNewScObj);
  3621. Assert(!usedFixedCtorCache || newObjInstr->HasFixedFunctionAddressTarget());
  3622. Assert(!skipNewScObj || !emitBailOut);
  3623. #if DBG
  3624. if (usedFixedCtorCache)
  3625. {
  3626. Js::JavascriptFunction* ctor = newObjInstr->GetFixedFunction();
  3627. Js::FunctionInfo* ctorInfo = ctor->GetFunctionInfo();
  3628. Assert((ctorInfo->GetAttributes() & Js::FunctionInfo::Attributes::ErrorOnNew) == 0);
  3629. Assert(!!(ctorInfo->GetAttributes() & Js::FunctionInfo::Attributes::SkipDefaultNewObject) == skipNewScObj);
  3630. }
  3631. #endif
  3632. IR::Instr* startCallInstr = nullptr;
  3633. if (callCtor && hasArgs)
  3634. {
  3635. hasArgs = !newObjInstr->HasEmptyArgOutChain(&startCallInstr);
  3636. }
  3637. // If we're not skipping the default new object, let's emit bailout or a call to NewScObject* helper
  3638. IR::JnHelperMethod newScHelper = IR::HelperInvalid;
  3639. IR::Instr *newScObjCall = nullptr;
  3640. if (!skipNewScObj)
  3641. {
  3642. // If we emitted the fast path, this block is a helper block.
  3643. if (usedFixedCtorCache)
  3644. {
  3645. newObjInstr->InsertBefore(helperOrBailoutLabel);
  3646. }
  3647. if (emitBailOut)
  3648. {
  3649. IR::Instr* bailOutInstr = newObjInstr;
  3650. newObjInstr = IR::Instr::New(newObjInstr->m_opcode, func);
  3651. bailOutInstr->TransferTo(newObjInstr);
  3652. bailOutInstr->m_opcode = Js::OpCode::BailOut;
  3653. bailOutInstr->InsertAfter(newObjInstr);
  3654. GenerateBailOut(bailOutInstr);
  3655. }
  3656. else
  3657. {
  3658. Assert(!newObjDst->CanStoreTemp());
  3659. // createObjDst = NewScObject...(ctorOpnd)
  3660. newScHelper = !callCtor ?
  3661. (isBaseClassConstructorNewScObject ?
  3662. (hasArgs ? IR::HelperNewScObjectNoCtorFull : IR::HelperNewScObjectNoArgNoCtorFull) :
  3663. (hasArgs ? IR::HelperNewScObjectNoCtor : IR::HelperNewScObjectNoArgNoCtor)) :
  3664. (hasArgs || usedFixedCtorCache ? IR::HelperNewScObjectNoCtor : IR::HelperNewScObjectNoArg);
  3665. LoadScriptContext(newObjInstr);
  3666. m_lowererMD.LoadHelperArgument(newObjInstr, newObjInstr->GetSrc1());
  3667. newScObjCall = IR::Instr::New(Js::OpCode::Call, createObjDst, IR::HelperCallOpnd::New(newScHelper, func), func);
  3668. newObjInstr->InsertBefore(newScObjCall);
  3669. m_lowererMD.LowerCall(newScObjCall, 0);
  3670. }
  3671. }
  3672. // If we call HelperNewScObjectNoArg directly, we won't be calling the constructor from here, because the helper will do it.
  3673. // We could probably avoid this complexity by converting NewScObjectNoArg to NewScObject in the IRBuilder, once we have dedicated
  3674. // code paths for new Object() and new Array().
  3675. callCtor &= hasArgs || usedFixedCtorCache;
  3676. AssertMsg(!skipNewScObj || callCtor, "What will we return if we skip the default new object and don't call the ctor?");
  3677. newObjInstr->InsertBefore(callCtorLabel);
  3678. if (callCtor && usedFixedCtorCache)
  3679. {
  3680. IR::JnHelperMethod ctorHelper = IR::JnHelperMethodCount;
  3681. // If we have no arguments (i.e. the argument chain is empty), we can recognize a couple of common special cases, such
  3682. // as new Object() or new Array(), for which we have optimized helpers.
  3683. Js::JavascriptFunction* ctor = newObjInstr->GetFixedFunction();
  3684. Js::FunctionInfo* ctorInfo = ctor->GetFunctionInfo();
  3685. if (!hasArgs && (ctorInfo == &Js::JavascriptObject::EntryInfo::NewInstance || ctorInfo == &Js::JavascriptArray::EntryInfo::NewInstance))
  3686. {
  3687. if (ctorInfo == &Js::JavascriptObject::EntryInfo::NewInstance)
  3688. {
  3689. Assert(skipNewScObj);
  3690. ctorHelper = IR::HelperNewJavascriptObjectNoArg;
  3691. callCtor = false;
  3692. }
  3693. else if (ctorInfo == &Js::JavascriptArray::EntryInfo::NewInstance)
  3694. {
  3695. Assert(skipNewScObj);
  3696. ctorHelper = IR::HelperNewJavascriptArrayNoArg;
  3697. callCtor = false;
  3698. }
  3699. if (!callCtor)
  3700. {
  3701. LoadScriptContext(newObjInstr);
  3702. IR::Instr *ctorCall = IR::Instr::New(Js::OpCode::Call, newObjDst, IR::HelperCallOpnd::New(ctorHelper, func), func);
  3703. newObjInstr->InsertBefore(ctorCall);
  3704. m_lowererMD.LowerCall(ctorCall, 0);
  3705. }
  3706. }
  3707. }
  3708. IR::AutoReuseOpnd autoReuseSavedCtorOpnd;
  3709. if (callCtor)
  3710. {
  3711. // Load the first argument, which is either the object just created or null. Spread has an extra argument.
  3712. IR::Instr * argInstr = this->m_lowererMD.LoadNewScObjFirstArg(newObjInstr, createObjDst, isSpreadCall ? 1 : 0);
  3713. IR::Instr * insertAfterCtorInstr = newObjInstr->m_next;
  3714. if (skipNewScObj)
  3715. {
  3716. // Since we skipped the default new object, we must be returning whatever the constructor returns
  3717. // (which better be an Object), so let's just use newObjDst directly.
  3718. // newObjDst = newObjInstr->m_src1(createObjDst, ...)
  3719. Assert(newObjInstr->GetDst() == newObjDst);
  3720. if (isSpreadCall)
  3721. {
  3722. newObjInstr = this->LowerSpreadCall(newObjInstr, Js::CallFlags_New);
  3723. }
  3724. else
  3725. {
  3726. newObjInstr = this->m_lowererMD.LowerCallI(newObjInstr, Js::CallFlags_New, false, argInstr);
  3727. }
  3728. }
  3729. else
  3730. {
  3731. // We may need to return the default new object or whatever the constructor returns. Let's stash
  3732. // away the constructor's return in a temporary operand, and do the right check, if necessary.
  3733. // ctorResultObjOpnd = newObjInstr->m_src1(createObjDst, ...)
  3734. IR::RegOpnd *ctorResultObjOpnd = IR::RegOpnd::New(TyVar, func);
  3735. newObjInstr->UnlinkDst();
  3736. newObjInstr->SetDst(ctorResultObjOpnd);
  3737. if (isSpreadCall)
  3738. {
  3739. newObjInstr = this->LowerSpreadCall(newObjInstr, Js::CallFlags_New);
  3740. }
  3741. else
  3742. {
  3743. newObjInstr = this->m_lowererMD.LowerCallI(newObjInstr, Js::CallFlags_New, false, argInstr);
  3744. }
  3745. if (returnNewScObj)
  3746. {
  3747. // MOV newObjDst, createObjDst
  3748. this->m_lowererMD.CreateAssign(newObjDst, createObjDst, insertAfterCtorInstr);
  3749. }
  3750. else
  3751. {
  3752. LowerGetNewScObjectCommon(ctorResultObjOpnd, ctorResultObjOpnd, createObjDst, insertAfterCtorInstr);
  3753. this->m_lowererMD.CreateAssign(newObjDst, ctorResultObjOpnd, insertAfterCtorInstr);
  3754. }
  3755. }
  3756. // We don't ever need to update the constructor cache, if we hard coded it. Caches requiring update after constructor
  3757. // don't get cloned, and those that don't require update will never need one anymore.
  3758. if (!usedFixedCtorCache)
  3759. {
  3760. LowerUpdateNewScObjectCache(insertAfterCtorInstr, newObjDst, ctorOpnd, false /* isCtorFunction */);
  3761. }
  3762. }
  3763. else
  3764. {
  3765. if (newObjInstr->IsJitProfilingInstr())
  3766. {
  3767. Assert(m_func->IsSimpleJit());
  3768. Assert(!Js::FunctionBody::IsNewSimpleJit());
  3769. // This path skipped calling the Ctor, which skips calling LowerCallI with newObjInstr, meaning that the call will not be profiled.
  3770. // So we insert it manually here.
  3771. if(newScHelper == IR::HelperNewScObjectNoArg &&
  3772. newObjDst &&
  3773. ctorOpnd->IsRegOpnd() &&
  3774. newObjDst->AsRegOpnd()->m_sym == ctorOpnd->AsRegOpnd()->m_sym)
  3775. {
  3776. Assert(newObjInstr->m_func->IsSimpleJit());
  3777. Assert(createObjDst != newObjDst);
  3778. // The function object sym is going to be overwritten, so save it in a temp for profiling
  3779. IR::RegOpnd *const savedCtorOpnd = IR::RegOpnd::New(ctorOpnd->GetType(), newObjInstr->m_func);
  3780. autoReuseSavedCtorOpnd.Initialize(savedCtorOpnd, newObjInstr->m_func);
  3781. Lowerer::InsertMove(savedCtorOpnd, ctorOpnd, newObjInstr);
  3782. ctorOpnd = savedCtorOpnd;
  3783. }
  3784. // It is a constructor (CallFlags_New) and therefore a single argument (this) would have been given.
  3785. const auto info = Lowerer::MakeCallInfoConst(Js::CallFlags_New, 1, func);
  3786. Assert(newScObjCall);
  3787. IR::JitProfilingInstr *const newObjJitProfilingInstr = newObjInstr->AsJitProfilingInstr();
  3788. GenerateCallProfiling(
  3789. newObjJitProfilingInstr->profileId,
  3790. newObjJitProfilingInstr->inlineCacheIndex,
  3791. createObjDst,
  3792. ctorOpnd,
  3793. info,
  3794. false,
  3795. newScObjCall,
  3796. newObjInstr);
  3797. }
  3798. // MOV newObjDst, createObjDst
  3799. if (!skipNewScObj && createObjDst != newObjDst)
  3800. {
  3801. this->m_lowererMD.CreateAssign(newObjDst, createObjDst, newObjInstr);
  3802. }
  3803. newObjInstr->Remove();
  3804. }
  3805. // Return the first instruction above the region we've just lowered.
  3806. return RemoveLoweredRegionStartMarker(startMarkerInstr);
  3807. }
  3808. IR::Instr*
  3809. Lowerer::GenerateCallProfiling(Js::ProfileId profileId, Js::InlineCacheIndex inlineCacheIndex, IR::Opnd* retval, IR::Opnd*calleeFunctionObjOpnd, IR::Opnd* callInfo, bool returnTypeOnly, IR::Instr*callInstr,IR::Instr*insertAfter)
  3810. {
  3811. // This should only ever happen in profiling simplejit
  3812. Assert(m_func->DoSimpleJitDynamicProfile());
  3813. // Make sure they gave us the correct call instruction
  3814. #if defined(_M_IX86) || defined(_M_X64)
  3815. Assert(callInstr->m_opcode == Js::OpCode::CALL);
  3816. #elif defined(_M_ARM)
  3817. Assert(callInstr->m_opcode == Js::OpCode::BLX);
  3818. #endif
  3819. Func*const func = insertAfter->m_func;
  3820. {
  3821. // First, we should save the implicit call flags
  3822. const auto starFlag = GetImplicitCallFlagsOpnd();
  3823. const auto saveOpnd = IR::RegOpnd::New(starFlag->GetType(), func);
  3824. IR::AutoReuseOpnd a(starFlag, func), b(saveOpnd, func);
  3825. //Save the flags (before call) and restore them (after the call)
  3826. this->InsertMove(saveOpnd, starFlag, callInstr);
  3827. // Note: On arm this is slightly inefficient because it forces a reload of the memory location to a reg (whereas x86 can load straight from hard-coded memory into a reg)
  3828. // But it works and making it not reload the memory location would force more refactoring.
  3829. this->InsertMove(starFlag, saveOpnd, insertAfter->m_next);
  3830. }
  3831. // Profile a call that just happened: push some extra info on the stack and call the helper
  3832. if (!retval)
  3833. {
  3834. if (returnTypeOnly)
  3835. {
  3836. // If we are only supposed to profile the return type but don't use the return value, we might
  3837. // as well do nothing!
  3838. return insertAfter;
  3839. }
  3840. retval = IR::AddrOpnd::NewNull(func);
  3841. }
  3842. IR::Instr* profileCall = IR::Instr::New(Js::OpCode::Call, func);
  3843. bool needInlineCacheIndex;
  3844. IR::JnHelperMethod helperMethod;
  3845. if (returnTypeOnly)
  3846. {
  3847. needInlineCacheIndex = false;
  3848. helperMethod = IR::HelperSimpleProfileReturnTypeCall;
  3849. }
  3850. else if(inlineCacheIndex == Js::Constants::NoInlineCacheIndex)
  3851. {
  3852. needInlineCacheIndex = false;
  3853. helperMethod = IR::HelperSimpleProfileCall_DefaultInlineCacheIndex;
  3854. }
  3855. else
  3856. {
  3857. needInlineCacheIndex = true;
  3858. helperMethod = IR::HelperSimpleProfileCall;
  3859. }
  3860. profileCall->SetSrc1(IR::HelperCallOpnd::New(helperMethod, func));
  3861. insertAfter->InsertAfter(profileCall);
  3862. m_lowererMD.LoadHelperArgument(profileCall, callInfo);
  3863. m_lowererMD.LoadHelperArgument(profileCall, calleeFunctionObjOpnd);
  3864. m_lowererMD.LoadHelperArgument(profileCall, retval);
  3865. if(needInlineCacheIndex)
  3866. {
  3867. m_lowererMD.LoadHelperArgument(profileCall, IR::Opnd::CreateInlineCacheIndexOpnd(inlineCacheIndex, func));
  3868. }
  3869. m_lowererMD.LoadHelperArgument(profileCall, IR::Opnd::CreateProfileIdOpnd(profileId, func));
  3870. // Push the frame pointer so that the profiling call can grab the stack layout
  3871. m_lowererMD.LoadHelperArgument(profileCall, IR::Opnd::CreateFramePointerOpnd(func));
  3872. // No args: the helper is stdcall
  3873. return m_lowererMD.LowerCall(profileCall, 0);
  3874. }
  3875. bool Lowerer::TryLowerNewScObjectWithFixedCtorCache(IR::Instr* newObjInstr, IR::RegOpnd* newObjDst,
  3876. IR::LabelInstr* helperOrBailoutLabel, IR::LabelInstr* callCtorLabel, bool& skipNewScObj, bool& returnNewScObj, bool& emitBailOut)
  3877. {
  3878. skipNewScObj = false;
  3879. returnNewScObj = false;
  3880. AssertMsg(!PHASE_OFF(Js::ObjTypeSpecNewObjPhase, this->m_func) || !newObjInstr->HasBailOutInfo(),
  3881. "Why do we have bailout on NewScObject when ObjTypeSpecNewObj is off?");
  3882. if (PHASE_OFF(Js::FixedNewObjPhase, newObjInstr->m_func->GetJnFunction()) && PHASE_OFF(Js::ObjTypeSpecNewObjPhase, this->m_func))
  3883. {
  3884. return false;
  3885. }
  3886. Js::JitTimeConstructorCache* ctorCache;
  3887. if (newObjInstr->HasBailOutInfo())
  3888. {
  3889. Assert(newObjInstr->IsNewScObjectInstr());
  3890. Assert(newObjInstr->IsProfiledInstr());
  3891. Assert(newObjInstr->GetBailOutKind() == IR::BailOutFailedCtorGuardCheck);
  3892. emitBailOut = true;
  3893. ctorCache = newObjInstr->m_func->GetConstructorCache(static_cast<Js::ProfileId>(newObjInstr->AsProfiledInstr()->u.profileId));
  3894. Assert(ctorCache != nullptr);
  3895. Assert(!ctorCache->skipNewScObject);
  3896. Assert(!ctorCache->typeIsFinal || ctorCache->ctorHasNoExplicitReturnValue);
  3897. LinkCtorCacheToGuardedProperties(ctorCache);
  3898. }
  3899. else
  3900. {
  3901. if (newObjInstr->m_opcode == Js::OpCode::NewScObjArray || newObjInstr->m_opcode == Js::OpCode::NewScObjArraySpread)
  3902. {
  3903. // These instr's carry a profile that indexes the array call site info, not the ctor cache.
  3904. return false;
  3905. }
  3906. ctorCache = newObjInstr->IsProfiledInstr() ? newObjInstr->m_func->GetConstructorCache(static_cast<Js::ProfileId>(newObjInstr->AsProfiledInstr()->u.profileId)) : nullptr;
  3907. if (ctorCache == nullptr)
  3908. {
  3909. if (PHASE_TRACE(Js::FixedNewObjPhase, newObjInstr->m_func->GetJnFunction()) || PHASE_TESTTRACE(Js::FixedNewObjPhase, newObjInstr->m_func->GetJnFunction()))
  3910. {
  3911. Js::FunctionBody* callerFunctionBody = newObjInstr->m_func->GetJnFunction();
  3912. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  3913. Output::Print(L"FixedNewObj: function %s (%s): lowering non-fixed new script object for %s, because %s.\n",
  3914. callerFunctionBody->GetDisplayName(), callerFunctionBody->GetDebugNumberSet(debugStringBuffer), Js::OpCodeUtil::GetOpCodeName(newObjInstr->m_opcode),
  3915. newObjInstr->IsProfiledInstr() ? L"constructor cache hasn't been cloned" : L"instruction is not profiled");
  3916. Output::Flush();
  3917. }
  3918. return false;
  3919. }
  3920. }
  3921. Assert(ctorCache != nullptr);
  3922. // We should only have cloned if the script contexts match.
  3923. Assert(newObjInstr->m_func->GetScriptContext() == ctorCache->scriptContext);
  3924. // Built-in constructors don't need a default new object. Since we know which constructor we're calling, we can skip creating a default
  3925. // object and call a specialized helper (or even constructor, directly) avoiding the checks in generic NewScObjectCommon.
  3926. if (ctorCache->skipNewScObject)
  3927. {
  3928. if (PHASE_TRACE(Js::FixedNewObjPhase, newObjInstr->m_func->GetJnFunction()) || PHASE_TESTTRACE(Js::FixedNewObjPhase, newObjInstr->m_func->GetJnFunction()))
  3929. {
  3930. Js::FunctionBody* callerFunctionBody = newObjInstr->m_func->GetJnFunction();
  3931. const Js::JavascriptFunction* ctor = ctorCache->constructor;
  3932. Js::FunctionBody* ctorBody = ctor->GetFunctionInfo()->HasBody() ? ctor->GetFunctionInfo()->GetFunctionBody() : nullptr;
  3933. const wchar_t* ctorName = ctorBody != nullptr ? ctorBody->GetDisplayName() : L"<unknown>";
  3934. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  3935. wchar_t debugStringBuffer2[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  3936. Output::Print(L"FixedNewObj: function %s (%s): lowering skipped new script object for %s with %s ctor <unknown> (%s %s).\n",
  3937. callerFunctionBody->GetDisplayName(), callerFunctionBody->GetDebugNumberSet(debugStringBuffer2), Js::OpCodeUtil::GetOpCodeName(newObjInstr->m_opcode),
  3938. newObjInstr->m_opcode == Js::OpCode::NewScObjectNoCtor ? L"inlined" : L"called",
  3939. ctorName, ctorBody ? ctorBody->GetDebugNumberSet(debugStringBuffer) : L"(null)");
  3940. Output::Flush();
  3941. }
  3942. // All built-in constructors share a special singleton cache that is never checked and never invalidated. It cannot be used
  3943. // as a guard to protect any property operations downstream from the constructor. If this ever becomes a performance issue,
  3944. // we could have a dedicated cache for each built-in constructor, populate it and invalidate it as any other constructor cache.
  3945. AssertMsg(!emitBailOut, "Can't bail out on constructor cache guard for built-in constructors.");
  3946. skipNewScObj = true;
  3947. IR::AddrOpnd* zeroOpnd = IR::AddrOpnd::NewNull(this->m_func);
  3948. this->m_lowererMD.CreateAssign(newObjDst, zeroOpnd, newObjInstr);
  3949. return true;
  3950. }
  3951. AssertMsg(ctorCache->type != nullptr, "Why did we hard-code a mismatched, invalidated or polymorphic constructor cache?");
  3952. if (PHASE_TRACE(Js::FixedNewObjPhase, newObjInstr->m_func->GetJnFunction()) || PHASE_TESTTRACE(Js::FixedNewObjPhase, newObjInstr->m_func->GetJnFunction()))
  3953. {
  3954. Js::FunctionBody* callerFunctionBody = newObjInstr->m_func->GetJnFunction();
  3955. const Js::JavascriptFunction* constructor = ctorCache->constructor;
  3956. Js::FunctionBody* constructorBody = constructor->GetFunctionInfo()->HasBody() ? constructor->GetFunctionInfo()->GetFunctionBody() : nullptr;
  3957. const wchar_t* constructorName = constructorBody != nullptr ? constructorBody->GetDisplayName() : L"<unknown>";
  3958. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  3959. wchar_t debugStringBuffer2[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  3960. if (PHASE_TRACE(Js::FixedNewObjPhase, newObjInstr->m_func->GetJnFunction()))
  3961. {
  3962. Output::Print(L"FixedNewObj: function %s (%s): lowering fixed new script object for %s with %s ctor <unknown> (%s %s): type = %p, slots = %d, inlined slots = %d.\n",
  3963. callerFunctionBody->GetDisplayName(), callerFunctionBody->GetDebugNumberSet(debugStringBuffer2), Js::OpCodeUtil::GetOpCodeName(newObjInstr->m_opcode),
  3964. newObjInstr->m_opcode == Js::OpCode::NewScObjectNoCtor ? L"inlined" : L"called",
  3965. constructorName, constructorBody ? constructorBody->GetDebugNumberSet(debugStringBuffer) : L"(null)",
  3966. ctorCache->type, ctorCache->slotCount, ctorCache->inlineSlotCount);
  3967. }
  3968. else
  3969. {
  3970. Output::Print(L"FixedNewObj: function %s (%s): lowering fixed new script object for %s with %s ctor <unknown> (%s %s): slots = %d, inlined slots = %d.\n",
  3971. callerFunctionBody->GetDisplayName(), callerFunctionBody->GetDebugNumberSet(debugStringBuffer2), Js::OpCodeUtil::GetOpCodeName(newObjInstr->m_opcode),
  3972. newObjInstr->m_opcode == Js::OpCode::NewScObjectNoCtor ? L"inlined" : L"called",
  3973. constructorName, debugStringBuffer, ctorCache->slotCount, ctorCache->inlineSlotCount);
  3974. }
  3975. Output::Flush();
  3976. }
  3977. // If the constructor has no return statements, we can safely return the object that was created here.
  3978. // No need to check what the constructor returned - it must be undefined.
  3979. returnNewScObj = ctorCache->ctorHasNoExplicitReturnValue;
  3980. Assert(Js::ConstructorCache::GetSizeOfGuardValue() == static_cast<size_t>(TySize[TyMachPtr]));
  3981. IR::MemRefOpnd* guardOpnd = IR::MemRefOpnd::New(const_cast<void*>(ctorCache->runtimeCache->GetAddressOfGuardValue()), TyMachReg, this->m_func,
  3982. IR::AddrOpndKindDynamicGuardValueRef);
  3983. IR::AddrOpnd* zeroOpnd = IR::AddrOpnd::NewNull(this->m_func);
  3984. InsertCompareBranch(guardOpnd, zeroOpnd, Js::OpCode::BrEq_A, helperOrBailoutLabel, newObjInstr);
  3985. // If we are calling new on a class constructor, the contract is that we pass new.target as the 'this' argument.
  3986. // function is the constructor on which we called new - which is new.target.
  3987. Js::JavascriptFunction* ctor = newObjInstr->GetFixedFunction();
  3988. Js::FunctionInfo* functionInfo = Js::JavascriptOperators::GetConstructorFunctionInfo(ctor, this->m_func->GetScriptContext());
  3989. Assert(functionInfo);
  3990. if (functionInfo->IsClassConstructor())
  3991. {
  3992. // MOV newObjDst, function
  3993. this->m_lowererMD.CreateAssign(newObjDst, newObjInstr->GetSrc1(), newObjInstr);
  3994. }
  3995. else
  3996. {
  3997. const Js::DynamicType* newObjectType = ctorCache->type;
  3998. Assert(newObjectType->GetIsShared());
  3999. IR::AddrOpnd* typeSrc = IR::AddrOpnd::New(const_cast<void *>(reinterpret_cast<const void *>(newObjectType)), IR::AddrOpndKindDynamicType, m_func);
  4000. // For the next call:
  4001. // inlineSlotSize == Number of slots to allocate beyond the DynamicObject header
  4002. // slotSize - inlineSlotSize == Number of aux slots to allocate
  4003. int inlineSlotSize = ctorCache->inlineSlotCount;
  4004. int slotSize = ctorCache->slotCount;
  4005. if (newObjectType->GetTypeHandler()->IsObjectHeaderInlinedTypeHandler())
  4006. {
  4007. Assert(inlineSlotSize >= Js::DynamicTypeHandler::GetObjectHeaderInlinableSlotCapacity());
  4008. Assert(inlineSlotSize == slotSize);
  4009. slotSize = inlineSlotSize -= Js::DynamicTypeHandler::GetObjectHeaderInlinableSlotCapacity();
  4010. }
  4011. GenerateDynamicObjectAlloc(newObjInstr, inlineSlotSize, slotSize, newObjDst, typeSrc);
  4012. }
  4013. // JMP $callCtor
  4014. IR::BranchInstr *callCtorBranch = IR::BranchInstr::New(Js::OpCode::Br, callCtorLabel, m_func);
  4015. newObjInstr->InsertBefore(callCtorBranch);
  4016. this->m_lowererMD.LowerUncondBranch(callCtorBranch);
  4017. return true;
  4018. }
  4019. void
  4020. Lowerer::GenerateRecyclerAllocAligned(IR::JnHelperMethod allocHelper, size_t allocSize, IR::RegOpnd* newObjDst, IR::Instr* insertionPointInstr, bool inOpHelper)
  4021. {
  4022. IR::LabelInstr * allocDoneLabel = nullptr;
  4023. if (!PHASE_OFF(Js::JitAllocNewObjPhase, insertionPointInstr->m_func->GetJnFunction()) && HeapInfo::IsSmallObject(allocSize))
  4024. {
  4025. IR::LabelInstr * allocHelperLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  4026. allocDoneLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, inOpHelper);
  4027. this->m_lowererMD.GenerateFastRecyclerAlloc(allocSize, newObjDst, insertionPointInstr, allocHelperLabel, allocDoneLabel);
  4028. // $allocHelper:
  4029. insertionPointInstr->InsertBefore(allocHelperLabel);
  4030. }
  4031. // call JavascriptOperators::AllocMemForScObject(allocSize, scriptContext->GetRecycler())
  4032. this->m_lowererMD.LoadHelperArgument(insertionPointInstr, this->LoadScriptContextValueOpnd(insertionPointInstr, ScriptContextValue::ScriptContextRecycler));
  4033. this->m_lowererMD.LoadHelperArgument(insertionPointInstr, IR::IntConstOpnd::New((int32)allocSize, TyUint32, m_func, true));
  4034. IR::Instr *newObjCall = IR::Instr::New(Js::OpCode::Call, newObjDst, IR::HelperCallOpnd::New(allocHelper, m_func), m_func);
  4035. insertionPointInstr->InsertBefore(newObjCall);
  4036. this->m_lowererMD.LowerCall(newObjCall, 0);
  4037. if (allocDoneLabel != nullptr)
  4038. {
  4039. // $allocDone:
  4040. insertionPointInstr->InsertBefore(allocDoneLabel);
  4041. }
  4042. }
  4043. IR::Instr *
  4044. Lowerer::LowerGetNewScObject(IR::Instr *instr)
  4045. {
  4046. Assert(instr);
  4047. Assert(instr->m_opcode == Js::OpCode::GetNewScObject);
  4048. Assert(instr->GetDst());
  4049. Assert(instr->GetSrc1());
  4050. Assert(instr->GetSrc2());
  4051. const auto instrPrev = instr->m_prev;
  4052. Assert(instrPrev);
  4053. LowerGetNewScObjectCommon(
  4054. instr->GetDst()->AsRegOpnd(),
  4055. instr->GetSrc1()->AsRegOpnd(),
  4056. instr->GetSrc2()->AsRegOpnd(),
  4057. instr);
  4058. instr->Remove();
  4059. return instrPrev;
  4060. }
  4061. void
  4062. Lowerer::LowerGetNewScObjectCommon(
  4063. IR::RegOpnd *const resultObjOpnd,
  4064. IR::RegOpnd *const constructorReturnOpnd,
  4065. IR::RegOpnd *const newObjOpnd,
  4066. IR::Instr *insertBeforeInstr)
  4067. {
  4068. Assert(resultObjOpnd);
  4069. Assert(constructorReturnOpnd);
  4070. Assert(newObjOpnd);
  4071. Assert(insertBeforeInstr);
  4072. // (newObjOpnd == 'this' value passed to constructor)
  4073. //
  4074. // if (!IsJsObject(constructorReturnOpnd))
  4075. // goto notObjectLabel
  4076. // newObjOpnd = constructorReturnOpnd
  4077. // notObjectLabel:
  4078. // resultObjOpnd = newObjOpnd
  4079. if(!constructorReturnOpnd->IsEqual(newObjOpnd))
  4080. {
  4081. // Need to check whether the constructor returned an object
  4082. IR::LabelInstr *notObjectLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  4083. Assert(insertBeforeInstr->m_prev);
  4084. IR::LabelInstr *const doneLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  4085. insertBeforeInstr->InsertBefore(doneLabel);
  4086. insertBeforeInstr = doneLabel;
  4087. #if defined(_M_ARM32_OR_ARM64)
  4088. m_lowererMD.LoadHelperArgument(insertBeforeInstr, constructorReturnOpnd);
  4089. IR::Opnd * targetOpnd = IR::RegOpnd::New(StackSym::New(TyInt32,m_func), TyInt32, m_func);
  4090. IR::Instr * callIsObjectInstr = IR::Instr::New(Js::OpCode::Call, targetOpnd, m_func);
  4091. insertBeforeInstr->InsertBefore(callIsObjectInstr);
  4092. this->m_lowererMD.ChangeToHelperCall(callIsObjectInstr, IR::HelperOp_IsObject);
  4093. InsertTestBranch( targetOpnd, targetOpnd, Js::OpCode::BrEq_A, notObjectLabel,insertBeforeInstr);
  4094. #else
  4095. m_lowererMD.GenerateIsJsObjectTest(constructorReturnOpnd, insertBeforeInstr, notObjectLabel);
  4096. #endif
  4097. // Value returned by constructor is an object (use constructorReturnOpnd)
  4098. if(!resultObjOpnd->IsEqual(constructorReturnOpnd))
  4099. {
  4100. this->m_lowererMD.CreateAssign(resultObjOpnd, constructorReturnOpnd, insertBeforeInstr);
  4101. }
  4102. insertBeforeInstr->InsertBefore(
  4103. m_lowererMD.LowerUncondBranch(IR::BranchInstr::New(Js::OpCode::Br, doneLabel, m_func)));
  4104. // Value returned by constructor is not an object (use newObjOpnd)
  4105. insertBeforeInstr->InsertBefore(notObjectLabel);
  4106. }
  4107. if(!resultObjOpnd->IsEqual(newObjOpnd))
  4108. {
  4109. this->m_lowererMD.CreateAssign(resultObjOpnd, newObjOpnd, insertBeforeInstr);
  4110. }
  4111. // fall through to insertBeforeInstr or doneLabel
  4112. }
  4113. ///----------------------------------------------------------------------------
  4114. ///
  4115. /// Lowerer::LowerUpdateNewScObjectCache
  4116. ///
  4117. ///----------------------------------------------------------------------------
  4118. IR::Instr *
  4119. Lowerer::LowerUpdateNewScObjectCache(IR::Instr * insertInstr, IR::Opnd *dst, IR::Opnd *src1, const bool isCtorFunction)
  4120. {
  4121. // if (!isCtorFunction)
  4122. // {
  4123. // MOV r1, [src1 + offset(type)] -- check base TypeIds_Function
  4124. // CMP [r1 + offset(typeId)], TypeIds_Function
  4125. // }
  4126. // JNE $fallThru
  4127. // MOV r2, [src1 + offset(constructorCache)]
  4128. // MOV r3, [r2 + offset(updateAfterCtor)]
  4129. // TEST r3, r3 -- check if updateAfterCtor is 0
  4130. // JEQ $fallThru
  4131. // CALL UpdateNewScObjectCache(src1, dst, scriptContext)
  4132. // $fallThru:
  4133. IR::LabelInstr *labelFallThru = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  4134. if (!src1->IsRegOpnd())
  4135. {
  4136. IR::RegOpnd *srcRegOpnd = IR::RegOpnd::New(TyMachReg, this->m_func);
  4137. LowererMD::CreateAssign(srcRegOpnd, src1, insertInstr);
  4138. src1 = srcRegOpnd;
  4139. }
  4140. // Check if constructor is a function if we don't already know it.
  4141. if (!isCtorFunction)
  4142. {
  4143. // MOV r1, [src1 + offset(type)] -- check base TypeIds_Function
  4144. IR::RegOpnd *r1 = IR::RegOpnd::New(TyMachReg, this->m_func);
  4145. IR::IndirOpnd *indirOpnd = IR::IndirOpnd::New(src1->AsRegOpnd(), Js::RecyclableObject::GetOffsetOfType(), TyMachReg, this->m_func);
  4146. LowererMD::CreateAssign(r1, indirOpnd, insertInstr);
  4147. // CMP [r1 + offset(typeId)], TypeIds_Function
  4148. // JNE $fallThru
  4149. indirOpnd = IR::IndirOpnd::New(r1, Js::Type::GetOffsetOfTypeId(), TyInt32, this->m_func);
  4150. IR::IntConstOpnd *intOpnd = IR::IntConstOpnd::New(Js::TypeIds_Function, TyInt32, this->m_func, true);
  4151. InsertCompareBranch(indirOpnd, intOpnd, Js::OpCode::BrNeq_A, labelFallThru, insertInstr);
  4152. }
  4153. // Every function has a constructor cache, even if only the default blank one.
  4154. // r2 = MOV JavascriptFunction->constructorCache
  4155. IR::RegOpnd *r2 = IR::RegOpnd::New(TyVar, this->m_func);
  4156. IR::IndirOpnd *opndIndir = IR::IndirOpnd::New(src1->AsRegOpnd(), Js::JavascriptFunction::GetOffsetOfConstructorCache(), TyMachReg, this->m_func);
  4157. IR::Instr *instr = LowererMD::CreateAssign(r2, opndIndir, insertInstr);
  4158. // r3 = constructorCache->updateAfterCtor
  4159. IR::RegOpnd *r3 = IR::RegOpnd::New(TyInt8, this->m_func);
  4160. IR::IndirOpnd *indirOpnd = IR::IndirOpnd::New(r2, Js::ConstructorCache::GetOffsetOfUpdateAfterCtor(), TyUint8, this->m_func);
  4161. instr = LowererMD::CreateAssign(r3, indirOpnd, insertInstr);
  4162. // TEST r3, r3 -- check if updateAfterCtor is 0
  4163. // JEQ $fallThru
  4164. InsertTestBranch(r3, r3, Js::OpCode::BrEq_A, labelFallThru, insertInstr);
  4165. // r2 = UpdateNewScObjectCache(src1, dst, scriptContext)
  4166. insertInstr->InsertBefore(IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true)); // helper label for uncommon path
  4167. IR::HelperCallOpnd * opndHelper = IR::HelperCallOpnd::New(IR::HelperUpdateNewScObjectCache, m_func);
  4168. LoadScriptContext(insertInstr);
  4169. m_lowererMD.LoadHelperArgument(insertInstr, dst);
  4170. m_lowererMD.LoadHelperArgument(insertInstr, src1);
  4171. instr = IR::Instr::New(Js::OpCode::Call, m_func);
  4172. instr->SetSrc1(opndHelper);
  4173. insertInstr->InsertBefore(instr);
  4174. m_lowererMD.LowerCall(instr, 0);
  4175. // $fallThru:
  4176. insertInstr->InsertBefore(labelFallThru);
  4177. return insertInstr;
  4178. }
  4179. IR::Instr *
  4180. Lowerer::LowerNewScObjArray(IR::Instr *newObjInstr)
  4181. {
  4182. IR::Instr* startCallInstr;
  4183. if (newObjInstr->HasEmptyArgOutChain(&startCallInstr))
  4184. {
  4185. newObjInstr->FreeSrc2();
  4186. return LowerNewScObjArrayNoArg(newObjInstr);
  4187. }
  4188. IR::Instr* startMarkerInstr = nullptr;
  4189. IR::Opnd *targetOpnd = newObjInstr->GetSrc1();
  4190. Func *func = newObjInstr->m_func;
  4191. if (!targetOpnd->IsAddrOpnd())
  4192. {
  4193. if (!newObjInstr->HasBailOutInfo())
  4194. {
  4195. return this->LowerNewScObject(newObjInstr, true, true);
  4196. }
  4197. // Insert a temporary label before the instruction we're about to lower, so that we can return
  4198. // the first instruction above that needs to be lowered after we're done - regardless of argument
  4199. // list, StartCall, etc.
  4200. startMarkerInstr = InsertLoweredRegionStartMarker(newObjInstr);
  4201. // For whatever reason, we couldn't do a fixed function check on the call target.
  4202. // Generate a runtime check on the target.
  4203. Assert(newObjInstr->GetBailOutKind() == IR::BailOutOnNotNativeArray);
  4204. IR::LabelInstr *labelSkipBailOut = IR::LabelInstr::New(Js::OpCode::Label, func);
  4205. InsertCompareBranch(
  4206. targetOpnd,
  4207. LoadLibraryValueOpnd(newObjInstr, LibraryValue::ValueArrayConstructor),
  4208. Js::OpCode::BrEq_A,
  4209. true,
  4210. labelSkipBailOut,
  4211. newObjInstr);
  4212. IR::ProfiledInstr *instrNew = IR::ProfiledInstr::New(newObjInstr->m_opcode, newObjInstr->UnlinkDst(), newObjInstr->UnlinkSrc1(), newObjInstr->UnlinkSrc2(), func);
  4213. instrNew->u.profileId = newObjInstr->AsProfiledInstr()->u.profileId;
  4214. newObjInstr->InsertAfter(instrNew);
  4215. newObjInstr->m_opcode = Js::OpCode::BailOut;
  4216. GenerateBailOut(newObjInstr);
  4217. instrNew->InsertBefore(labelSkipBailOut);
  4218. newObjInstr = instrNew;
  4219. }
  4220. else
  4221. {
  4222. // Insert a temporary label before the instruction we're about to lower, so that we can return
  4223. // the first instruction above that needs to be lowered after we're done - regardless of argument
  4224. // list, StartCall, etc.
  4225. startMarkerInstr = InsertLoweredRegionStartMarker(newObjInstr);
  4226. }
  4227. RecyclerWeakReference<Js::FunctionBody> *weakFuncRef = nullptr;
  4228. Js::ArrayCallSiteInfo *arrayInfo = nullptr;
  4229. Assert(newObjInstr->IsProfiledInstr());
  4230. IR::RegOpnd *resultObjOpnd = newObjInstr->GetDst()->AsRegOpnd();
  4231. IR::Instr * insertInstr = newObjInstr->m_next;
  4232. Js::ProfileId profileId = static_cast<Js::ProfileId>(newObjInstr->AsProfiledInstr()->u.profileId);
  4233. // We may not have profileId if we converted a NewScObject to NewScObjArray
  4234. if (profileId != Js::Constants::NoProfileId)
  4235. {
  4236. Js::FunctionBody *functionBody = func->GetJnFunction();
  4237. arrayInfo = functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, profileId);
  4238. Assert(arrayInfo);
  4239. weakFuncRef = func->GetWeakFuncRef();
  4240. Assert(weakFuncRef);
  4241. }
  4242. IR::Opnd *opndSrc1 = newObjInstr->UnlinkSrc1();
  4243. if (opndSrc1->IsImmediateOpnd())
  4244. {
  4245. intptr_t length = opndSrc1->GetImmediateValue();
  4246. if (length >= 0 && length <= 8)
  4247. {
  4248. GenerateProfiledNewScObjArrayFastPath(newObjInstr, arrayInfo, weakFuncRef, (uint32)length);
  4249. }
  4250. }
  4251. IR::Opnd *profileOpnd = IR::AddrOpnd::New(arrayInfo, IR::AddrOpndKindDynamicArrayCallSiteInfo, func);
  4252. this->m_lowererMD.LoadNewScObjFirstArg(newObjInstr, profileOpnd);
  4253. IR::JnHelperMethod helperMethod = IR::HelperScrArr_ProfiledNewInstance;
  4254. newObjInstr->SetSrc1(IR::HelperCallOpnd::New(helperMethod, func));
  4255. newObjInstr = GenerateDirectCall(newObjInstr, targetOpnd, Js::CallFlags_New);
  4256. IR::LabelInstr *labelDone = IR::LabelInstr::New(Js::OpCode::Label, func);
  4257. InsertCompareBranch(
  4258. IR::IndirOpnd::New(resultObjOpnd, 0, TyMachPtr, func),
  4259. LoadVTableValueOpnd(insertInstr, VTableValue::VtableJavascriptArray),
  4260. Js::OpCode::BrEq_A,
  4261. true,
  4262. labelDone,
  4263. insertInstr);
  4264. // We know we have a native array, so store the weak ref and call site index.
  4265. m_lowererMD.CreateAssign(
  4266. IR::IndirOpnd::New(resultObjOpnd, Js::JavascriptNativeArray::GetOffsetOfArrayCallSiteIndex(), TyUint16, func),
  4267. IR::Opnd::CreateProfileIdOpnd(profileId, func),
  4268. insertInstr);
  4269. m_lowererMD.CreateAssign(
  4270. IR::IndirOpnd::New(resultObjOpnd, Js::JavascriptNativeArray::GetOffsetOfWeakFuncRef(), TyMachReg, func),
  4271. IR::AddrOpnd::New(weakFuncRef, IR::AddrOpndKindDynamicFunctionBodyWeakRef, func),
  4272. insertInstr);
  4273. insertInstr->InsertBefore(labelDone);
  4274. return RemoveLoweredRegionStartMarker(startMarkerInstr);
  4275. }
  4276. IR::Instr *
  4277. Lowerer::LowerNewScObjArrayNoArg(IR::Instr *newObjInstr)
  4278. {
  4279. IR::Opnd *targetOpnd = newObjInstr->GetSrc1();
  4280. Func *func = newObjInstr->m_func;
  4281. IR::Instr* startMarkerInstr = nullptr;
  4282. if (!targetOpnd->IsAddrOpnd())
  4283. {
  4284. if (!newObjInstr->HasBailOutInfo())
  4285. {
  4286. return this->LowerNewScObject(newObjInstr, true, false);
  4287. }
  4288. // Insert a temporary label before the instruction we're about to lower, so that we can return
  4289. // the first instruction above that needs to be lowered after we're done - regardless of argument
  4290. // list, StartCall, etc.
  4291. startMarkerInstr = InsertLoweredRegionStartMarker(newObjInstr);
  4292. // For whatever reason, we couldn't do a fixed function check on the call target.
  4293. // Generate a runtime check on the target.
  4294. Assert(newObjInstr->GetBailOutKind() == IR::BailOutOnNotNativeArray);
  4295. IR::LabelInstr *labelSkipBailOut = IR::LabelInstr::New(Js::OpCode::Label, func);
  4296. InsertCompareBranch(
  4297. targetOpnd,
  4298. LoadLibraryValueOpnd(newObjInstr, LibraryValue::ValueArrayConstructor),
  4299. Js::OpCode::BrEq_A,
  4300. true,
  4301. labelSkipBailOut,
  4302. newObjInstr);
  4303. IR::ProfiledInstr *instrNew = IR::ProfiledInstr::New(newObjInstr->m_opcode, newObjInstr->UnlinkDst(), newObjInstr->UnlinkSrc1(), func);
  4304. instrNew->u.profileId = newObjInstr->AsProfiledInstr()->u.profileId;
  4305. newObjInstr->InsertAfter(instrNew);
  4306. newObjInstr->m_opcode = Js::OpCode::BailOut;
  4307. GenerateBailOut(newObjInstr);
  4308. instrNew->InsertBefore(labelSkipBailOut);
  4309. newObjInstr = instrNew;
  4310. }
  4311. else
  4312. {
  4313. // Insert a temporary label before the instruction we're about to lower, so that we can return
  4314. // the first instruction above that needs to be lowered after we're done - regardless of argument
  4315. // list, StartCall, etc.
  4316. startMarkerInstr = InsertLoweredRegionStartMarker(newObjInstr);
  4317. }
  4318. Assert(newObjInstr->IsProfiledInstr());
  4319. RecyclerWeakReference<Js::FunctionBody> *weakFuncRef = nullptr;
  4320. Js::ArrayCallSiteInfo *arrayInfo = nullptr;
  4321. Js::ProfileId profileId = static_cast<Js::ProfileId>(newObjInstr->AsProfiledInstr()->u.profileId);
  4322. if (profileId != Js::Constants::NoProfileId)
  4323. {
  4324. Js::FunctionBody *functionBody = func->GetJnFunction();
  4325. arrayInfo = functionBody->GetAnyDynamicProfileInfo()->GetArrayCallSiteInfo(functionBody, profileId);
  4326. Assert(arrayInfo);
  4327. weakFuncRef = func->GetWeakFuncRef();
  4328. Assert(weakFuncRef);
  4329. }
  4330. GenerateProfiledNewScObjArrayFastPath(newObjInstr, arrayInfo, weakFuncRef, 0);
  4331. m_lowererMD.LoadHelperArgument(newObjInstr, IR::AddrOpnd::New(weakFuncRef, IR::AddrOpndKindDynamicFunctionBodyWeakRef, func));
  4332. m_lowererMD.LoadHelperArgument(newObjInstr, IR::AddrOpnd::New(arrayInfo, IR::AddrOpndKindDynamicArrayCallSiteInfo, func));
  4333. LoadScriptContext(newObjInstr);
  4334. m_lowererMD.LoadHelperArgument(newObjInstr, targetOpnd);
  4335. newObjInstr->UnlinkSrc1();
  4336. newObjInstr->SetSrc1(IR::HelperCallOpnd::New(IR::HelperScrArr_ProfiledNewInstanceNoArg, func));
  4337. m_lowererMD.LowerCall(newObjInstr, 0);
  4338. return RemoveLoweredRegionStartMarker(startMarkerInstr);
  4339. }
  4340. ///----------------------------------------------------------------------------
  4341. ///
  4342. /// Lowerer::LowerPrologEpilog
  4343. ///
  4344. ///----------------------------------------------------------------------------
  4345. void
  4346. Lowerer::LowerPrologEpilog()
  4347. {
  4348. if (m_func->GetJnFunction()->IsGenerator())
  4349. {
  4350. LowerGeneratorResumeJumpTable();
  4351. }
  4352. IR::Instr * instr;
  4353. instr = m_func->m_headInstr;
  4354. AssertMsg(instr->IsEntryInstr(), "First instr isn't an EntryInstr...");
  4355. m_lowererMD.LowerEntryInstr(instr->AsEntryInstr());
  4356. instr = m_func->m_exitInstr;
  4357. AssertMsg(instr->IsExitInstr(), "Last instr isn't an ExitInstr...");
  4358. m_lowererMD.LowerExitInstr(instr->AsExitInstr());
  4359. }
  4360. void
  4361. Lowerer::LowerPrologEpilogAsmJs()
  4362. {
  4363. IR::Instr * instr;
  4364. instr = m_func->m_headInstr;
  4365. AssertMsg(instr->IsEntryInstr(), "First instr isn't an EntryInstr...");
  4366. m_lowererMD.LowerEntryInstrAsmJs(instr->AsEntryInstr());
  4367. instr = m_func->m_exitInstr;
  4368. AssertMsg(instr->IsExitInstr(), "Last instr isn't an ExitInstr...");
  4369. m_lowererMD.LowerExitInstrAsmJs(instr->AsExitInstr());
  4370. }
  4371. void
  4372. Lowerer::LowerGeneratorResumeJumpTable()
  4373. {
  4374. Assert(m_func->GetJnFunction()->IsGenerator());
  4375. IR::Instr * jumpTableInstr = m_func->m_headInstr;
  4376. AssertMsg(jumpTableInstr->IsEntryInstr(), "First instr isn't an EntryInstr...");
  4377. // Hope to do away with this linked list scan by moving this lowering to a post-prolog-epilog/pre-encoder phase that is common to all architectures (currently such phase is only available on amd64/arm)
  4378. while (jumpTableInstr->m_opcode != Js::OpCode::GeneratorResumeJumpTable)
  4379. {
  4380. jumpTableInstr = jumpTableInstr->m_next;
  4381. }
  4382. IR::Opnd * srcOpnd = jumpTableInstr->UnlinkSrc1();
  4383. m_func->MapYieldOffsetResumeLabels([&](int i, const YieldOffsetResumeLabel& yorl)
  4384. {
  4385. uint32 offset = yorl.First();
  4386. IR::LabelInstr * label = yorl.Second();
  4387. if (label != nullptr && label->m_hasNonBranchRef)
  4388. {
  4389. // Also fix up the bailout at the label with the jump to epilog that was not emitted in GenerateBailOut()
  4390. Assert(label->m_prev->HasBailOutInfo());
  4391. GenerateJumpToEpilogForBailOut(label->m_prev->GetBailOutInfo(), label->m_prev);
  4392. }
  4393. else if (label == nullptr)
  4394. {
  4395. label = m_func->m_bailOutNoSaveLabel;
  4396. }
  4397. // For each offset label pair, insert a compare of the offset and branch if equal to the label
  4398. InsertCompareBranch(srcOpnd, IR::IntConstOpnd::New(offset, TyUint32, m_func), Js::OpCode::BrSrEq_A, label, jumpTableInstr);
  4399. });
  4400. jumpTableInstr->Remove();
  4401. }
  4402. void
  4403. Lowerer::DoInterruptProbes()
  4404. {
  4405. this->m_func->SetHasInstrNumber(true);
  4406. uint instrCount = 1;
  4407. FOREACH_INSTR_IN_FUNC(instr, this->m_func)
  4408. {
  4409. instr->SetNumber(instrCount++);
  4410. if (instr->IsLabelInstr())
  4411. {
  4412. IR::LabelInstr *labelInstr = instr->AsLabelInstr();
  4413. if (labelInstr->m_isLoopTop)
  4414. {
  4415. // For every loop top label, insert the following:
  4416. // cmp sp, ThreadContext::stackLimitForCurrentThread
  4417. // bgt $continue
  4418. // $helper:
  4419. // call JavascriptOperators::ScriptAbort
  4420. // b $exit
  4421. // $continue:
  4422. IR::LabelInstr *newLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  4423. labelInstr->InsertAfter(newLabel);
  4424. this->InsertOneLoopProbe(newLabel, newLabel);
  4425. }
  4426. }
  4427. }
  4428. NEXT_INSTR_IN_FUNC;
  4429. }
  4430. // Insert an interrupt probe at each loop back branch. (Currently uncalled, since we're inserting
  4431. // probes at loop tops instead of back edges, but kept around because it may prove useful.)
  4432. uint
  4433. Lowerer::DoLoopProbeAndNumber(IR::BranchInstr *branchInstr)
  4434. {
  4435. IR::LabelInstr *labelInstr = branchInstr->GetTarget();
  4436. if (labelInstr == nullptr || labelInstr->GetNumber() == 0)
  4437. {
  4438. // Forward branch (possibly an indirect jump after try-catch-finally); nothing to do.
  4439. return branchInstr->GetNumber() + 1;
  4440. }
  4441. Assert(labelInstr->m_isLoopTop);
  4442. // Insert a stack probe at this branch. Number all the instructions we insert
  4443. // and return the next instruction number.
  4444. uint number = branchInstr->GetNumber();
  4445. IR::Instr *instrPrev = branchInstr->m_prev;
  4446. IR::Instr *instrNext = branchInstr->m_next;
  4447. if (branchInstr->IsUnconditional())
  4448. {
  4449. // B $loop ==>
  4450. // cmp [], 0
  4451. // beq $loop
  4452. // $helper:
  4453. // call abort
  4454. // b $exit
  4455. this->InsertOneLoopProbe(branchInstr, labelInstr);
  4456. branchInstr->Remove();
  4457. }
  4458. else
  4459. {
  4460. // Bcc $loop ==>
  4461. // Binv $notloop
  4462. // cmp [], 0
  4463. // beq $loop
  4464. // $helper:
  4465. // call abort
  4466. // b $exit
  4467. // $notloop:
  4468. IR::LabelInstr *loopExitLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  4469. branchInstr->SetTarget(loopExitLabel);
  4470. LowererMD::InvertBranch(branchInstr);
  4471. branchInstr->InsertAfter(loopExitLabel);
  4472. this->InsertOneLoopProbe(loopExitLabel, labelInstr);
  4473. }
  4474. FOREACH_INSTR_IN_RANGE(instr, instrPrev->m_next, instrNext->m_prev)
  4475. {
  4476. instr->SetNumber(number++);
  4477. }
  4478. NEXT_INSTR_IN_RANGE;
  4479. return number;
  4480. }
  4481. void
  4482. Lowerer::InsertOneLoopProbe(IR::Instr *insertInstr, IR::LabelInstr *loopLabel)
  4483. {
  4484. // Insert one interrupt probe at the given instruction. Probe the stack and call the abort helper
  4485. // directly if the probe fails.
  4486. IR::Opnd *memRefOpnd = IR::MemRefOpnd::New(
  4487. this->m_func->GetScriptContext()->GetThreadContext()->GetAddressOfStackLimitForCurrentThread(),
  4488. TyMachReg, this->m_func);
  4489. IR::RegOpnd *regStackPointer = IR::RegOpnd::New(
  4490. NULL, this->m_lowererMD.GetRegStackPointer(), TyMachReg, this->m_func);
  4491. InsertCompareBranch(regStackPointer, memRefOpnd, Js::OpCode::BrGt_A, loopLabel, insertInstr);
  4492. IR::LabelInstr *helperLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  4493. insertInstr->InsertBefore(helperLabel);
  4494. IR::HelperCallOpnd *helperOpnd = IR::HelperCallOpnd::New(IR::HelperScriptAbort, this->m_func);
  4495. IR::Instr *instr = IR::Instr::New(Js::OpCode::Call, this->m_func);
  4496. instr->SetSrc1(helperOpnd);
  4497. insertInstr->InsertBefore(instr);
  4498. this->m_lowererMD.LowerCall(instr, 0);
  4499. // Jump to the exit after the helper call. This instruction will never be reached, but the jump
  4500. // indicates that nothing is live after the call (to avoid useless spills in code that will
  4501. // be executed).
  4502. instr = this->m_func->m_exitInstr->GetPrevRealInstrOrLabel();
  4503. if (instr->IsLabelInstr())
  4504. {
  4505. helperLabel = instr->AsLabelInstr();
  4506. }
  4507. else
  4508. {
  4509. helperLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  4510. this->m_func->m_exitInstr->InsertBefore(helperLabel);
  4511. }
  4512. instr = IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, helperLabel, this->m_func);
  4513. insertInstr->InsertBefore(instr);
  4514. }
  4515. ///----------------------------------------------------------------------------
  4516. ///
  4517. /// Lowerer::LoadPropertySymAsArgument
  4518. ///
  4519. /// Generate code to pass a fieldSym as argument to a helper.
  4520. ///----------------------------------------------------------------------------
  4521. IR::Instr *
  4522. Lowerer::LoadPropertySymAsArgument(IR::Instr *instr, IR::Opnd *fieldSrc)
  4523. {
  4524. IR::Instr * instrPrev;
  4525. AssertMsg(fieldSrc->IsSymOpnd() && fieldSrc->AsSymOpnd()->m_sym->IsPropertySym(), "Expected fieldSym as src of LdFld");
  4526. IR::SymOpnd *symOpnd = fieldSrc->AsSymOpnd();
  4527. PropertySym * fieldSym = symOpnd->m_sym->AsPropertySym();
  4528. IR::IntConstOpnd * indexOpnd = IR::IntConstOpnd::New(fieldSym->m_propertyId, TyInt32, m_func, /*dontEncode*/true);
  4529. instrPrev = m_lowererMD.LoadHelperArgument(instr, indexOpnd);
  4530. IR::RegOpnd * instanceOpnd = symOpnd->CreatePropertyOwnerOpnd(m_func);
  4531. m_lowererMD.LoadHelperArgument(instr, instanceOpnd);
  4532. return instrPrev;
  4533. }
  4534. ///----------------------------------------------------------------------------
  4535. ///
  4536. /// Lowerer::LoadFunctionBodyAsArgument
  4537. ///
  4538. /// Special case: the "property ID" is a key into the ScriptContext's FunctionBody map
  4539. ///----------------------------------------------------------------------------
  4540. IR::Instr *
  4541. Lowerer::LoadFunctionBodyAsArgument(IR::Instr *instr, IR::IntConstOpnd * functionBodySlotOpnd, IR::RegOpnd * envOpnd)
  4542. {
  4543. IR::Instr * instrPrev;
  4544. // We need to pass in the function reference, we can't embed the pointer to the function proxy here.
  4545. // The function proxy may be deferred parsed/serialize, and may 'progress' to a real function body after it is undeferred
  4546. // At which point the deferred function proxy may be collect.
  4547. // Just pass it the address where we will find the function proxy/body
  4548. Js::FunctionProxyPtrPtr proxyRef = instr->m_func->GetJnFunction()->GetNestedFuncReference((uint)functionBodySlotOpnd->GetValue());
  4549. AssertMsg(proxyRef, "Expected FunctionProxy for index of NewScFunc or NewScGenFunc opnd");
  4550. AssertMsg(*proxyRef, "Expected FunctionProxy for index of NewScFunc or NewScGenFunc opnd");
  4551. IR::AddrOpnd * indexOpnd = IR::AddrOpnd::New((Js::Var)proxyRef, IR::AddrOpndKindDynamicMisc, m_func);
  4552. instrPrev = m_lowererMD.LoadHelperArgument(instr, indexOpnd);
  4553. m_lowererMD.LoadHelperArgument(instr, envOpnd);
  4554. return instrPrev;
  4555. }
  4556. IR::Instr *
  4557. Lowerer::LowerProfiledLdFld(IR::JitProfilingInstr *ldFldInstr)
  4558. {
  4559. const auto instrPrev = ldFldInstr->m_prev;
  4560. auto src = ldFldInstr->UnlinkSrc1();
  4561. AssertMsg(src->IsSymOpnd() && src->AsSymOpnd()->m_sym->IsPropertySym(), "Expected property sym as src");
  4562. IR::JnHelperMethod helper;
  4563. switch (ldFldInstr->m_opcode)
  4564. {
  4565. case Js::OpCode::LdFld:
  4566. helper = IR::HelperProfiledLdFld;
  4567. goto ldFldCommon;
  4568. case Js::OpCode::LdRootFld:
  4569. helper = IR::HelperProfiledLdRootFld;
  4570. goto ldFldCommon;
  4571. case Js::OpCode::LdMethodFld:
  4572. helper = IR::HelperProfiledLdMethodFld;
  4573. goto ldFldCommon;
  4574. case Js::OpCode::LdRootMethodFld:
  4575. helper = IR::HelperProfiledLdRootMethodFld;
  4576. goto ldFldCommon;
  4577. case Js::OpCode::LdFldForCallApplyTarget:
  4578. helper = IR::HelperProfiledLdFld_CallApplyTarget;
  4579. goto ldFldCommon;
  4580. case Js::OpCode::LdFldForTypeOf:
  4581. helper = IR::HelperProfiledLdFldForTypeOf;
  4582. goto ldFldCommon;
  4583. case Js::OpCode::LdRootFldForTypeOf:
  4584. helper = IR::HelperProfiledLdRootFldForTypeOf;
  4585. goto ldFldCommon;
  4586. ldFldCommon:
  4587. {
  4588. Assert(ldFldInstr->profileId == Js::Constants::NoProfileId);
  4589. /*
  4590. Var ProfilingHelpers::ProfiledLdFld_Jit(
  4591. const Var instance,
  4592. const PropertyId propertyId,
  4593. const InlineCacheIndex inlineCacheIndex,
  4594. void *const framePointer)
  4595. */
  4596. m_lowererMD.LoadHelperArgument(ldFldInstr, IR::Opnd::CreateFramePointerOpnd(m_func));
  4597. m_lowererMD.LoadHelperArgument(
  4598. ldFldInstr,
  4599. IR::Opnd::CreateInlineCacheIndexOpnd(src->AsPropertySymOpnd()->m_inlineCacheIndex, m_func));
  4600. LoadPropertySymAsArgument(ldFldInstr, src);
  4601. break;
  4602. }
  4603. case Js::OpCode::LdSuperFld:
  4604. {
  4605. Assert(ldFldInstr->profileId == Js::Constants::NoProfileId);
  4606. IR::Opnd * src2 = nullptr;
  4607. /*
  4608. Var ProfilingHelpers::ProfiledLdSuperFld_Jit(
  4609. const Var instance,
  4610. const PropertyId propertyId,
  4611. const InlineCacheIndex inlineCacheIndex,
  4612. void *const framePointer,
  4613. const Var thisInstance)
  4614. */
  4615. src2 = ldFldInstr->UnlinkSrc2();
  4616. m_lowererMD.LoadHelperArgument(ldFldInstr, src2 );
  4617. m_lowererMD.LoadHelperArgument(ldFldInstr, IR::Opnd::CreateFramePointerOpnd(m_func));
  4618. m_lowererMD.LoadHelperArgument(
  4619. ldFldInstr,
  4620. IR::Opnd::CreateInlineCacheIndexOpnd(src->AsPropertySymOpnd()->m_inlineCacheIndex, m_func));
  4621. LoadPropertySymAsArgument(ldFldInstr, src);
  4622. helper = IR::HelperProfiledLdSuperFld;
  4623. break;
  4624. }
  4625. case Js::OpCode::LdLen_A:
  4626. // If we want to profile this call, then push some extra args and call the profiling version
  4627. m_lowererMD.LoadHelperArgument(ldFldInstr, IR::Opnd::CreateProfileIdOpnd(ldFldInstr->profileId, m_func));
  4628. m_lowererMD.LoadHelperArgument(ldFldInstr, src->AsSymOpnd()->CreatePropertyOwnerOpnd(m_func));
  4629. m_lowererMD.LoadHelperArgument(ldFldInstr, CreateFunctionBodyOpnd(ldFldInstr->m_func));
  4630. helper = IR::HelperSimpleProfiledLdLen;
  4631. break;
  4632. default:
  4633. Assert(false);
  4634. __assume(false);
  4635. }
  4636. ldFldInstr->SetSrc1(IR::HelperCallOpnd::New(helper, m_func));
  4637. m_lowererMD.LowerCall(ldFldInstr, 0);
  4638. return instrPrev;
  4639. }
  4640. ///----------------------------------------------------------------------------
  4641. ///
  4642. /// Lowerer::LowerLdFld
  4643. ///
  4644. /// Lower an instruction (LdFld, ScopedLdFld) that takes a property
  4645. /// reference as a source and puts a result in a register.
  4646. ///
  4647. ///----------------------------------------------------------------------------
  4648. IR::Instr *
  4649. Lowerer::LowerLdFld(
  4650. IR::Instr * ldFldInstr,
  4651. IR::JnHelperMethod helperMethod,
  4652. IR::JnHelperMethod polymorphicHelperMethod,
  4653. bool useInlineCache,
  4654. IR::LabelInstr *labelBailOut,
  4655. bool isHelper)
  4656. {
  4657. if (ldFldInstr->IsJitProfilingInstr())
  4658. {
  4659. // If we want to profile then do something completely different
  4660. return this->LowerProfiledLdFld(ldFldInstr->AsJitProfilingInstr());
  4661. }
  4662. IR::Opnd *src;
  4663. IR::Instr *instrPrev = ldFldInstr->m_prev;
  4664. src = ldFldInstr->UnlinkSrc1();
  4665. if (ldFldInstr->m_opcode == Js::OpCode::LdSuperFld)
  4666. {
  4667. IR::Opnd * src2 = nullptr;
  4668. src2 = ldFldInstr->UnlinkSrc2();
  4669. m_lowererMD.LoadHelperArgument(ldFldInstr, src2);
  4670. }
  4671. AssertMsg(src->IsSymOpnd() && src->AsSymOpnd()->m_sym->IsPropertySym(), "Expected property sym as src");
  4672. if (useInlineCache)
  4673. {
  4674. IR::Opnd * inlineCacheOpnd;
  4675. AssertMsg(src->AsSymOpnd()->IsPropertySymOpnd(), "Need property sym operand to find the inline cache");
  4676. if (src->AsPropertySymOpnd()->m_runtimePolymorphicInlineCache && polymorphicHelperMethod != helperMethod)
  4677. {
  4678. Js::PolymorphicInlineCache * polymorphicInlineCache = src->AsPropertySymOpnd()->m_runtimePolymorphicInlineCache;
  4679. helperMethod = polymorphicHelperMethod;
  4680. inlineCacheOpnd = IR::AddrOpnd::New(polymorphicInlineCache, IR::AddrOpndKindDynamicInlineCache, this->m_func);
  4681. }
  4682. else
  4683. {
  4684. // Need to load runtime inline cache opnd first before loading any helper argument
  4685. // because LoadRuntimeInlineCacheOpnd may create labels marked as helper,
  4686. // and cause op helper register push/pop save in x86, messing up with any helper arguments that is already pushed
  4687. inlineCacheOpnd = this->LoadRuntimeInlineCacheOpnd(ldFldInstr, src->AsPropertySymOpnd(), isHelper);
  4688. }
  4689. this->LoadPropertySymAsArgument(ldFldInstr, src);
  4690. this-> m_lowererMD.LoadHelperArgument(
  4691. ldFldInstr,
  4692. IR::Opnd::CreateInlineCacheIndexOpnd(src->AsPropertySymOpnd()->m_inlineCacheIndex, m_func));
  4693. this->m_lowererMD.LoadHelperArgument(ldFldInstr, inlineCacheOpnd);
  4694. this->m_lowererMD.LoadHelperArgument(ldFldInstr, LoadFunctionBodyOpnd(ldFldInstr));
  4695. }
  4696. else
  4697. {
  4698. LoadScriptContext(ldFldInstr);
  4699. this->LoadPropertySymAsArgument(ldFldInstr, src);
  4700. }
  4701. // Do we need to reload the type and slot array after the helper returns?
  4702. // (We do if there's a propertySymOpnd downstream that needs it, i.e., the type is not dead.)
  4703. IR::RegOpnd *opndBase = src->AsSymOpnd()->CreatePropertyOwnerOpnd(m_func);
  4704. m_lowererMD.ChangeToHelperCall(ldFldInstr, helperMethod, labelBailOut, opndBase, src->AsSymOpnd()->IsPropertySymOpnd() ? src->AsSymOpnd()->AsPropertySymOpnd() : nullptr, isHelper);
  4705. return instrPrev;
  4706. }
  4707. bool
  4708. Lowerer::GenerateLdFldWithCachedType(IR::Instr * instrLdFld, bool* continueAsHelperOut, IR::LabelInstr** labelHelperOut, IR::RegOpnd** typeOpndOut)
  4709. {
  4710. IR::Instr *instr;
  4711. IR::Opnd *opnd;
  4712. IR::LabelInstr *labelObjCheckFailed = nullptr;
  4713. IR::LabelInstr *labelTypeCheckFailed = nullptr;
  4714. IR::LabelInstr *labelDone = nullptr;
  4715. Assert(continueAsHelperOut != nullptr);
  4716. *continueAsHelperOut = false;
  4717. Assert(labelHelperOut != nullptr);
  4718. *labelHelperOut = nullptr;
  4719. Assert(typeOpndOut != nullptr);
  4720. *typeOpndOut = nullptr;
  4721. Assert(instrLdFld->GetSrc1()->IsSymOpnd());
  4722. if (!instrLdFld->GetSrc1()->AsSymOpnd()->IsPropertySymOpnd())
  4723. {
  4724. return false;
  4725. }
  4726. IR::PropertySymOpnd *propertySymOpnd = instrLdFld->GetSrc1()->AsPropertySymOpnd();
  4727. if (!propertySymOpnd->IsTypeCheckSeqCandidate())
  4728. {
  4729. return false;
  4730. }
  4731. AssertMsg(propertySymOpnd->TypeCheckSeqBitsSetOnlyIfCandidate(), "Property sym operand optimized despite not being a candidate?");
  4732. if (!propertySymOpnd->IsTypeCheckSeqParticipant() && !propertySymOpnd->NeedsLocalTypeCheck())
  4733. {
  4734. return false;
  4735. }
  4736. Assert(!propertySymOpnd->NeedsTypeCheckAndBailOut() || (instrLdFld->HasBailOutInfo() && IR::IsTypeCheckBailOutKind(instrLdFld->GetBailOutKind())));
  4737. // In the backwards pass we only add guarded property operations to instructions that are not already
  4738. // protected by an upstream type check.
  4739. Assert(!propertySymOpnd->IsTypeCheckProtected() || propertySymOpnd->GetGuardedPropOps() == nullptr);
  4740. PHASE_PRINT_TESTTRACE(
  4741. Js::ObjTypeSpecPhase,
  4742. this->m_func,
  4743. L"Field load: %s, property: %s, func: %s, cache ID: %d, cloned cache: true, layout: %s, redundant check: %s\n",
  4744. Js::OpCodeUtil::GetOpCodeName(instrLdFld->m_opcode),
  4745. this->m_func->GetScriptContext()->GetPropertyNameLocked(
  4746. propertySymOpnd->m_sym->AsPropertySym()->m_propertyId)->GetBuffer(),
  4747. this->m_func->GetJnFunction()->GetDisplayName(),
  4748. propertySymOpnd->m_inlineCacheIndex,
  4749. propertySymOpnd->GetCacheLayoutString(),
  4750. propertySymOpnd->IsTypeChecked() ? L"true" : L"false");
  4751. if (propertySymOpnd->HasFinalType() && !propertySymOpnd->IsLoadedFromProto())
  4752. {
  4753. propertySymOpnd->UpdateSlotForFinalType();
  4754. }
  4755. // TODO (ObjTypeSpec): If ((PropertySym*)propertySymOpnd->m_sym)->m_stackSym->m_isIntConst consider emitting a direct
  4756. // jump to helper or bailout. If we have a type check bailout, we could even abort compilation.
  4757. bool hasTypeCheckBailout = instrLdFld->HasBailOutInfo() && IR::IsTypeCheckBailOutKind(instrLdFld->GetBailOutKind());
  4758. // If the hard-coded type is not available here, do a type check, and branch to the helper if the check fails.
  4759. // In the prototype case, we have to check the type even if it was checked upstream, to cover the case where
  4760. // the property has been added locally. Note that this is not necessary if the proto chain has been checked,
  4761. // because then we know there's been no store of the property since the type was checked.
  4762. bool emitPrimaryTypeCheck = propertySymOpnd->NeedsPrimaryTypeCheck();
  4763. bool emitLocalTypeCheck = propertySymOpnd->NeedsLocalTypeCheck();
  4764. bool emitLoadFromProtoTypeCheck = propertySymOpnd->NeedsLoadFromProtoTypeCheck();
  4765. if (emitPrimaryTypeCheck || emitLocalTypeCheck || emitLoadFromProtoTypeCheck)
  4766. {
  4767. if (emitLoadFromProtoTypeCheck)
  4768. {
  4769. propertySymOpnd->EnsureGuardedPropOps(this->m_func->m_alloc);
  4770. propertySymOpnd->SetGuardedPropOp(propertySymOpnd->GetObjTypeSpecFldId());
  4771. }
  4772. labelTypeCheckFailed = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  4773. labelObjCheckFailed = hasTypeCheckBailout ? labelTypeCheckFailed : IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  4774. *typeOpndOut = this->GenerateCachedTypeCheck(instrLdFld, propertySymOpnd, labelObjCheckFailed, labelTypeCheckFailed);
  4775. }
  4776. IR::Opnd *opndSlotArray;
  4777. if (propertySymOpnd->IsLoadedFromProto())
  4778. {
  4779. opndSlotArray = this->LoadSlotArrayWithCachedProtoType(instrLdFld, propertySymOpnd);
  4780. }
  4781. else
  4782. {
  4783. opndSlotArray = this->LoadSlotArrayWithCachedLocalType(instrLdFld, propertySymOpnd);
  4784. }
  4785. // Load the value from the slot, getting the slot ID from the cache.
  4786. uint16 index = propertySymOpnd->GetSlotIndex();
  4787. Assert(index != -1);
  4788. if (opndSlotArray->IsRegOpnd())
  4789. {
  4790. opnd = IR::IndirOpnd::New(opndSlotArray->AsRegOpnd(), index * sizeof(Js::Var), TyMachReg, this->m_func);
  4791. }
  4792. else
  4793. {
  4794. Assert(opndSlotArray->IsMemRefOpnd());
  4795. opnd = IR::MemRefOpnd::New((char*)opndSlotArray->AsMemRefOpnd()->GetMemLoc() + (index * sizeof(Js::Var)), TyMachReg, this->m_func, IR::AddrOpndKindDynamicPropertySlotRef);
  4796. }
  4797. Lowerer::InsertMove(instrLdFld->GetDst(), opnd, instrLdFld);
  4798. // We eliminate the helper, or the type check succeeds, or we bail out before the operation.
  4799. // Either delete the original instruction or replace it with a bailout.
  4800. if (!emitPrimaryTypeCheck && !emitLocalTypeCheck && !emitLoadFromProtoTypeCheck)
  4801. {
  4802. Assert(labelTypeCheckFailed == nullptr);
  4803. AssertMsg(!instrLdFld->HasBailOutInfo(), "Why does a direct field load have bailout?");
  4804. instrLdFld->Remove();
  4805. return true;
  4806. }
  4807. // Otherwise, branch around the bailout or helper.
  4808. labelDone = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  4809. instr = IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, labelDone, this->m_func);
  4810. instrLdFld->InsertBefore(instr);
  4811. // Insert the bailout or helper label here.
  4812. instrLdFld->InsertBefore(labelTypeCheckFailed);
  4813. instrLdFld->InsertAfter(labelDone);
  4814. if (hasTypeCheckBailout)
  4815. {
  4816. AssertMsg(PHASE_ON1(Js::ObjTypeSpecIsolatedFldOpsWithBailOutPhase) || !propertySymOpnd->IsTypeDead(),
  4817. "Why does a field load have a type check bailout, if its type is dead?");
  4818. // Convert the original instruction to a bailout.
  4819. if (instrLdFld->GetBailOutInfo()->bailOutInstr != instrLdFld)
  4820. {
  4821. // Set the cache index in the bailout info so that the bailout code will write it into the
  4822. // bailout record at runtime.
  4823. instrLdFld->GetBailOutInfo()->polymorphicCacheIndex = propertySymOpnd->m_inlineCacheIndex;
  4824. }
  4825. instrLdFld->FreeDst();
  4826. instrLdFld->FreeSrc1();
  4827. instrLdFld->m_opcode = Js::OpCode::BailOut;
  4828. this->GenerateBailOut(instrLdFld);
  4829. return true;
  4830. }
  4831. else
  4832. {
  4833. *continueAsHelperOut = true;
  4834. Assert(labelObjCheckFailed != nullptr && labelObjCheckFailed != labelTypeCheckFailed);
  4835. *labelHelperOut = labelObjCheckFailed;
  4836. return false;
  4837. }
  4838. }
  4839. template<bool isRoot>
  4840. IR::Instr* Lowerer::GenerateCompleteLdFld(IR::Instr* instr, bool emitFastPath, IR::JnHelperMethod monoHelperAfterFastPath, IR::JnHelperMethod polyHelperAfterFastPath,
  4841. IR::JnHelperMethod monoHelperWithoutFastPath, IR::JnHelperMethod polyHelperWithoutFastPath)
  4842. {
  4843. if(instr->CallsAccessor() && instr->HasBailOutInfo())
  4844. {
  4845. IR::BailOutKind kindMinusBits = instr->GetBailOutKind() & ~IR::BailOutKindBits;
  4846. Assert(kindMinusBits != IR::BailOutOnImplicitCalls && kindMinusBits != IR::BailOutOnImplicitCallsPreOp);
  4847. }
  4848. IR::Instr* prevInstr = instr->m_prev;
  4849. IR::LabelInstr* labelHelper = nullptr;
  4850. IR::LabelInstr* labelBailOut = nullptr;
  4851. bool isHelper = false;
  4852. IR::RegOpnd* typeOpnd = nullptr;
  4853. if (isRoot)
  4854. {
  4855. // Don't do the fast path here if emitFastPath is false, even if we can.
  4856. if (emitFastPath && (this->GenerateLdFldWithCachedType(instr, &isHelper, &labelHelper, &typeOpnd) || this->GenerateNonConfigurableLdRootFld(instr)))
  4857. {
  4858. Assert(labelHelper == nullptr);
  4859. return prevInstr;
  4860. }
  4861. }
  4862. else
  4863. {
  4864. if (this->GenerateLdFldWithCachedType(instr, &isHelper, &labelHelper, &typeOpnd))
  4865. {
  4866. Assert(labelHelper == nullptr);
  4867. return prevInstr;
  4868. }
  4869. }
  4870. if (emitFastPath)
  4871. {
  4872. if (!GenerateFastLdFld(instr, monoHelperWithoutFastPath, polyHelperWithoutFastPath, &labelBailOut, typeOpnd, &isHelper, &labelHelper))
  4873. {
  4874. if (labelHelper != nullptr)
  4875. {
  4876. labelHelper->isOpHelper = isHelper;
  4877. instr->InsertBefore(labelHelper);
  4878. }
  4879. prevInstr = LowerLdFld(instr, monoHelperAfterFastPath, polyHelperAfterFastPath, true, labelBailOut, isHelper);
  4880. }
  4881. }
  4882. else
  4883. {
  4884. if (labelHelper != nullptr)
  4885. {
  4886. labelHelper->isOpHelper = isHelper;
  4887. instr->InsertBefore(labelHelper);
  4888. }
  4889. prevInstr = LowerLdFld(instr, monoHelperWithoutFastPath, polyHelperWithoutFastPath, true, labelBailOut, isHelper);
  4890. }
  4891. return prevInstr;
  4892. }
  4893. bool
  4894. Lowerer::GenerateCheckFixedFld(IR::Instr * instrChkFld)
  4895. {
  4896. IR::Instr *instr;
  4897. IR::LabelInstr *labelBailOut = nullptr;
  4898. IR::LabelInstr *labelDone = nullptr;
  4899. AssertMsg(!PHASE_OFF(Js::FixedMethodsPhase, instrChkFld->m_func->GetJnFunction()) ||
  4900. !PHASE_OFF(Js::UseFixedDataPropsPhase, instrChkFld->m_func->GetJnFunction()), "Lowering a check fixed field with fixed data/method phase disabled?");
  4901. Assert(instrChkFld->GetSrc1()->IsSymOpnd() && instrChkFld->GetSrc1()->AsSymOpnd()->IsPropertySymOpnd());
  4902. IR::PropertySymOpnd *propertySymOpnd = instrChkFld->GetSrc1()->AsPropertySymOpnd();
  4903. AssertMsg(propertySymOpnd->TypeCheckSeqBitsSetOnlyIfCandidate(), "Property sym operand optimized despite not being a candidate?");
  4904. Assert(propertySymOpnd->MayNeedTypeCheckProtection());
  4905. // In the backwards pass we only add guarded property operations to instructions that are not already
  4906. // protected by an upstream type check.
  4907. Assert(!propertySymOpnd->IsTypeCheckProtected() || propertySymOpnd->GetGuardedPropOps() == nullptr);
  4908. // For the non-configurable properties on the global object we do not need a type check. Otherwise,
  4909. // we need a type check and bailout here unless this operation is part of the type check sequence and
  4910. // is protected by a type check upstream.
  4911. bool emitPrimaryTypeCheck = propertySymOpnd->NeedsPrimaryTypeCheck();
  4912. // In addition, we may also need a local type check in case the property comes from the prototype and
  4913. // it may have been overwritten on the instance after the primary type check upstream. If the property
  4914. // comes from the instance, we must still protect against its value changing after the type check, but
  4915. // for this a cheaper guard check is sufficient (see below).
  4916. bool emitFixedFieldTypeCheck = propertySymOpnd->NeedsCheckFixedFieldTypeCheck() &&
  4917. (!propertySymOpnd->IsTypeChecked() || propertySymOpnd->IsLoadedFromProto());
  4918. PropertySym * propertySym = propertySymOpnd->m_sym->AsPropertySym();
  4919. uint inlineCacheIndex = propertySymOpnd->m_inlineCacheIndex;
  4920. OUTPUT_TRACE_FUNC(
  4921. Js::ObjTypeSpecPhase,
  4922. this->m_func,
  4923. L"Fixed field check: %s, property: %s, cache ID: %u, cloned cache: true, layout: %s, redundant check: %s count of props: %u \n",
  4924. Js::OpCodeUtil::GetOpCodeName(instrChkFld->m_opcode),
  4925. this->m_func->GetScriptContext()->GetPropertyNameLocked(propertySym->m_propertyId)->GetBuffer(),
  4926. inlineCacheIndex, propertySymOpnd->GetCacheLayoutString(), propertySymOpnd->IsTypeChecked() ? L"true" : L"false",
  4927. propertySymOpnd->GetGuardedPropOps() ? propertySymOpnd->GetGuardedPropOps()->Count() : 0);
  4928. if (emitPrimaryTypeCheck || emitFixedFieldTypeCheck)
  4929. {
  4930. labelBailOut = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  4931. if(emitFixedFieldTypeCheck && propertySymOpnd->IsRootObjectNonConfigurableFieldLoad())
  4932. {
  4933. AssertMsg(!propertySymOpnd->GetGuardedPropOps() || propertySymOpnd->GetGuardedPropOps()->IsEmpty(), "This property Guard is used only for one property");
  4934. //We need only cheaper Guard check, if the property belongs to the GlobalObject.
  4935. GenerateFixedFieldGuardCheck(instrChkFld, propertySymOpnd, labelBailOut);
  4936. }
  4937. else
  4938. {
  4939. if (emitFixedFieldTypeCheck)
  4940. {
  4941. propertySymOpnd->EnsureGuardedPropOps(this->m_func->m_alloc);
  4942. propertySymOpnd->SetGuardedPropOp(propertySymOpnd->GetObjTypeSpecFldId());
  4943. }
  4944. this->GenerateCachedTypeCheck(instrChkFld, propertySymOpnd, labelBailOut, labelBailOut);
  4945. }
  4946. }
  4947. // We may still need this guard if we didn't emit the write protect type check above. This situation arises if we have
  4948. // a fixed field from the instance (not proto) and a property of the same name has been written somewhere between the
  4949. // primary type check and here. Note that we don't need a type check, because we know the fixed field exists on the
  4950. // object even if it has been written since primary type check, but we need to verify the fixed value didn't get overwritten.
  4951. if (!emitPrimaryTypeCheck && !emitFixedFieldTypeCheck && !propertySymOpnd->IsWriteGuardChecked())
  4952. {
  4953. if (!PHASE_OFF(Js::FixedFieldGuardCheckPhase, this->m_func))
  4954. {
  4955. Assert(labelBailOut == nullptr);
  4956. labelBailOut = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  4957. GenerateFixedFieldGuardCheck(instrChkFld, propertySymOpnd, labelBailOut);
  4958. }
  4959. }
  4960. // Note that a type handler holds only a weak reference to the singleton instance it represents, so
  4961. // it is possible that the instance gets collected before the type and handler do. Hence, the upstream
  4962. // type check may succeed, even as the original instance no longer exists. However, this would happen
  4963. // only if another instance reached the same type (otherwise we wouldn't ever pass the type check
  4964. // upstream). In that case we would have invalidated all fixed fields on that type, and so the type
  4965. // check (or property guard check, if necessary) above would fail. All in all, we would never attempt
  4966. // to access a fixed field from an instance that has been collected.
  4967. if (!emitPrimaryTypeCheck && !emitFixedFieldTypeCheck && propertySymOpnd->IsWriteGuardChecked())
  4968. {
  4969. Assert(labelBailOut == nullptr);
  4970. AssertMsg(!instrChkFld->HasBailOutInfo(), "Why does a direct fixed field check have bailout?");
  4971. instrChkFld->Remove();
  4972. return true;
  4973. }
  4974. labelDone = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  4975. instr = IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, labelDone, this->m_func);
  4976. instrChkFld->InsertBefore(instr);
  4977. // Insert the helper label here.
  4978. instrChkFld->InsertBefore(labelBailOut);
  4979. instrChkFld->InsertAfter(labelDone);
  4980. // Convert the original instruction to a bailout.
  4981. Assert(instrChkFld->HasBailOutInfo());
  4982. if (instrChkFld->GetBailOutInfo()->bailOutInstr != instrChkFld)
  4983. {
  4984. // Set the cache index in the bailout info so that the bailout code will write it into the
  4985. // bailout record at runtime.
  4986. instrChkFld->GetBailOutInfo()->polymorphicCacheIndex = inlineCacheIndex;
  4987. }
  4988. instrChkFld->FreeSrc1();
  4989. instrChkFld->m_opcode = Js::OpCode::BailOut;
  4990. this->GenerateBailOut(instrChkFld);
  4991. return true;
  4992. }
  4993. void
  4994. Lowerer::GenerateCheckObjType(IR::Instr * instrChkObjType)
  4995. {
  4996. Assert(instrChkObjType->GetSrc1()->IsSymOpnd() && instrChkObjType->GetSrc1()->AsSymOpnd()->IsPropertySymOpnd());
  4997. IR::PropertySymOpnd *propertySymOpnd = instrChkObjType->GetSrc1()->AsPropertySymOpnd();
  4998. // Why do we have an explicit type check if the cached type has been checked upstream? The dead store pass should have
  4999. // removed this instruction.
  5000. Assert(propertySymOpnd->IsTypeCheckSeqCandidate() && !propertySymOpnd->IsTypeChecked());
  5001. // Why do we have an explicit type check on a non-configurable root field load?
  5002. Assert(!propertySymOpnd->IsRootObjectNonConfigurableFieldLoad());
  5003. PropertySym * propertySym = propertySymOpnd->m_sym->AsPropertySym();
  5004. uint inlineCacheIndex = propertySymOpnd->m_inlineCacheIndex;
  5005. PHASE_PRINT_TESTTRACE(
  5006. Js::ObjTypeSpecPhase,
  5007. this->m_func,
  5008. L"Object type check: %s, property: %s, func: %s, cache ID: %d, cloned cache: true, layout: %s, redundant check: %s\n",
  5009. Js::OpCodeUtil::GetOpCodeName(instrChkObjType->m_opcode),
  5010. this->m_func->GetScriptContext()->GetPropertyNameLocked(propertySym->m_propertyId)->GetBuffer(),
  5011. this->m_func->GetJnFunction()->GetDisplayName(),
  5012. inlineCacheIndex, propertySymOpnd->GetCacheLayoutString(), L"false");
  5013. IR::LabelInstr* labelBailOut = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  5014. this->GenerateCachedTypeCheck(instrChkObjType, propertySymOpnd, labelBailOut, labelBailOut);
  5015. IR::LabelInstr* labelDone = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  5016. IR::Instr* instr = IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, labelDone, this->m_func);
  5017. instrChkObjType->InsertBefore(instr);
  5018. // Insert the bailout label here.
  5019. instrChkObjType->InsertBefore(labelBailOut);
  5020. instrChkObjType->InsertAfter(labelDone);
  5021. // Convert the original instruction to a bailout.
  5022. Assert(instrChkObjType->HasBailOutInfo());
  5023. if (instrChkObjType->GetBailOutInfo()->bailOutInstr != instrChkObjType)
  5024. {
  5025. // Set the cache index in the bailout info so that the bailout code will write it into the
  5026. // bailout record at runtime.
  5027. instrChkObjType->GetBailOutInfo()->polymorphicCacheIndex = inlineCacheIndex;
  5028. }
  5029. instrChkObjType->FreeSrc1();
  5030. instrChkObjType->m_opcode = Js::OpCode::BailOut;
  5031. this->GenerateBailOut(instrChkObjType);
  5032. }
  5033. void
  5034. Lowerer::LowerAdjustObjType(IR::Instr * instrAdjustObjType)
  5035. {
  5036. IR::AddrOpnd *finalTypeOpnd = instrAdjustObjType->UnlinkDst()->AsAddrOpnd();
  5037. IR::AddrOpnd *initialTypeOpnd = instrAdjustObjType->UnlinkSrc2()->AsAddrOpnd();
  5038. IR::RegOpnd *baseOpnd = instrAdjustObjType->UnlinkSrc1()->AsRegOpnd();
  5039. this->GenerateAdjustBaseSlots(
  5040. instrAdjustObjType, baseOpnd, (Js::Type*)initialTypeOpnd->m_address, (Js::Type*)finalTypeOpnd->m_address);
  5041. this->m_func->PinTypeRef(finalTypeOpnd->m_address);
  5042. IR::Opnd *opnd = IR::IndirOpnd::New(baseOpnd, Js::RecyclableObject::GetOffsetOfType(), TyMachReg, instrAdjustObjType->m_func);
  5043. this->m_lowererMD.CreateAssign(opnd, finalTypeOpnd, instrAdjustObjType);
  5044. initialTypeOpnd->Free(instrAdjustObjType->m_func);
  5045. instrAdjustObjType->Remove();
  5046. }
  5047. bool
  5048. Lowerer::GenerateNonConfigurableLdRootFld(IR::Instr * instrLdFld)
  5049. {
  5050. if (!instrLdFld->GetSrc1()->AsSymOpnd()->IsPropertySymOpnd())
  5051. {
  5052. return false;
  5053. }
  5054. IR::PropertySymOpnd *propertySymOpnd = instrLdFld->GetSrc1()->AsPropertySymOpnd();
  5055. if (!propertySymOpnd->IsRootObjectNonConfigurableFieldLoad())
  5056. {
  5057. return false;
  5058. }
  5059. Assert(!PHASE_OFF(Js::RootObjectFldFastPathPhase, this->m_func->GetJnFunction()));
  5060. Assert(!instrLdFld->HasBailOutInfo());
  5061. IR::Opnd * srcOpnd;
  5062. Js::RootObjectBase * rootObject = this->m_func->GetJnFunction()->GetRootObject();
  5063. if (propertySymOpnd->UsesAuxSlot())
  5064. {
  5065. IR::RegOpnd * auxSlotOpnd = IR::RegOpnd::New(TyMachPtr, this->m_func);
  5066. this->InsertMove(auxSlotOpnd, IR::MemRefOpnd::New((byte *)rootObject + Js::DynamicObject::GetOffsetOfAuxSlots(),
  5067. TyMachPtr, this->m_func), instrLdFld);
  5068. srcOpnd = IR::IndirOpnd::New(auxSlotOpnd, propertySymOpnd->GetSlotIndex() * sizeof(Js::Var *),
  5069. TyVar, this->m_func);
  5070. }
  5071. else
  5072. {
  5073. srcOpnd = IR::MemRefOpnd::New((Js::Var *)rootObject + propertySymOpnd->GetSlotIndex(),
  5074. TyVar, this->m_func);
  5075. }
  5076. instrLdFld->ReplaceSrc1(srcOpnd);
  5077. instrLdFld->m_opcode = Js::OpCode::Ld_A;
  5078. LowererMD::ChangeToAssign(instrLdFld);
  5079. return true;
  5080. }
  5081. IR::Instr *
  5082. Lowerer::LowerDelFld(IR::Instr *delFldInstr, IR::JnHelperMethod helperMethod, bool useInlineCache, bool strictMode)
  5083. {
  5084. IR::Instr *instrPrev;
  5085. Js::PropertyOperationFlags propertyOperationFlag = Js::PropertyOperation_None;
  5086. if (strictMode)
  5087. {
  5088. propertyOperationFlag = Js::PropertyOperation_StrictMode;
  5089. }
  5090. instrPrev = m_lowererMD.LoadHelperArgument(delFldInstr, IR::IntConstOpnd::New((IntConstType)propertyOperationFlag, TyInt32, m_func, true));
  5091. LowerLdFld(delFldInstr, helperMethod, helperMethod, useInlineCache);
  5092. return instrPrev;
  5093. }
  5094. IR::Instr *
  5095. Lowerer::LowerIsInst(IR::Instr * isInstInstr, IR::JnHelperMethod helperMethod)
  5096. {
  5097. IR::Instr * instrPrev;
  5098. IR::Instr * instrArg;
  5099. IR::RegOpnd * argOpnd;
  5100. // inlineCache
  5101. instrPrev = m_lowererMD.LoadHelperArgument(isInstInstr, LoadIsInstInlineCacheOpnd(isInstInstr, isInstInstr->GetSrc1()->AsIntConstOpnd()->AsUint32()));
  5102. isInstInstr->FreeSrc1();
  5103. argOpnd = isInstInstr->UnlinkSrc2()->AsRegOpnd();
  5104. Assert(argOpnd->m_sym->m_isSingleDef);
  5105. instrArg = argOpnd->m_sym->m_instrDef;
  5106. argOpnd->Free(m_func);
  5107. // scriptContext
  5108. LoadScriptContext(isInstInstr);
  5109. // instance goes last, so remember it now
  5110. IR::Opnd * instanceOpnd = instrArg->UnlinkSrc1();
  5111. argOpnd = instrArg->UnlinkSrc2()->AsRegOpnd();
  5112. Assert(argOpnd->m_sym->m_isSingleDef);
  5113. instrArg->Remove();
  5114. instrArg = argOpnd->m_sym->m_instrDef;
  5115. argOpnd->Free(m_func);
  5116. // function
  5117. IR::Opnd *opnd = instrArg->UnlinkSrc1();
  5118. m_lowererMD.LoadHelperArgument(isInstInstr, opnd);
  5119. Assert(instrArg->GetSrc2() == NULL);
  5120. instrArg->Remove();
  5121. // instance
  5122. m_lowererMD.LoadHelperArgument(isInstInstr, instanceOpnd);
  5123. m_lowererMD.ChangeToHelperCall(isInstInstr, helperMethod);
  5124. return instrPrev;
  5125. }
  5126. void
  5127. Lowerer::GenerateStackScriptFunctionInit(StackSym * stackSym, Js::FunctionProxyPtrPtr nestedProxy)
  5128. {
  5129. Func * func = this->m_func;
  5130. Assert(func->HasAnyStackNestedFunc());
  5131. Assert(nextStackFunctionOpnd);
  5132. IR::Instr * insertBeforeInstr = func->GetFunctionEntryInsertionPoint();
  5133. IR::RegOpnd * addressOpnd = IR::RegOpnd::New(TyMachPtr, func);
  5134. const IR::AutoReuseOpnd autoReuseAddressOpnd(addressOpnd, func);
  5135. InsertLea(addressOpnd, IR::SymOpnd::New(stackSym, TyMachPtr, func), insertBeforeInstr);
  5136. // Currently we don't initialize the environment until we actually allocate the function, we also
  5137. // walk the list of stack function when we need to box them. so we should use initialize it to NullFrameDisplay
  5138. GenerateStackScriptFunctionInit(addressOpnd, nestedProxy,
  5139. IR::AddrOpnd::New((Js::Var)&Js::NullFrameDisplay, IR::AddrOpndKindDynamicMisc, func), insertBeforeInstr);
  5140. // Establish the next link
  5141. InsertMove(nextStackFunctionOpnd, addressOpnd, insertBeforeInstr);
  5142. this->nextStackFunctionOpnd = IR::SymOpnd::New(stackSym, sizeof(Js::StackScriptFunction), TyMachPtr, func);
  5143. }
  5144. void
  5145. Lowerer::GenerateScriptFunctionInit(IR::RegOpnd * regOpnd, IR::Opnd * vtableAddressOpnd,
  5146. Js::FunctionProxyPtrPtr nestedProxy, IR::Opnd * envOpnd, IR::Instr * insertBeforeInstr, bool isZeroed)
  5147. {
  5148. Func * func = this->m_func;
  5149. IR::Opnd * functionProxyOpnd;
  5150. Js::FunctionProxy * functionProxy = *nestedProxy;
  5151. IR::Opnd * typeOpnd = nullptr;
  5152. bool doCheckTypeOpnd = true;
  5153. if (functionProxy->IsDeferred())
  5154. {
  5155. functionProxyOpnd = IR::RegOpnd::New(TyMachPtr, func);
  5156. InsertMove(functionProxyOpnd, IR::MemRefOpnd::New((Js::FunctionProxy**) nestedProxy, TyMachPtr, func), insertBeforeInstr);
  5157. typeOpnd = IR::RegOpnd::New(TyMachPtr, func);
  5158. InsertMove(typeOpnd, IR::IndirOpnd::New(functionProxyOpnd->AsRegOpnd(), Js::FunctionProxy::GetOffsetOfDeferredPrototypeType(),
  5159. TyMachPtr, func), insertBeforeInstr);
  5160. }
  5161. else
  5162. {
  5163. Js::FunctionBody * functionBody = functionProxy->GetFunctionBody();
  5164. functionProxyOpnd = CreateFunctionBodyOpnd(functionBody);
  5165. Js::ScriptFunctionType * type = functionProxy->GetDeferredPrototypeType();
  5166. if (type != nullptr)
  5167. {
  5168. typeOpnd = IR::AddrOpnd::New(type, IR::AddrOpndKindDynamicType, func);
  5169. doCheckTypeOpnd = false;
  5170. }
  5171. else
  5172. {
  5173. typeOpnd = IR::RegOpnd::New(TyMachPtr, func);
  5174. InsertMove(typeOpnd,
  5175. IR::MemRefOpnd::New(((byte *)functionBody) + Js::FunctionProxy::GetOffsetOfDeferredPrototypeType(), TyMachPtr, func),
  5176. insertBeforeInstr);
  5177. }
  5178. }
  5179. if (doCheckTypeOpnd)
  5180. {
  5181. IR::LabelInstr * labelHelper = IR::LabelInstr::New(Js::OpCode::Label, func, true);
  5182. InsertTestBranch(typeOpnd, typeOpnd, Js::OpCode::BrEq_A, labelHelper, insertBeforeInstr);
  5183. IR::LabelInstr * labelDone = IR::LabelInstr::New(Js::OpCode::Label, func, false);
  5184. InsertBranch(Js::OpCode::Br, labelDone, insertBeforeInstr);
  5185. insertBeforeInstr->InsertBefore(labelHelper);
  5186. m_lowererMD.LoadHelperArgument(insertBeforeInstr, functionProxyOpnd);
  5187. IR::Instr * callHelperInstr = IR::Instr::New(Js::OpCode::Call, typeOpnd,
  5188. IR::HelperCallOpnd::New(IR::JnHelperMethod::HelperEnsureFunctionProxyDeferredPrototypeType, func), func);
  5189. insertBeforeInstr->InsertBefore(callHelperInstr);
  5190. m_lowererMD.LowerCall(callHelperInstr, 0);
  5191. insertBeforeInstr->InsertBefore(labelDone);
  5192. }
  5193. GenerateMemInit(regOpnd, 0, vtableAddressOpnd, insertBeforeInstr, isZeroed);
  5194. GenerateMemInit(regOpnd, Js::ScriptFunction::GetOffsetOfType(), typeOpnd, insertBeforeInstr, isZeroed);
  5195. GenerateMemInitNull(regOpnd, Js::ScriptFunction::GetOffsetOfAuxSlots(), insertBeforeInstr, isZeroed);
  5196. GenerateMemInitNull(regOpnd, Js::ScriptFunction::GetOffsetOfObjectArray(), insertBeforeInstr, isZeroed);
  5197. GenerateMemInit(regOpnd, Js::ScriptFunction::GetOffsetOfConstructorCache(),
  5198. LoadLibraryValueOpnd(insertBeforeInstr, LibraryValue::ValueConstructorCacheDefaultInstance),
  5199. insertBeforeInstr, isZeroed);
  5200. GenerateMemInit(regOpnd, Js::ScriptFunction::GetOffsetOfFunctionInfo(), functionProxyOpnd, insertBeforeInstr, isZeroed);
  5201. GenerateMemInit(regOpnd, Js::ScriptFunction::GetOffsetOfEnvironment(), envOpnd, insertBeforeInstr, isZeroed);
  5202. GenerateMemInitNull(regOpnd, Js::ScriptFunction::GetOffsetOfCachedScopeObj(), insertBeforeInstr, isZeroed);
  5203. GenerateMemInitNull(regOpnd, Js::ScriptFunction::GetOffsetOfHasInlineCaches(), insertBeforeInstr, isZeroed);
  5204. }
  5205. void
  5206. Lowerer::GenerateStackScriptFunctionInit(IR::RegOpnd * regOpnd, Js::FunctionProxyPtrPtr nestedProxy, IR::Opnd * envOpnd, IR::Instr * insertBeforeInstr)
  5207. {
  5208. Func * func = this->m_func;
  5209. GenerateScriptFunctionInit(regOpnd,
  5210. LoadVTableValueOpnd(insertBeforeInstr, VTableValue::VtableStackScriptFunction),
  5211. nestedProxy, envOpnd, insertBeforeInstr);
  5212. InsertMove(IR::IndirOpnd::New(regOpnd, Js::StackScriptFunction::GetOffsetOfBoxedScriptFunction(), TyMachPtr, func),
  5213. IR::AddrOpnd::NewNull(func), insertBeforeInstr);
  5214. }
  5215. void
  5216. Lowerer::EnsureStackFunctionListStackSym()
  5217. {
  5218. Func * func = this->m_func;
  5219. Assert(func->HasAnyStackNestedFunc());
  5220. #if defined(_M_IX86) || defined(_M_X64)
  5221. Assert(func->m_localStackHeight == (func->HasArgumentSlot()? MachArgsSlotOffset : 0));
  5222. StackSym * stackFunctionListStackSym = StackSym::New(TyMachPtr, func);
  5223. func->StackAllocate(stackFunctionListStackSym, sizeof(Js::ScriptFunction *));
  5224. nextStackFunctionOpnd = IR::SymOpnd::New(stackFunctionListStackSym, TyMachPtr, func);
  5225. #else
  5226. Assert(func->m_localStackHeight == 0);
  5227. nextStackFunctionOpnd = IR::IndirOpnd::New(IR::RegOpnd::New(NULL, FRAME_REG, TyMachReg, func),
  5228. -(int32)(Js::Constants::StackNestedFuncList * sizeof(Js::Var)), TyMachPtr, func);
  5229. #endif
  5230. }
  5231. void
  5232. Lowerer::AllocStackClosure()
  5233. {
  5234. m_func->StackAllocate(m_func->GetLocalFrameDisplaySym(), sizeof(Js::Var));
  5235. m_func->StackAllocate(m_func->GetLocalClosureSym(), sizeof(Js::Var));
  5236. }
  5237. void
  5238. Lowerer::EnsureZeroLastStackFunctionNext()
  5239. {
  5240. Assert(nextStackFunctionOpnd != nullptr);
  5241. Func * func = this->m_func;
  5242. IR::Instr * insertBeforeInstr = func->GetFunctionEntryInsertionPoint();
  5243. InsertMove(nextStackFunctionOpnd, IR::AddrOpnd::NewNull(func), insertBeforeInstr);
  5244. }
  5245. IR::Instr *
  5246. Lowerer::GenerateNewStackScFunc(IR::Instr * newScFuncInstr)
  5247. {
  5248. Assert(newScFuncInstr->m_func->DoStackNestedFunc());
  5249. Func * func = newScFuncInstr->m_func;
  5250. uint index = newScFuncInstr->GetSrc1()->AsIntConstOpnd()->AsUint32();
  5251. Assert(index < func->GetJnFunction()->GetNestedCount());
  5252. Js::FunctionProxyPtrPtr nestedProxy = func->GetJnFunction()->GetNestedFuncReference(index);
  5253. // the stackAllocate Call below for this sym is passing a size that is not represented by any IRType and hence passing TyMisc for the constructor
  5254. StackSym * stackSym = StackSym::New(TyMisc, func);
  5255. // ScriptFunction and it's next pointer
  5256. this->m_func->StackAllocate(stackSym, sizeof(Js::StackScriptFunction) + sizeof(Js::StackScriptFunction *));
  5257. IR::Opnd * envOpnd = newScFuncInstr->GetSrc2();
  5258. GenerateStackScriptFunctionInit(stackSym, nestedProxy);
  5259. IR::LabelInstr * labelNoStackFunc = IR::LabelInstr::New(Js::OpCode::Label, func, true);
  5260. IR::LabelInstr * labelDone = IR::LabelInstr::New(Js::OpCode::Label, func);
  5261. InsertTestBranch(IR::MemRefOpnd::New(func->GetJnFunction()->GetAddressOfFlags(), TyInt8, func),
  5262. IR::IntConstOpnd::New(Js::FunctionBody::Flags_StackNestedFunc, TyInt8, func, true),
  5263. Js::OpCode::BrEq_A, labelNoStackFunc, newScFuncInstr);
  5264. InsertMove(IR::SymOpnd::New(stackSym, Js::ScriptFunction::GetOffsetOfEnvironment(), TyMachPtr, func),
  5265. envOpnd,
  5266. newScFuncInstr);
  5267. IR::Instr * lea =
  5268. InsertLea(newScFuncInstr->GetDst()->AsRegOpnd(), IR::SymOpnd::New(stackSym, TyMachPtr, func), newScFuncInstr);
  5269. InsertBranch(Js::OpCode::Br, labelDone, newScFuncInstr);
  5270. newScFuncInstr->InsertBefore(labelNoStackFunc);
  5271. newScFuncInstr->InsertAfter(labelDone);
  5272. return lea;
  5273. }
  5274. IR::Instr *
  5275. Lowerer::LowerNewScFunc(IR::Instr * newScFuncInstr)
  5276. {
  5277. IR::Instr *stackNewScFuncInstr = nullptr;
  5278. if (newScFuncInstr->m_func->DoStackNestedFunc())
  5279. {
  5280. stackNewScFuncInstr = GenerateNewStackScFunc(newScFuncInstr);
  5281. }
  5282. IR::IntConstOpnd * functionBodySlotOpnd = newScFuncInstr->UnlinkSrc1()->AsIntConstOpnd();
  5283. IR::RegOpnd * envOpnd = newScFuncInstr->UnlinkSrc2()->AsRegOpnd();
  5284. IR::Instr * instrPrev = this->LoadFunctionBodyAsArgument(newScFuncInstr, functionBodySlotOpnd, envOpnd);
  5285. m_lowererMD.ChangeToHelperCall(newScFuncInstr, IR::HelperScrFunc_OP_NewScFunc );
  5286. return stackNewScFuncInstr == nullptr? instrPrev : stackNewScFuncInstr;
  5287. }
  5288. IR::Instr *
  5289. Lowerer::LowerNewScGenFunc(IR::Instr * newScFuncInstr)
  5290. {
  5291. IR::IntConstOpnd * functionBodySlotOpnd = newScFuncInstr->UnlinkSrc1()->AsIntConstOpnd();
  5292. IR::RegOpnd * envOpnd = newScFuncInstr->UnlinkSrc2()->AsRegOpnd();
  5293. IR::Instr * instrPrev = this->LoadFunctionBodyAsArgument(newScFuncInstr, functionBodySlotOpnd, envOpnd);
  5294. m_lowererMD.ChangeToHelperCall(newScFuncInstr, IR::HelperScrFunc_OP_NewScGenFunc );
  5295. return instrPrev;
  5296. }
  5297. ///----------------------------------------------------------------------------
  5298. ///
  5299. /// Lowerer::LowerScopedLdFld
  5300. ///
  5301. /// Lower a load instruction that takes an additional instance to use as a
  5302. /// a default if the scope chain provided doesn't contain the property.
  5303. ///
  5304. ///----------------------------------------------------------------------------
  5305. IR::Instr *
  5306. Lowerer::LowerScopedLdFld(IR::Instr * ldFldInstr, IR::JnHelperMethod helperMethod, bool withInlineCache)
  5307. {
  5308. IR::Opnd *src;
  5309. IR::Instr *instrPrev = ldFldInstr->m_prev;
  5310. if(!withInlineCache)
  5311. {
  5312. LoadScriptContext(ldFldInstr);
  5313. }
  5314. src = ldFldInstr->UnlinkSrc2();
  5315. AssertMsg(src->IsRegOpnd(), "Expected reg opnd as src2");
  5316. instrPrev = m_lowererMD.LoadHelperArgument(ldFldInstr, src);
  5317. src = ldFldInstr->UnlinkSrc1();
  5318. AssertMsg(src->IsSymOpnd() && src->AsSymOpnd()->m_sym->IsPropertySym(), "Expected property sym as src");
  5319. this->LoadPropertySymAsArgument(ldFldInstr, src);
  5320. if (withInlineCache)
  5321. {
  5322. AssertMsg(src->AsSymOpnd()->IsPropertySymOpnd(), "Need property sym operand to find the inline cache");
  5323. m_lowererMD.LoadHelperArgument(
  5324. ldFldInstr,
  5325. IR::Opnd::CreateInlineCacheIndexOpnd(src->AsPropertySymOpnd()->m_inlineCacheIndex, m_func));
  5326. // Not using the polymorphic inline cache because the fast path only uses the monomorphic inline cache
  5327. this->m_lowererMD.LoadHelperArgument(ldFldInstr, this->LoadRuntimeInlineCacheOpnd(ldFldInstr, src->AsPropertySymOpnd()));
  5328. m_lowererMD.LoadHelperArgument(ldFldInstr, LoadFunctionBodyOpnd(ldFldInstr));
  5329. }
  5330. m_lowererMD.ChangeToHelperCall(ldFldInstr, helperMethod);
  5331. return instrPrev;
  5332. }
  5333. ///----------------------------------------------------------------------------
  5334. ///
  5335. /// Lowerer::LowerScopedLdInst
  5336. ///
  5337. /// Lower a load instruction that takes an additional instance to use as a
  5338. /// a default if the scope chain provided doesn't contain the property.
  5339. ///
  5340. ///----------------------------------------------------------------------------
  5341. IR::Instr *
  5342. Lowerer::LowerScopedLdInst(IR::Instr *instr, IR::JnHelperMethod helperMethod)
  5343. {
  5344. IR::Opnd *src;
  5345. IR::Instr *instrPrev;
  5346. // last argument is the scriptContext
  5347. instrPrev = LoadScriptContext(instr);
  5348. src = instr->UnlinkSrc2();
  5349. AssertMsg(src->IsRegOpnd(), "Expected Reg opnd as src2");
  5350. // __out Var*. The StackSym is allocated in irbuilder, and here we need to insert a lea
  5351. StackSym* dstSym = src->GetStackSym();
  5352. IR::Instr *load = this->m_lowererMD.LoadStackAddress(dstSym);
  5353. instr->InsertBefore(load);
  5354. IR::Opnd* tempOpnd = load->GetDst();
  5355. m_lowererMD.LoadHelperArgument(instr, tempOpnd);
  5356. // now 3rd last argument is the rootObject of the function. Need to add addrOpnd to
  5357. // pass in the address of the roobObject.
  5358. IR::Opnd * srcOpnd;
  5359. Js::RootObjectBase * rootObject = this->m_func->GetJnFunction()->GetRootObject();
  5360. srcOpnd = IR::AddrOpnd::New(rootObject, IR::AddrOpndKindDynamicVar, instr->m_func, true);
  5361. instrPrev = m_lowererMD.LoadHelperArgument(instr, srcOpnd);
  5362. // no change, the property field built from irbuilder.
  5363. src = instr->UnlinkSrc1();
  5364. AssertMsg(src->IsSymOpnd() && src->AsSymOpnd()->m_sym->IsPropertySym(), "Expected property sym as src");
  5365. this->LoadPropertySymAsArgument(instr, src);
  5366. instrPrev = m_lowererMD.ChangeToHelperCall(instr, helperMethod);
  5367. IR::RegOpnd* regOpnd = IR::RegOpnd::New(dstSym, TyVar, this->m_func);
  5368. IR::SymOpnd*symOpnd = IR::SymOpnd::New(dstSym, TyVar, this->m_func);
  5369. this->m_lowererMD.CreateAssign(regOpnd, symOpnd, instrPrev);
  5370. return instrPrev;
  5371. }
  5372. IR::Instr *
  5373. Lowerer::LowerScopedDelFld(IR::Instr * delFldInstr, IR::JnHelperMethod helperMethod, bool withInlineCache, bool strictMode)
  5374. {
  5375. IR::Instr *instrPrev;
  5376. Js::PropertyOperationFlags propertyOperationFlag = Js::PropertyOperation_None;
  5377. if (strictMode)
  5378. {
  5379. propertyOperationFlag = Js::PropertyOperation_StrictMode;
  5380. }
  5381. instrPrev = m_lowererMD.LoadHelperArgument(delFldInstr, IR::IntConstOpnd::New((IntConstType)propertyOperationFlag, TyInt32, m_func, true));
  5382. LowerScopedLdFld(delFldInstr, helperMethod, withInlineCache);
  5383. return instrPrev;
  5384. }
  5385. IR::Instr *
  5386. Lowerer::LowerProfiledStFld(IR::JitProfilingInstr *stFldInstr, Js::PropertyOperationFlags flags)
  5387. {
  5388. Assert(stFldInstr->profileId == Js::Constants::NoProfileId);
  5389. IR::Instr *const instrPrev = stFldInstr->m_prev;
  5390. /*
  5391. void ProfilingHelpers::ProfiledInitFld_Jit(
  5392. const Var instance,
  5393. const PropertyId propertyId,
  5394. const InlineCacheIndex inlineCacheIndex,
  5395. const Var value,
  5396. void *const framePointer)
  5397. void ProfilingHelpers::ProfiledStFld_Jit(
  5398. const Var instance,
  5399. const PropertyId propertyId,
  5400. const InlineCacheIndex inlineCacheIndex,
  5401. const Var value,
  5402. void *const framePointer)
  5403. void ProfilingHelpers::ProfiledStSuperFld_Jit(
  5404. const Var instance,
  5405. const PropertyId propertyId,
  5406. const InlineCacheIndex inlineCacheIndex,
  5407. const Var value,
  5408. void *const framePointer,
  5409. const Var thisInstance)
  5410. {
  5411. */
  5412. m_lowererMD.LoadHelperArgument(stFldInstr, IR::Opnd::CreateFramePointerOpnd(m_func));
  5413. if (stFldInstr->m_opcode == Js::OpCode::StSuperFld)
  5414. {
  5415. m_lowererMD.LoadHelperArgument(stFldInstr, stFldInstr->UnlinkSrc2());
  5416. }
  5417. m_lowererMD.LoadHelperArgument(stFldInstr, stFldInstr->UnlinkSrc1());
  5418. IR::Opnd *dst = stFldInstr->UnlinkDst();
  5419. AssertMsg(dst->IsSymOpnd() && dst->AsSymOpnd()->m_sym->IsPropertySym(), "Expected property sym as dst of field store");
  5420. m_lowererMD.LoadHelperArgument(
  5421. stFldInstr,
  5422. IR::Opnd::CreateInlineCacheIndexOpnd(dst->AsPropertySymOpnd()->m_inlineCacheIndex, m_func));
  5423. LoadPropertySymAsArgument(stFldInstr, dst);
  5424. IR::JnHelperMethod helper;
  5425. switch (stFldInstr->m_opcode)
  5426. {
  5427. case Js::OpCode::InitFld:
  5428. case Js::OpCode::InitRootFld:
  5429. helper = IR::HelperProfiledInitFld;
  5430. break;
  5431. case Js::OpCode::StSuperFld:
  5432. helper = IR::HelperProfiledStSuperFld;
  5433. break;
  5434. default:
  5435. helper =
  5436. flags & Js::PropertyOperation_Root
  5437. ? flags & Js::PropertyOperation_StrictMode ? IR::HelperProfiledStRootFld_Strict : IR::HelperProfiledStRootFld
  5438. : flags & Js::PropertyOperation_StrictMode ? IR::HelperProfiledStFld_Strict : IR::HelperProfiledStFld;
  5439. break;
  5440. }
  5441. stFldInstr->SetSrc1(IR::HelperCallOpnd::New(helper, m_func));
  5442. m_lowererMD.LowerCall(stFldInstr, 0);
  5443. return instrPrev;
  5444. }
  5445. ///----------------------------------------------------------------------------
  5446. ///
  5447. /// Lowerer::LowerStFld
  5448. ///
  5449. ///----------------------------------------------------------------------------
  5450. IR::Instr *
  5451. Lowerer::LowerStFld(
  5452. IR::Instr * stFldInstr,
  5453. IR::JnHelperMethod helperMethod,
  5454. IR::JnHelperMethod polymorphicHelperMethod,
  5455. bool withInlineCache,
  5456. IR::LabelInstr *labelBailOut,
  5457. bool isHelper,
  5458. bool withPutFlags,
  5459. Js::PropertyOperationFlags flags)
  5460. {
  5461. if (stFldInstr->IsJitProfilingInstr())
  5462. {
  5463. // If we want to profile then do something completely different
  5464. return this->LowerProfiledStFld(stFldInstr->AsJitProfilingInstr(), flags);
  5465. }
  5466. IR::Instr *instrPrev = stFldInstr->m_prev;
  5467. IR::Opnd *dst = stFldInstr->UnlinkDst();
  5468. AssertMsg(dst->IsSymOpnd() && dst->AsSymOpnd()->m_sym->IsPropertySym(), "Expected property sym as dst of field store");
  5469. IR::Opnd * inlineCacheOpnd = nullptr;
  5470. if (withInlineCache)
  5471. {
  5472. AssertMsg(dst->AsSymOpnd()->IsPropertySymOpnd(), "Need property sym operand to find the inline cache");
  5473. if (dst->AsPropertySymOpnd()->m_runtimePolymorphicInlineCache && polymorphicHelperMethod != helperMethod)
  5474. {
  5475. Js::PolymorphicInlineCache * polymorphicInlineCache = dst->AsPropertySymOpnd()->m_runtimePolymorphicInlineCache;
  5476. helperMethod = polymorphicHelperMethod;
  5477. inlineCacheOpnd = IR::AddrOpnd::New(polymorphicInlineCache, IR::AddrOpndKindDynamicInlineCache, this->m_func);
  5478. }
  5479. else
  5480. {
  5481. // Need to load runtime inline cache opnd first before loading any helper argument
  5482. // because LoadRuntimeInlineCacheOpnd may create labels marked as helper
  5483. // and cause op helper register push/pop save in x86, messing up with any helper arguments that is already pushed
  5484. inlineCacheOpnd = this->LoadRuntimeInlineCacheOpnd(stFldInstr, dst->AsPropertySymOpnd(), isHelper);
  5485. }
  5486. }
  5487. if (withPutFlags)
  5488. {
  5489. m_lowererMD.LoadHelperArgument(stFldInstr,
  5490. IR::IntConstOpnd::New(static_cast<IntConstType>(flags), IRType::TyInt32, m_func, true));
  5491. }
  5492. IR::Opnd *src = stFldInstr->UnlinkSrc1();
  5493. if (stFldInstr->m_opcode == Js::OpCode::StSuperFld)
  5494. {
  5495. m_lowererMD.LoadHelperArgument(stFldInstr, stFldInstr->UnlinkSrc2());
  5496. }
  5497. m_lowererMD.LoadHelperArgument(stFldInstr, src);
  5498. this->LoadPropertySymAsArgument(stFldInstr, dst);
  5499. if (withInlineCache)
  5500. {
  5501. Assert(inlineCacheOpnd != nullptr);
  5502. this->m_lowererMD.LoadHelperArgument(
  5503. stFldInstr,
  5504. IR::Opnd::CreateInlineCacheIndexOpnd(dst->AsPropertySymOpnd()->m_inlineCacheIndex, m_func));
  5505. this->m_lowererMD.LoadHelperArgument(stFldInstr, inlineCacheOpnd);
  5506. this->m_lowererMD.LoadHelperArgument(stFldInstr, LoadFunctionBodyOpnd(stFldInstr));
  5507. }
  5508. IR::RegOpnd *opndBase = dst->AsSymOpnd()->CreatePropertyOwnerOpnd(m_func);
  5509. m_lowererMD.ChangeToHelperCall(stFldInstr, helperMethod, labelBailOut, opndBase, dst->AsSymOpnd()->IsPropertySymOpnd() ? dst->AsSymOpnd()->AsPropertySymOpnd() : nullptr, isHelper);
  5510. return instrPrev;
  5511. }
  5512. IR::Instr* Lowerer::GenerateCompleteStFld(IR::Instr* instr, bool emitFastPath, IR::JnHelperMethod monoHelperAfterFastPath, IR::JnHelperMethod polyHelperAfterFastPath,
  5513. IR::JnHelperMethod monoHelperWithoutFastPath, IR::JnHelperMethod polyHelperWithoutFastPath, bool withPutFlags, Js::PropertyOperationFlags flags)
  5514. {
  5515. if(instr->CallsAccessor() && instr->HasBailOutInfo())
  5516. {
  5517. IR::BailOutKind kindMinusBits = instr->GetBailOutKind() & ~IR::BailOutKindBits;
  5518. Assert(kindMinusBits != IR::BailOutOnImplicitCalls && kindMinusBits != IR::BailOutOnImplicitCallsPreOp);
  5519. }
  5520. IR::Instr* prevInstr = instr->m_prev;
  5521. IR::LabelInstr* labelBailOut = nullptr;
  5522. IR::LabelInstr* labelHelper = nullptr;
  5523. bool isHelper = false;
  5524. IR::RegOpnd* typeOpnd = nullptr;
  5525. if(emitFastPath && GenerateFastStFldForCustomProperty(instr, &labelHelper))
  5526. {
  5527. if(labelHelper)
  5528. {
  5529. Assert(labelHelper->isOpHelper);
  5530. instr->InsertBefore(labelHelper);
  5531. prevInstr = this->LowerStFld(instr, monoHelperWithoutFastPath, polyHelperWithoutFastPath, true, labelBailOut, isHelper, withPutFlags, flags);
  5532. }
  5533. else
  5534. {
  5535. instr->Remove();
  5536. return prevInstr;
  5537. }
  5538. }
  5539. else if (this->GenerateStFldWithCachedType(instr, &isHelper, &labelHelper, &typeOpnd))
  5540. {
  5541. Assert(labelHelper == nullptr);
  5542. return prevInstr;
  5543. }
  5544. else if (emitFastPath)
  5545. {
  5546. if (!GenerateFastStFld(instr, monoHelperWithoutFastPath, polyHelperWithoutFastPath, &labelBailOut, typeOpnd, &isHelper, &labelHelper, withPutFlags, flags))
  5547. {
  5548. if (labelHelper != nullptr)
  5549. {
  5550. labelHelper->isOpHelper = isHelper;
  5551. instr->InsertBefore(labelHelper);
  5552. }
  5553. prevInstr = this->LowerStFld(instr, monoHelperAfterFastPath, polyHelperAfterFastPath, true, labelBailOut, isHelper, withPutFlags, flags);
  5554. }
  5555. }
  5556. else
  5557. {
  5558. if (labelHelper != nullptr)
  5559. {
  5560. labelHelper->isOpHelper = isHelper;
  5561. instr->InsertBefore(labelHelper);
  5562. }
  5563. prevInstr = this->LowerStFld(instr, monoHelperWithoutFastPath, monoHelperWithoutFastPath, true, labelBailOut, isHelper, withPutFlags, flags);
  5564. }
  5565. return prevInstr;
  5566. }
  5567. void
  5568. Lowerer::GenerateDirectFieldStore(IR::Instr* instrStFld, IR::PropertySymOpnd* propertySymOpnd)
  5569. {
  5570. Func* func = instrStFld->m_func;
  5571. IR::Opnd *opndSlotArray = this->LoadSlotArrayWithCachedLocalType(instrStFld, propertySymOpnd);
  5572. // Store the value to the slot, getting the slot index from the cache.
  5573. uint16 index = propertySymOpnd->GetSlotIndex();
  5574. Assert(index != -1);
  5575. #ifdef RECYCLER_RECYCLER_WRITE_BARRIER_JIT
  5576. if (opndSlotArray->IsRegOpnd())
  5577. {
  5578. IR::IndirOpnd * opndDst = IR::IndirOpnd::New(opndSlotArray->AsRegOpnd(), index * sizeof(Js::Var), TyMachReg, func);
  5579. LowererMD::GenerateWriteBarrierAssign(opndDst, instrStFld->GetSrc1(), instrStFld);
  5580. }
  5581. else
  5582. {
  5583. Assert(opndSlotArray->IsMemRefOpnd());
  5584. IR::MemRefOpnd * opndDst = IR::MemRefOpnd::New((char*)opndSlotArray->AsMemRefOpnd()->GetMemLoc() + (index * sizeof(Js::Var)), TyMachReg, func);
  5585. LowererMD::GenerateWriteBarrierAssign(opndDst, instrStFld->GetSrc1(), instrStFld);
  5586. }
  5587. #else
  5588. IR::Opnd *opnd;
  5589. if (opndSlotArray->IsRegOpnd())
  5590. {
  5591. opnd = IR::IndirOpnd::New(opndSlotArray->AsRegOpnd(), index * sizeof(Js::Var), TyMachReg, func);
  5592. }
  5593. else
  5594. {
  5595. opnd = IR::MemRefOpnd::New((char*)opndSlotArray->AsMemRefOpnd()->GetMemLoc() + (index * sizeof(Js::Var)), TyMachReg, func);
  5596. }
  5597. this->m_lowererMD.CreateAssign(opnd, instrStFld->GetSrc1(), instrStFld);
  5598. #endif
  5599. }
  5600. bool
  5601. Lowerer::GenerateStFldWithCachedType(IR::Instr *instrStFld, bool* continueAsHelperOut, IR::LabelInstr** labelHelperOut, IR::RegOpnd** typeOpndOut)
  5602. {
  5603. IR::Instr *instr;
  5604. IR::RegOpnd *typeOpnd = nullptr;
  5605. IR::LabelInstr* labelObjCheckFailed = nullptr;
  5606. IR::LabelInstr *labelTypeCheckFailed = nullptr;
  5607. IR::LabelInstr *labelBothTypeChecksFailed = nullptr;
  5608. IR::LabelInstr *labelDone = nullptr;
  5609. Assert(continueAsHelperOut != nullptr);
  5610. *continueAsHelperOut = false;
  5611. Assert(labelHelperOut != nullptr);
  5612. *labelHelperOut = nullptr;
  5613. Assert(typeOpndOut != nullptr);
  5614. *typeOpndOut = nullptr;
  5615. Assert(instrStFld->GetDst()->IsSymOpnd());
  5616. if (!instrStFld->GetDst()->AsSymOpnd()->IsPropertySymOpnd() || !instrStFld->GetDst()->AsPropertySymOpnd()->IsTypeCheckSeqCandidate())
  5617. {
  5618. return false;
  5619. }
  5620. IR::PropertySymOpnd *propertySymOpnd = instrStFld->GetDst()->AsPropertySymOpnd();
  5621. // If we have any object type spec info, we better not believe this is a load from prototype, since this is a store
  5622. // and we never share inline caches between loads and stores.
  5623. Assert(!propertySymOpnd->HasObjTypeSpecFldInfo() || !propertySymOpnd->IsLoadedFromProto());
  5624. AssertMsg(propertySymOpnd->TypeCheckSeqBitsSetOnlyIfCandidate(), "Property sym operand optimized despite not being a candidate?");
  5625. if (!propertySymOpnd->IsTypeCheckSeqCandidate())
  5626. {
  5627. return false;
  5628. }
  5629. if (!propertySymOpnd->IsTypeCheckSeqParticipant() && !propertySymOpnd->NeedsLocalTypeCheck())
  5630. {
  5631. return false;
  5632. }
  5633. Assert(!propertySymOpnd->NeedsTypeCheckAndBailOut() || (instrStFld->HasBailOutInfo() && IR::IsTypeCheckBailOutKind(instrStFld->GetBailOutKind())));
  5634. // In the backwards pass we only add guarded property operations to instructions that are not already
  5635. // protected by an upstream type check.
  5636. Assert(!propertySymOpnd->IsTypeCheckProtected() || propertySymOpnd->GetGuardedPropOps() == nullptr);
  5637. PHASE_PRINT_TESTTRACE(
  5638. Js::ObjTypeSpecPhase,
  5639. this->m_func,
  5640. L"Field store: %s, property: %s, func: %s, cache ID: %d, cloned cache: true, layout: %s, redundant check: %s\n",
  5641. Js::OpCodeUtil::GetOpCodeName(instrStFld->m_opcode),
  5642. this->m_func->GetScriptContext()->GetPropertyNameLocked(propertySymOpnd->m_sym->AsPropertySym()->m_propertyId)->GetBuffer(),
  5643. this->m_func->GetJnFunction()->GetDisplayName(),
  5644. propertySymOpnd->m_inlineCacheIndex, propertySymOpnd->GetCacheLayoutString(),
  5645. propertySymOpnd->IsTypeChecked() ? L"true" : L"false");
  5646. if (propertySymOpnd->HasFinalType() && !propertySymOpnd->IsLoadedFromProto())
  5647. {
  5648. propertySymOpnd->UpdateSlotForFinalType();
  5649. }
  5650. Func* func = instrStFld->m_func;
  5651. // TODO (ObjTypeSpec): If ((PropertySym*)propertySymOpnd->m_sym)->m_stackSym->m_isIntConst consider emitting a direct
  5652. // jump to helper or bailout. If we have a type check bailout, we could even abort compilation.
  5653. bool hasTypeCheckBailout = instrStFld->HasBailOutInfo() && IR::IsTypeCheckBailOutKind(instrStFld->GetBailOutKind());
  5654. // If the type hasn't been checked upstream, see if it makes sense to check it here.
  5655. bool isTypeChecked = propertySymOpnd->IsTypeChecked();
  5656. if (!isTypeChecked)
  5657. {
  5658. // If the initial type has been checked, we can do a hard coded type transition without any type checks
  5659. // (see GenerateStFldWithCachedFinalType), which is always worth doing, even if the type is not needed
  5660. // downstream. We're not introducing any additional bailouts.
  5661. if (propertySymOpnd->HasFinalType() && propertySymOpnd->HasInitialType() && !propertySymOpnd->IsTypeDead())
  5662. {
  5663. // We have a final type in hand, so we can JIT (most of) the type transition work.
  5664. return this->GenerateStFldWithCachedFinalType(instrStFld, propertySymOpnd);
  5665. }
  5666. if (propertySymOpnd->HasTypeMismatch())
  5667. {
  5668. // So we have a type mismatch, which happens when the type (and the type without property if ObjTypeSpecStore
  5669. // is on) on this instruction didn't match the live type value according to the flow. We must have hit some
  5670. // stale inline cache (perhaps inlined from a different function, or on a code path not taken for a while).
  5671. // Either way, we know exactly what type the object must have at this point (fully determined by flow), but
  5672. // we don't know whether that type already has the property we're storing here. All in all, we know exactly
  5673. // what shape the object will have after this operation, but we're not sure what label (type) to give this
  5674. // shape. Thus we can simply let the fast path do its thing based on the live inline cache. The downstream
  5675. // instructions relying only on this shape (loads and stores) are safe, and those that need the next type
  5676. // (i.e. adds) will do the same thing as this instruction.
  5677. return false;
  5678. }
  5679. // If we're still here then we must need a primary type check on this instruction to protect
  5680. // a sequence of field operations downstream, or a local type check for an isolated field store.
  5681. Assert(propertySymOpnd->NeedsPrimaryTypeCheck() || propertySymOpnd->NeedsLocalTypeCheck());
  5682. labelTypeCheckFailed = IR::LabelInstr::New(Js::OpCode::Label, func, true);
  5683. labelBothTypeChecksFailed = IR::LabelInstr::New(Js::OpCode::Label, func, true);
  5684. labelObjCheckFailed = hasTypeCheckBailout ? labelBothTypeChecksFailed : IR::LabelInstr::New(Js::OpCode::Label, func, true);
  5685. typeOpnd = this->GenerateCachedTypeCheck(instrStFld, propertySymOpnd, labelObjCheckFailed, labelBothTypeChecksFailed, labelTypeCheckFailed);
  5686. *typeOpndOut = typeOpnd;
  5687. }
  5688. // Either we are protected by a type check upstream or we just emitted a type check above,
  5689. // now it's time to store the field value.
  5690. GenerateDirectFieldStore(instrStFld, propertySymOpnd);
  5691. // If we are protected by a type check upstream, we don't need a bailout or helper here, delete the instruction
  5692. // and return "true" to indicate that we succeeded in eliminating it.
  5693. if (isTypeChecked)
  5694. {
  5695. Assert(labelTypeCheckFailed == nullptr && labelBothTypeChecksFailed == nullptr);
  5696. AssertMsg(!instrStFld->HasBailOutInfo(), "Why does a direct field store have bailout?");
  5697. instrStFld->Remove();
  5698. return true;
  5699. }
  5700. // Otherwise, branch around the helper on successful type check.
  5701. labelDone = IR::LabelInstr::New(Js::OpCode::Label, func);
  5702. instr = IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, labelDone, func);
  5703. instrStFld->InsertBefore(instr);
  5704. // On failed type check, try the type without property if we've got one.
  5705. instrStFld->InsertBefore(labelTypeCheckFailed);
  5706. // Caution, this is one of the dusty corners of the JIT. We only get here if this is an isolated StFld which adds a property, or
  5707. // ObjTypeSpecStore is off. In the former case no downstream operations depend on the final type produced here, and we can fall
  5708. // back on live cache and helper if the type doesn't match. In the latter we may have a cache with type transition, which must
  5709. // produce a value for the type after transition, because that type is consumed downstream. Thus, if the object's type doesn't
  5710. // match either the type with or the type without the property we're storing, we must bail out here.
  5711. bool emitAddProperty = propertySymOpnd->IsMono() && propertySymOpnd->HasInitialType();
  5712. if (emitAddProperty)
  5713. {
  5714. GenerateCachedTypeWithoutPropertyCheck(instrStFld, propertySymOpnd, typeOpnd, labelBothTypeChecksFailed);
  5715. GenerateFieldStoreWithTypeChange(instrStFld, propertySymOpnd, propertySymOpnd->GetInitialType(), propertySymOpnd->GetType());
  5716. instr = IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, labelDone, func);
  5717. instrStFld->InsertBefore(instr);
  5718. }
  5719. instrStFld->InsertBefore(labelBothTypeChecksFailed);
  5720. instrStFld->InsertAfter(labelDone);
  5721. if (hasTypeCheckBailout)
  5722. {
  5723. AssertMsg(PHASE_ON1(Js::ObjTypeSpecIsolatedFldOpsWithBailOutPhase) || !propertySymOpnd->IsTypeDead(),
  5724. "Why does a field store have a type check bailout, if its type is dead?");
  5725. if (instrStFld->GetBailOutInfo()->bailOutInstr != instrStFld)
  5726. {
  5727. // Set the cache index in the bailout info so that the generated code will write it into the
  5728. // bailout record at runtime.
  5729. instrStFld->GetBailOutInfo()->polymorphicCacheIndex = propertySymOpnd->m_inlineCacheIndex;
  5730. }
  5731. else
  5732. {
  5733. Assert(instrStFld->GetBailOutInfo()->polymorphicCacheIndex == propertySymOpnd->m_inlineCacheIndex);
  5734. }
  5735. instrStFld->m_opcode = Js::OpCode::BailOut;
  5736. instrStFld->FreeSrc1();
  5737. instrStFld->FreeDst();
  5738. this->GenerateBailOut(instrStFld);
  5739. return true;
  5740. }
  5741. else
  5742. {
  5743. *continueAsHelperOut = true;
  5744. Assert(labelObjCheckFailed != nullptr && labelObjCheckFailed != labelBothTypeChecksFailed);
  5745. *labelHelperOut = labelObjCheckFailed;
  5746. return false;
  5747. }
  5748. }
  5749. IR::RegOpnd *
  5750. Lowerer::GenerateCachedTypeCheck(IR::Instr *instrChk, IR::PropertySymOpnd *propertySymOpnd, IR::LabelInstr* labelObjCheckFailed, IR::LabelInstr *labelTypeCheckFailed, IR::LabelInstr *labelSecondChance)
  5751. {
  5752. Assert(propertySymOpnd->MayNeedTypeCheckProtection());
  5753. Func* func = instrChk->m_func;
  5754. IR::RegOpnd *regOpnd = propertySymOpnd->CreatePropertyOwnerOpnd(func);
  5755. regOpnd->SetValueType(propertySymOpnd->GetPropertyOwnerValueType());
  5756. if (!regOpnd->IsNotTaggedValue())
  5757. {
  5758. m_lowererMD.GenerateObjectTest(regOpnd, instrChk, labelObjCheckFailed);
  5759. }
  5760. IR::Opnd *expectedTypeOpnd;
  5761. bool emitDirectCheck = true;
  5762. // Note: don't attempt equivalent type check if we're doing a final type optimization or if we have a monomorphic
  5763. // cache and no type check bailout. In the latter case, we can wind up doing expensive failed equivalence checks
  5764. // repeatedly and never rejit.
  5765. bool doEquivTypeCheck =
  5766. propertySymOpnd->HasEquivalentTypeSet() &&
  5767. !(propertySymOpnd->HasFinalType() && propertySymOpnd->HasInitialType()) &&
  5768. !propertySymOpnd->MustDoMonoCheck() &&
  5769. (propertySymOpnd->IsPoly() || instrChk->HasTypeCheckBailOut());
  5770. Assert(doEquivTypeCheck || !instrChk->HasEquivalentTypeCheckBailOut());
  5771. Js::Type* type = doEquivTypeCheck ? propertySymOpnd->GetFirstEquivalentType() : propertySymOpnd->GetType();
  5772. Js::PropertyGuard* typeCheckGuard = doEquivTypeCheck ?
  5773. (Js::PropertyGuard*)CreateEquivalentTypeGuardAndLinkToGuardedProperties(type, propertySymOpnd) :
  5774. (Js::PropertyGuard*)CreateTypePropertyGuardForGuardedProperties(type, propertySymOpnd);
  5775. if (typeCheckGuard == nullptr)
  5776. {
  5777. Assert(type != nullptr);
  5778. expectedTypeOpnd = IR::AddrOpnd::New(type, IR::AddrOpndKindDynamicType, func, true);
  5779. }
  5780. else
  5781. {
  5782. Assert(Js::PropertyGuard::GetSizeOfValue() == static_cast<size_t>(TySize[TyMachPtr]));
  5783. expectedTypeOpnd = IR::MemRefOpnd::New((void*)(typeCheckGuard->GetAddressOfValue()), TyMachPtr, func, IR::AddrOpndKindDynamicGuardValueRef);
  5784. emitDirectCheck = false;
  5785. }
  5786. if (PHASE_VERBOSE_TRACE(Js::ObjTypeSpecPhase, this->m_func))
  5787. {
  5788. OUTPUT_VERBOSE_TRACE_FUNC(Js::ObjTypeSpecPhase, this->m_func, L"Emitted %s type check for type 0x%p",
  5789. emitDirectCheck ? L"direct" : propertySymOpnd->IsPoly() ? L"equivalent" : L"indirect", type);
  5790. #if DBG
  5791. if (propertySymOpnd->GetGuardedPropOps() != nullptr)
  5792. {
  5793. Output::Print(L" guarding operations:\n ");
  5794. propertySymOpnd->GetGuardedPropOps()->Dump();
  5795. }
  5796. else
  5797. {
  5798. Output::Print(L"\n");
  5799. }
  5800. #else
  5801. Output::Print(L"\n");
  5802. #endif
  5803. Output::Flush();
  5804. }
  5805. IR::RegOpnd* typeOpnd = IR::RegOpnd::New(TyMachReg, func);
  5806. IR::Opnd *sourceType;
  5807. if (regOpnd->m_sym->IsConst() && !regOpnd->m_sym->IsIntConst() && !regOpnd->m_sym->IsFloatConst())
  5808. {
  5809. sourceType = IR::MemRefOpnd::New((BYTE*)regOpnd->m_sym->GetConstAddress() +
  5810. Js::RecyclableObject::GetOffsetOfType(), TyMachReg, func, IR::AddrOpndKindDynamicObjectTypeRef);
  5811. }
  5812. else
  5813. {
  5814. sourceType = IR::IndirOpnd::New(regOpnd, Js::RecyclableObject::GetOffsetOfType(), TyMachReg, func);
  5815. }
  5816. m_lowererMD.CreateAssign(typeOpnd, sourceType, instrChk);
  5817. if (doEquivTypeCheck)
  5818. {
  5819. // TODO (ObjTypeSpec): For isolated equivalent type checks it would be good to emit a check if the cache is still valid, and
  5820. // if not go straight to live polymorphic cache. This way we wouldn't have to bail out and re-JIT, and also wouldn't continue
  5821. // to try the equivalent type cache, miss it and do the slow comparison. This may be as easy as sticking a null on the main
  5822. // type in the equivalent type cache.
  5823. IR::LabelInstr* labelCheckEquivalentType = IR::LabelInstr::New(Js::OpCode::Label, func, true);
  5824. InsertCompareBranch(typeOpnd, expectedTypeOpnd, Js::OpCode::BrNeq_A, labelCheckEquivalentType, instrChk);
  5825. IR::LabelInstr *labelTypeCheckSucceeded = IR::LabelInstr::New(Js::OpCode::Label, func, false);
  5826. InsertBranch(Js::OpCode::Br, labelTypeCheckSucceeded, instrChk);
  5827. instrChk->InsertBefore(labelCheckEquivalentType);
  5828. this->m_lowererMD.LoadHelperArgument(instrChk, IR::AddrOpnd::New((Js::Var)typeCheckGuard, IR::AddrOpndKindDynamicTypeCheckGuard, func, true));
  5829. this->m_lowererMD.LoadHelperArgument(instrChk, typeOpnd);
  5830. IR::RegOpnd* equivalentTypeCheckResultOpnd = IR::RegOpnd::New(TyUint8, func);
  5831. IR::HelperCallOpnd* equivalentTypeCheckHelperCallOpnd = IR::HelperCallOpnd::New(IR::HelperCheckIfTypeIsEquivalent, func);
  5832. IR::Instr* equivalentTypeCheckCallInstr = IR::Instr::New(Js::OpCode::Call, equivalentTypeCheckResultOpnd, equivalentTypeCheckHelperCallOpnd, func);
  5833. instrChk->InsertBefore(equivalentTypeCheckCallInstr);
  5834. this->m_lowererMD.LowerCall(equivalentTypeCheckCallInstr, 0);
  5835. InsertTestBranch(equivalentTypeCheckResultOpnd, equivalentTypeCheckResultOpnd, Js::OpCode::BrEq_A, labelTypeCheckFailed, instrChk);
  5836. // TODO (ObjTypeSpec): Consider emitting a shared bailout to which a specific bailout kind is written at runtime. This would allow us to distinguish
  5837. // between non-equivalent type and other cases, such as invalidated guard (due to fixed field overwrite, perhaps) or too much thrashing on the
  5838. // equivalent type cache. We could determine bailout kind based on the value returned by the helper. In the case of cache thrashing we could just
  5839. // turn off the whole optimization for a given function.
  5840. instrChk->InsertBefore(labelTypeCheckSucceeded);
  5841. }
  5842. else
  5843. {
  5844. InsertCompareBranch(typeOpnd, expectedTypeOpnd, Js::OpCode::BrNeq_A, labelSecondChance != nullptr ? labelSecondChance : labelTypeCheckFailed, instrChk);
  5845. }
  5846. // Don't pin the type for polymorphic operations. The code can successfully execute even if this type is no longer referenced by any objects,
  5847. // as long as there are other objects with types equivalent on the properties referenced by this code. The type is kept alive until entry point
  5848. // installation by the JIT transfer data, and after that by the equivalent type cache, so it will stay alive unless or until it gets evicted
  5849. // from the cache.
  5850. if (!doEquivTypeCheck)
  5851. {
  5852. PinTypeRef(type, type, instrChk, propertySymOpnd->m_sym->AsPropertySym()->m_propertyId);
  5853. }
  5854. return typeOpnd;
  5855. }
  5856. void
  5857. Lowerer::PinTypeRef(Js::Type* type, void* typeRef, IR::Instr* instr, Js::PropertyId propertyId)
  5858. {
  5859. this->m_func->PinTypeRef(typeRef);
  5860. if (PHASE_TRACE(Js::TracePinnedTypesPhase, this->m_func))
  5861. {
  5862. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5863. Output::Print(L"PinnedTypes: function %s(%s) instr %s property %s(#%u) pinned %s reference 0x%p to type 0x%p.\n",
  5864. this->m_func->GetJnFunction()->GetDisplayName(), this->m_func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  5865. Js::OpCodeUtil::GetOpCodeName(instr->m_opcode), GetScriptContext()->GetPropertyNameLocked(propertyId)->GetBuffer(), propertyId,
  5866. typeRef == type ? L"strong" : L"weak", typeRef, type);
  5867. Output::Flush();
  5868. }
  5869. }
  5870. void
  5871. Lowerer::GenerateCachedTypeWithoutPropertyCheck(IR::Instr *instrInsert, IR::PropertySymOpnd *propertySymOpnd, IR::Opnd *typeOpnd, IR::LabelInstr *labelTypeCheckFailed)
  5872. {
  5873. Assert(propertySymOpnd->IsMonoObjTypeSpecCandidate());
  5874. Assert(propertySymOpnd->HasInitialType());
  5875. Js::Type* typeWithoutProperty = propertySymOpnd->GetInitialType();
  5876. // We should never add properties to objects of static types.
  5877. Assert(Js::DynamicType::Is(typeWithoutProperty->GetTypeId()));
  5878. if (typeOpnd == nullptr)
  5879. {
  5880. // No opnd holding the type was passed in, so we have to load the type here.
  5881. IR::RegOpnd *baseOpnd = propertySymOpnd->CreatePropertyOwnerOpnd(m_func);
  5882. if (!baseOpnd->IsNotTaggedValue())
  5883. {
  5884. m_lowererMD.GenerateObjectTest(baseOpnd, instrInsert, labelTypeCheckFailed);
  5885. }
  5886. IR::Opnd *opnd = IR::IndirOpnd::New(baseOpnd, Js::RecyclableObject::GetOffsetOfType(), TyMachReg, this->m_func);
  5887. typeOpnd = IR::RegOpnd::New(TyMachReg, this->m_func);
  5888. m_lowererMD.CreateAssign(typeOpnd, opnd, instrInsert);
  5889. }
  5890. Js::JitTypePropertyGuard* typePropertyGuard = CreateTypePropertyGuardForGuardedProperties(typeWithoutProperty, propertySymOpnd);
  5891. IR::Opnd *expectedTypeOpnd;
  5892. if (typePropertyGuard)
  5893. {
  5894. bool emitDirectCheck = true;
  5895. Assert(typePropertyGuard != nullptr);
  5896. Assert(Js::PropertyGuard::GetSizeOfValue() == static_cast<size_t>(TySize[TyMachPtr]));
  5897. expectedTypeOpnd = IR::MemRefOpnd::New((void*)(typePropertyGuard->GetAddressOfValue()), TyMachPtr, this->m_func, IR::AddrOpndKindDynamicGuardValueRef);
  5898. emitDirectCheck = false;
  5899. OUTPUT_VERBOSE_TRACE_FUNC(Js::ObjTypeSpecPhase, this->m_func, L"Emitted %s type check for type 0x%p.\n",
  5900. emitDirectCheck ? L"direct" : L"indirect", typeWithoutProperty);
  5901. }
  5902. else
  5903. {
  5904. expectedTypeOpnd = IR::AddrOpnd::New(typeWithoutProperty, IR::AddrOpndKindDynamicType, m_func, true);
  5905. }
  5906. InsertCompareBranch(typeOpnd, expectedTypeOpnd, Js::OpCode::BrNeq_A, labelTypeCheckFailed, instrInsert);
  5907. // Technically, it should be enough to pin the final type, because it should keep all of its predecessors alive, but
  5908. // just to be extra cautious, let's pin the initial type as well.
  5909. PinTypeRef(typeWithoutProperty, typeWithoutProperty, instrInsert, propertySymOpnd->m_sym->AsPropertySym()->m_propertyId);
  5910. }
  5911. void
  5912. Lowerer::GenerateFixedFieldGuardCheck(IR::Instr *insertPointInstr, IR::PropertySymOpnd *propertySymOpnd, IR::LabelInstr *labelBailOut)
  5913. {
  5914. GeneratePropertyGuardCheck(insertPointInstr, propertySymOpnd, labelBailOut);
  5915. }
  5916. Js::JitTypePropertyGuard*
  5917. Lowerer::CreateTypePropertyGuardForGuardedProperties(Js::Type* type, IR::PropertySymOpnd* propertySymOpnd)
  5918. {
  5919. // We should always have a list of guarded properties.
  5920. Assert(propertySymOpnd->GetGuardedPropOps() != nullptr);
  5921. Js::JitTypePropertyGuard* guard = nullptr;
  5922. Js::EntryPointInfo* entryPointInfo = this->m_func->m_workItem->GetEntryPoint();
  5923. if (entryPointInfo->HasSharedPropertyGuards())
  5924. {
  5925. // Consider (ObjTypeSpec): Because we allocate these guards from the JIT thread we can't share guards for the same type across multiple functions.
  5926. // This leads to proliferation of property guards on the thread context. The alternative would be to pre-allocate shared (by value) guards
  5927. // from the thread context during work item creation. We would create too many of them (because some types aren't actually used as guards),
  5928. // but we could share a guard for a given type between functions. This may ultimately be better.
  5929. LinkGuardToGuardedProperties(entryPointInfo, propertySymOpnd->GetGuardedPropOps(), [this, type, &guard](Js::PropertyId propertyId)
  5930. {
  5931. if (DoLazyFixedTypeBailout(this->m_func))
  5932. {
  5933. this->m_func->lazyBailoutProperties.Item(propertyId);
  5934. }
  5935. else
  5936. {
  5937. if (guard == nullptr)
  5938. {
  5939. guard = this->m_func->GetOrCreateSingleTypeGuard(type);
  5940. }
  5941. if (PHASE_TRACE(Js::ObjTypeSpecPhase, this->m_func) || PHASE_TRACE(Js::TracePropertyGuardsPhase, this->m_func))
  5942. {
  5943. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5944. wchar_t workItemName[256];
  5945. this->m_func->m_workItem->GetDisplayName(workItemName, _countof(workItemName));
  5946. Output::Print(L"ObjTypeSpec: function %s(%s) registered guard 0x%p with value 0x%p for property %s (%u).\n",
  5947. workItemName, this->m_func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  5948. guard, guard->GetValue(), this->GetScriptContext()->GetPropertyNameLocked(propertyId)->GetBuffer(), propertyId);
  5949. Output::Flush();
  5950. }
  5951. this->m_func->EnsurePropertyGuardsByPropertyId();
  5952. this->m_func->LinkGuardToPropertyId(propertyId, guard);
  5953. }
  5954. });
  5955. }
  5956. return guard;
  5957. }
  5958. Js::JitEquivalentTypeGuard*
  5959. Lowerer::CreateEquivalentTypeGuardAndLinkToGuardedProperties(Js::Type* type, IR::PropertySymOpnd* propertySymOpnd)
  5960. {
  5961. // We should always have a list of guarded properties.
  5962. Assert(propertySymOpnd->HasObjTypeSpecFldInfo() && propertySymOpnd->HasEquivalentTypeSet() && propertySymOpnd->GetGuardedPropOps());
  5963. Js::JitEquivalentTypeGuard* guard = this->m_func->CreateEquivalentTypeGuard(type, propertySymOpnd->GetObjTypeSpecFldId());
  5964. Js::EntryPointInfo* entryPointInfo = this->m_func->m_workItem->GetEntryPoint();
  5965. if (entryPointInfo->HasSharedPropertyGuards())
  5966. {
  5967. LinkGuardToGuardedProperties(entryPointInfo, propertySymOpnd->GetGuardedPropOps(), [=](Js::PropertyId propertyId)
  5968. {
  5969. if (PHASE_TRACE(Js::ObjTypeSpecPhase, this->m_func) || PHASE_TRACE(Js::TracePropertyGuardsPhase, this->m_func))
  5970. {
  5971. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  5972. Output::Print(L"ObjTypeSpec: function %s(%s) registered equivalent type spec guard 0x%p with value 0x%p for property %s (%u).\n",
  5973. this->m_func->GetJnFunction()->GetDisplayName(), this->m_func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  5974. guard, guard->GetValue(), GetScriptContext()->GetPropertyNameLocked(propertyId)->GetBuffer(), propertyId);
  5975. Output::Flush();
  5976. }
  5977. this->m_func->EnsurePropertyGuardsByPropertyId();
  5978. this->m_func->LinkGuardToPropertyId(propertyId, guard);
  5979. });
  5980. }
  5981. Assert(guard->GetCache() != nullptr);
  5982. Js::EquivalentTypeCache* cache = guard->GetCache();
  5983. // TODO (ObjTypeSpec): If we delayed populating the types until encoder, we could bulk allocate all equivalent type caches
  5984. // in one block from the heap. This would allow us to not allocate them from the native code data allocator and free them
  5985. // when no longer needed. However, we would need to store the global property operation ID in the guard, so we can look up
  5986. // the info in the encoder. Perhaps we could overload the cache pointer to be the ID until encoder.
  5987. // Copy types from the type set to the guard's cache
  5988. Js::EquivalentTypeSet* typeSet = propertySymOpnd->GetEquivalentTypeSet();
  5989. uint16 cachedTypeCount = typeSet->GetCount() < EQUIVALENT_TYPE_CACHE_SIZE ? typeSet->GetCount() : EQUIVALENT_TYPE_CACHE_SIZE;
  5990. for (uint16 ti = 0; ti < cachedTypeCount; ti++)
  5991. {
  5992. cache->types[ti] = typeSet->GetType(ti);
  5993. }
  5994. // Populate property ID and slot index arrays on the guard's cache. We iterate over the
  5995. // bit vector of property operations protected by this guard, but some property operations
  5996. // may be referring to the same property ID (but not share the same cache). We skip
  5997. // redundant entries by maintaining a hash set of property IDs we've already encountered.
  5998. auto propOps = propertySymOpnd->GetGuardedPropOps();
  5999. uint propOpCount = propOps->Count();
  6000. bool isTypeStatic = Js::StaticType::Is(type->GetTypeId());
  6001. JsUtil::BaseDictionary<Js::PropertyId, Js::EquivalentPropertyEntry*, JitArenaAllocator> propIds(this->m_alloc, propOpCount);
  6002. Js::EquivalentPropertyEntry* properties = AnewArray(this->m_alloc, Js::EquivalentPropertyEntry, propOpCount);
  6003. uint propIdCount = 0;
  6004. FOREACH_BITSET_IN_SPARSEBV(propOpId, propOps)
  6005. {
  6006. Js::ObjTypeSpecFldInfo* propOpInfo = this->m_func->GetGlobalObjTypeSpecFldInfo(propOpId);
  6007. Js::PropertyId propertyId = propOpInfo->GetPropertyId();
  6008. Js::PropertyIndex propOpIndex = Js::Constants::NoSlot;
  6009. bool hasFixedValue = propOpInfo->HasFixedValue();
  6010. if (hasFixedValue)
  6011. {
  6012. cache->SetHasFixedValue();
  6013. }
  6014. bool isLoadedFromProto = propOpInfo->IsLoadedFromProto();
  6015. if (isLoadedFromProto)
  6016. {
  6017. cache->SetIsLoadedFromProto();
  6018. }
  6019. else
  6020. {
  6021. propOpIndex = propOpInfo->GetSlotIndex();
  6022. }
  6023. bool propOpUsesAuxSlot = propOpInfo->UsesAuxSlot();
  6024. AssertMsg(!isTypeStatic || !propOpInfo->IsBeingStored(), "Why are we storing a field to an object of static type?");
  6025. Js::EquivalentPropertyEntry* entry;
  6026. if (propIds.TryGetValue(propertyId, &entry))
  6027. {
  6028. if (propOpIndex == entry->slotIndex && propOpUsesAuxSlot == entry->isAuxSlot)
  6029. {
  6030. entry->mustBeWritable |= propOpInfo->IsBeingStored();
  6031. }
  6032. else
  6033. {
  6034. // Due to inline cache sharing we have the same property accessed using different caches
  6035. // with inconsistent info. This means a guaranteed bailout on the equivalent type check.
  6036. // We'll just let it happen and turn off the optimization for this function. We could avoid
  6037. // this problem by tracking property information on the value type in glob opt.
  6038. if (PHASE_TRACE(Js::EquivObjTypeSpecPhase, this->m_func))
  6039. {
  6040. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  6041. Js::FunctionBody* topFunctionBody = this->m_func->GetJnFunction();
  6042. Js::ScriptContext* scriptContext = topFunctionBody->GetScriptContext();
  6043. Output::Print(L"EquivObjTypeSpec: top function %s (%s): duplicate property clash on %s(#%d) \n",
  6044. topFunctionBody->GetDisplayName(), topFunctionBody->GetDebugNumberSet(debugStringBuffer), propertyId, scriptContext->GetPropertyNameLocked(propertyId)->GetBuffer());
  6045. Output::Flush();
  6046. }
  6047. Assert(propIdCount < propOpCount);
  6048. __analysis_assume(propIdCount < propOpCount);
  6049. entry = &properties[propIdCount++];
  6050. entry->propertyId = propertyId;
  6051. entry->slotIndex = propOpIndex;
  6052. entry->isAuxSlot = propOpUsesAuxSlot;
  6053. entry->mustBeWritable = propOpInfo->IsBeingStored();
  6054. }
  6055. }
  6056. else
  6057. {
  6058. Assert(propIdCount < propOpCount);
  6059. __analysis_assume(propIdCount < propOpCount);
  6060. entry = &properties[propIdCount++];
  6061. entry->propertyId = propertyId;
  6062. entry->slotIndex = propOpIndex;
  6063. entry->isAuxSlot = propOpUsesAuxSlot;
  6064. entry->mustBeWritable = propOpInfo->IsBeingStored();
  6065. propIds.AddNew(propertyId, entry);
  6066. }
  6067. }
  6068. NEXT_BITSET_IN_SPARSEBV;
  6069. cache->record.propertyCount = propIdCount;
  6070. cache->record.properties = NativeCodeDataNewArray(this->m_func->GetNativeCodeDataAllocator(), Js::EquivalentPropertyEntry, propIdCount);
  6071. memcpy(cache->record.properties, properties, propIdCount * sizeof(Js::EquivalentPropertyEntry));
  6072. return guard;
  6073. }
  6074. bool
  6075. Lowerer::LinkCtorCacheToGuardedProperties(Js::JitTimeConstructorCache* ctorCache)
  6076. {
  6077. // We do not always have guarded properties. If the constructor is empty and the subsequent code doesn't load or store any of
  6078. // the constructed object's properties, or if all inline caches are empty then this ctor cache doesn't guard any properties.
  6079. if (ctorCache->GetGuardedPropOps() == nullptr)
  6080. {
  6081. return false;
  6082. }
  6083. bool linked = false;
  6084. Js::EntryPointInfo* entryPointInfo = this->m_func->m_workItem->GetEntryPoint();
  6085. if (entryPointInfo->HasSharedPropertyGuards())
  6086. {
  6087. linked = LinkGuardToGuardedProperties(entryPointInfo, ctorCache->GetGuardedPropOps(), [=](Js::PropertyId propertyId)
  6088. {
  6089. if (PHASE_TRACE(Js::ObjTypeSpecPhase, this->m_func) || PHASE_TRACE(Js::TracePropertyGuardsPhase, this->m_func))
  6090. {
  6091. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  6092. Output::Print(L"ObjTypeSpec: function %s(%s) registered ctor cache 0x%p with value 0x%p for property %s (%u).\n",
  6093. this->m_func->GetJnFunction()->GetDisplayName(), this->m_func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  6094. ctorCache->runtimeCache, ctorCache->type, GetScriptContext()->GetPropertyNameLocked(propertyId)->GetBuffer(), propertyId);
  6095. Output::Flush();
  6096. }
  6097. this->m_func->EnsureCtorCachesByPropertyId();
  6098. this->m_func->LinkCtorCacheToPropertyId(propertyId, ctorCache);
  6099. });
  6100. }
  6101. return linked;
  6102. }
  6103. template<typename LinkFunc>
  6104. bool
  6105. Lowerer::LinkGuardToGuardedProperties(Js::EntryPointInfo* entryPointInfo, const BVSparse<JitArenaAllocator>* guardedPropOps, LinkFunc link)
  6106. {
  6107. Assert(entryPointInfo != nullptr);
  6108. Assert(entryPointInfo->HasSharedPropertyGuards());
  6109. Assert(guardedPropOps != nullptr);
  6110. bool linked = false;
  6111. // For every entry in the bit vector, register the guard for the corresponding property ID.
  6112. FOREACH_BITSET_IN_SPARSEBV(propertyOpId, guardedPropOps)
  6113. {
  6114. Js::ObjTypeSpecFldInfo* propertyOpInfo = this->m_func->GetGlobalObjTypeSpecFldInfo(propertyOpId);
  6115. Js::PropertyId propertyId = propertyOpInfo->GetPropertyId();
  6116. // It's okay for an equivalent type check to be registered as a guard against a property becoming read-only. This transpires if, there is
  6117. // a different monomorphic type check upstream, which guarantees the actual type of the object needed for the hard-coded type transition,
  6118. // but it is later followed by a sequence of polymorphic inline caches, which do not have that type in the type set. At the beginning of
  6119. // that sequence we'll emit an equivalent type check to verify that the actual type has relevant properties on appropriate slots. Then in
  6120. // the dead store pass we'll walk upwards and encounter this check first, thus we'll drop the guarded properties accumulated thus far
  6121. // (including the one being added) on that check.
  6122. // AssertMsg(!propertyOpInfo->IsBeingAdded() || !isEquivalentTypeGuard, "Why do we have an equivalent type check protecting a property add?");
  6123. if (propertyOpInfo->IsBeingAdded() || propertyOpInfo->IsLoadedFromProto() || propertyOpInfo->HasFixedValue())
  6124. {
  6125. // Equivalent object type spec only supports fixed fields on prototypes. This is to simplify the slow type equivalence check.
  6126. // See JavascriptOperators::CheckIfTypeIsEquivalent.
  6127. Assert(!propertyOpInfo->IsPoly() || (!propertyOpInfo->HasFixedValue() || propertyOpInfo->IsLoadedFromProto() || propertyOpInfo->UsesAccessor()));
  6128. if (entryPointInfo->HasSharedPropertyGuard(propertyId))
  6129. {
  6130. link(propertyId);
  6131. linked = true;
  6132. }
  6133. else
  6134. {
  6135. #if TRUE
  6136. AssertMsg(false, "Did we fail to create a shared property guard for a guarded property?");
  6137. #else
  6138. if (PHASE_VERBOSE_TRACE(Js::ObjTypeSpecPhase, this->m_func) || PHASE_TRACE(Js::TracePropertyGuardsPhase, this->m_func))
  6139. {
  6140. if (!this->m_func->m_workItem->GetEntryPoint()->HasSharedPropertyGuard(propertyId))
  6141. {
  6142. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  6143. Output::Print(L"ObjTypeStore: function %s(%s): no shared property guard for property % (%u).\n",
  6144. this->m_func->GetJnFunction()->GetDisplayName(), this->m_func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  6145. GetScriptContext()->GetPropertyNameLocked(propertyId)->GetBuffer(), propertyId);
  6146. Output::Flush();
  6147. }
  6148. }
  6149. #endif
  6150. }
  6151. }
  6152. }
  6153. NEXT_BITSET_IN_SPARSEBV;
  6154. return linked;
  6155. }
  6156. void
  6157. Lowerer::GeneratePropertyGuardCheck(IR::Instr *insertPointInstr, IR::PropertySymOpnd *propertySymOpnd, IR::LabelInstr *labelBailOut)
  6158. {
  6159. Js::PropertyGuard* guard = propertySymOpnd->GetPropertyGuard();
  6160. Assert(guard != nullptr);
  6161. if (!DoLazyFixedDataBailout(this->m_func))
  6162. {
  6163. Assert(Js::PropertyGuard::GetSizeOfValue() == static_cast<size_t>(TySize[TyMachPtr]));
  6164. IR::AddrOpnd* zeroOpnd = IR::AddrOpnd::NewNull(this->m_func);
  6165. IR::MemRefOpnd* guardOpnd = IR::MemRefOpnd::New((void*)guard->GetAddressOfValue(), TyMachPtr, this->m_func, IR::AddrOpndKindDynamicGuardValueRef);
  6166. InsertCompareBranch(guardOpnd, zeroOpnd, Js::OpCode::BrEq_A, labelBailOut, insertPointInstr);
  6167. }
  6168. else
  6169. {
  6170. this->m_func->lazyBailoutProperties.Item(propertySymOpnd->GetPropertyId());
  6171. }
  6172. }
  6173. IR::Instr*
  6174. Lowerer::GeneratePropertyGuardCheckBailoutAndLoadType(IR::Instr *insertInstr)
  6175. {
  6176. IR::Instr* instrPrev = insertInstr->m_prev;
  6177. IR::Opnd* numberTypeOpnd = IR::AddrOpnd::New(insertInstr->m_func->GetScriptContext()->GetLibrary()->GetNumberTypeStatic(), IR::AddrOpndKindDynamicType, insertInstr->m_func);
  6178. IR::PropertySymOpnd* propertySymOpnd = insertInstr->GetSrc1()->AsPropertySymOpnd();
  6179. IR::LabelInstr* labelBailout = IR::LabelInstr::New(Js::OpCode::Label, insertInstr->m_func, true);
  6180. IR::LabelInstr* labelContinue = IR::LabelInstr::New(Js::OpCode::Label, insertInstr->m_func);
  6181. IR::LabelInstr* loadNumberTypeLabel = IR::LabelInstr::New(Js::OpCode::Label, insertInstr->m_func, true);
  6182. GeneratePropertyGuardCheck(insertInstr, propertySymOpnd, labelBailout);
  6183. IR::RegOpnd *baseOpnd = propertySymOpnd->CreatePropertyOwnerOpnd(m_func);
  6184. GenerateObjectTestAndTypeLoad(insertInstr, baseOpnd, insertInstr->GetDst()->AsRegOpnd(), loadNumberTypeLabel);
  6185. insertInstr->InsertBefore(IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, labelContinue, this->m_func));
  6186. insertInstr->InsertBefore(loadNumberTypeLabel);
  6187. this->m_lowererMD.CreateAssign(insertInstr->GetDst(), numberTypeOpnd, insertInstr);
  6188. insertInstr->InsertBefore(IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, labelContinue, this->m_func));
  6189. insertInstr->InsertBefore(labelBailout);
  6190. insertInstr->InsertAfter(labelContinue);
  6191. insertInstr->FreeSrc1();
  6192. insertInstr->m_opcode = Js::OpCode::BailOut;
  6193. this->GenerateBailOut(insertInstr);
  6194. return instrPrev;
  6195. }
  6196. void
  6197. Lowerer::GenerateNonWritablePropertyCheck(IR::Instr *instrInsert, IR::PropertySymOpnd *propertySymOpnd, IR::LabelInstr *labelBailOut)
  6198. {
  6199. IR::Opnd *opnd;
  6200. IR::Instr *instr;
  6201. // Generate a check for non-writable properties, on the model of the work done by PatchPutValueetc.
  6202. // Inline the check on the bit in the prototype object's type. If that check fails, call the helper.
  6203. // If the helper finds a non-writable property, bail out, as we're counting on being able to add the property.
  6204. Js::Type *typeWithoutProperty = propertySymOpnd->GetInitialType();
  6205. Assert(typeWithoutProperty);
  6206. Js::RecyclableObject *protoObject = typeWithoutProperty->GetPrototype();
  6207. Assert(protoObject);
  6208. // s1 = MOV [proto->type].ptr
  6209. IR::RegOpnd *typeOpnd = IR::RegOpnd::New(TyMachReg, this->m_func);
  6210. opnd = IR::MemRefOpnd::New((char*)protoObject + Js::RecyclableObject::GetOffsetOfType(), TyMachReg,
  6211. this->m_func, IR::AddrOpndKindDynamicObjectTypeRef);
  6212. m_lowererMD.CreateAssign(typeOpnd, opnd, instrInsert);
  6213. // TEST [s1->areThisAndPrototypesEnsuredToHaveOnlyWritableDataProperties].u8, 1
  6214. // JNE $continue
  6215. IR::LabelInstr *labelContinue = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  6216. opnd = IR::IndirOpnd::New(typeOpnd, (int32)Js::Type::OffsetOfWritablePropertiesFlag(), TyUint8, this->m_func);
  6217. InsertTestBranch(opnd, IR::IntConstOpnd::New(1, TyUint8, this->m_func), Js::OpCode::BrNeq_A, labelContinue, instrInsert);
  6218. // $Lhelper:
  6219. IR::LabelInstr *labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  6220. instrInsert->InsertBefore(labelHelper);
  6221. // s2 = CALL DoProtoCheck, prototype
  6222. opnd = IR::AddrOpnd::New(protoObject, IR::AddrOpndKindDynamicVar, this->m_func, true);
  6223. m_lowererMD.LoadHelperArgument(instrInsert, opnd);
  6224. opnd = IR::HelperCallOpnd::New(IR::HelperCheckProtoHasNonWritable, this->m_func);
  6225. instr = IR::Instr::New(Js::OpCode::Call, IR::RegOpnd::New(TyUint8, this->m_func), opnd, this->m_func);
  6226. instrInsert->InsertBefore(instr);
  6227. opnd = instr->GetDst();
  6228. m_lowererMD.LowerCall(instr, 0);
  6229. InsertTestBranch(opnd, opnd, Js::OpCode::BrEq_A, labelBailOut, instrInsert);
  6230. // $Lcontinue:
  6231. instrInsert->InsertBefore(labelContinue);
  6232. }
  6233. void
  6234. Lowerer::GenerateAdjustSlots(IR::Instr *instrInsert, IR::PropertySymOpnd *propertySymOpnd, Js::Type* initialType, Js::Type* finalType)
  6235. {
  6236. IR::RegOpnd *baseOpnd = propertySymOpnd->CreatePropertyOwnerOpnd(m_func);
  6237. bool adjusted = this->GenerateAdjustBaseSlots(instrInsert, baseOpnd, initialType, finalType);
  6238. if (!adjusted)
  6239. {
  6240. baseOpnd->Free(m_func);
  6241. }
  6242. }
  6243. bool
  6244. Lowerer::GenerateAdjustBaseSlots(IR::Instr *instrInsert, IR::RegOpnd *baseOpnd, Js::Type* initialType, Js::Type* finalType)
  6245. {
  6246. // Possibly allocate new slot capacity to accommodate a type transition.
  6247. Js::DynamicType *oldType = static_cast<Js::DynamicType*>(initialType);
  6248. Assert(oldType);
  6249. Js::DynamicType *newType = static_cast<Js::DynamicType*>(finalType);
  6250. Assert(newType);
  6251. AssertMsg(Js::DynamicObject::IsTypeHandlerCompatibleForObjectHeaderInlining(oldType->GetTypeHandler(), newType->GetTypeHandler()),
  6252. "Incompatible typeHandler transition?");
  6253. int oldCount = oldType->GetTypeHandler()->GetSlotCapacity();
  6254. int newCount = newType->GetTypeHandler()->GetSlotCapacity();
  6255. Js::PropertyIndex inlineSlotCapacity = oldType->GetTypeHandler()->GetInlineSlotCapacity();
  6256. Js::PropertyIndex newInlineSlotCapacity = newType->GetTypeHandler()->GetInlineSlotCapacity();
  6257. if (oldCount >= newCount || newCount <= inlineSlotCapacity)
  6258. {
  6259. // Already have enough slot capacity. Do nothing.
  6260. return false;
  6261. }
  6262. // Call AdjustSlots using the new counts. Because AdjustSlots uses the "no dispose" flavor of alloc,
  6263. // no implicit calls are possible, and we don't need an implicit call check and bailout.
  6264. // CALL AdjustSlots, instance, newInlineSlotCapacity, newAuxSlotCapacity
  6265. //3rd Param
  6266. Assert(newCount > newInlineSlotCapacity);
  6267. const int newAuxSlotCapacity = newCount - newInlineSlotCapacity;
  6268. m_lowererMD.LoadHelperArgument(instrInsert, IR::IntConstOpnd::New(newAuxSlotCapacity, TyInt32, this->m_func));
  6269. //2nd Param
  6270. m_lowererMD.LoadHelperArgument(instrInsert, IR::IntConstOpnd::New(newInlineSlotCapacity, TyUint16, this->m_func));
  6271. //1st Param (instance)
  6272. m_lowererMD.LoadHelperArgument(instrInsert, baseOpnd);
  6273. //CALL HelperAdjustSlots
  6274. IR::Opnd *opnd = IR::HelperCallOpnd::New(IR::HelperAdjustSlots, this->m_func);
  6275. IR::Instr *instr = IR::Instr::New(Js::OpCode::Call, this->m_func);
  6276. instr->SetSrc1(opnd);
  6277. instrInsert->InsertBefore(instr);
  6278. m_lowererMD.LowerCall(instr, 0);
  6279. return true;
  6280. }
  6281. void
  6282. Lowerer::GenerateFieldStoreWithTypeChange(IR::Instr * instrStFld, IR::PropertySymOpnd *propertySymOpnd, Js::Type* initialType, Js::Type* finalType)
  6283. {
  6284. // Adjust instance slots, if necessary.
  6285. this->GenerateAdjustSlots(instrStFld, propertySymOpnd, initialType, finalType);
  6286. // We should never add properties to objects of static types.
  6287. Assert(Js::DynamicType::Is(finalType->GetTypeId()));
  6288. // Let's pin the final type to be sure its alive when we try to do the type transition.
  6289. PinTypeRef(finalType, finalType, instrStFld, propertySymOpnd->m_sym->AsPropertySym()->m_propertyId);
  6290. IR::Opnd *finalTypeOpnd = IR::AddrOpnd::New(finalType, IR::AddrOpndKindDynamicType, instrStFld->m_func, true);
  6291. // Set the new type.
  6292. IR::RegOpnd *baseOpnd = propertySymOpnd->CreatePropertyOwnerOpnd(instrStFld->m_func);
  6293. IR::Opnd *opnd = IR::IndirOpnd::New(baseOpnd, Js::RecyclableObject::GetOffsetOfType(), TyMachReg, instrStFld->m_func);
  6294. this->m_lowererMD.CreateAssign(opnd, finalTypeOpnd, instrStFld);
  6295. // Now do the store.
  6296. GenerateDirectFieldStore(instrStFld, propertySymOpnd);
  6297. }
  6298. bool
  6299. Lowerer::GenerateStFldWithCachedFinalType(IR::Instr * instrStFld, IR::PropertySymOpnd *propertySymOpnd)
  6300. {
  6301. // This function tries to treat a sequence of add-property stores as a single type transition.
  6302. Assert(propertySymOpnd == instrStFld->GetDst()->AsPropertySymOpnd());
  6303. Assert(propertySymOpnd->IsMonoObjTypeSpecCandidate());
  6304. Assert(propertySymOpnd->HasFinalType());
  6305. Assert(propertySymOpnd->HasInitialType());
  6306. IR::Instr *instr;
  6307. IR::LabelInstr *labelBailOut = nullptr;
  6308. AssertMsg(!propertySymOpnd->IsTypeChecked(), "Why are we doing a type transition when we have the type we want?");
  6309. // If the initial type must be checked here, do it.
  6310. Assert(instrStFld->HasBailOutInfo());
  6311. labelBailOut = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  6312. GenerateCachedTypeWithoutPropertyCheck(instrStFld, propertySymOpnd, nullptr/*typeOpnd*/, labelBailOut);
  6313. // Do the type transition.
  6314. GenerateFieldStoreWithTypeChange(instrStFld, propertySymOpnd, propertySymOpnd->GetInitialType(), propertySymOpnd->GetFinalType());
  6315. instrStFld->FreeSrc1();
  6316. instrStFld->FreeDst();
  6317. // Insert the bailout and let the main path branch around it.
  6318. IR::LabelInstr *labelDone = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  6319. instr = IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, labelDone, this->m_func);
  6320. instrStFld->InsertBefore(instr);
  6321. if (instrStFld->HasBailOutInfo())
  6322. {
  6323. Assert(labelBailOut != nullptr);
  6324. instrStFld->InsertBefore(labelBailOut);
  6325. instrStFld->InsertAfter(labelDone);
  6326. instrStFld->m_opcode = Js::OpCode::BailOut;
  6327. this->GenerateBailOut(instrStFld);
  6328. }
  6329. else
  6330. {
  6331. instrStFld->InsertAfter(labelDone);
  6332. instrStFld->Remove();
  6333. }
  6334. return true;
  6335. }
  6336. ///----------------------------------------------------------------------------
  6337. ///
  6338. /// Lowerer::LowerScopedStFld
  6339. ///
  6340. ///----------------------------------------------------------------------------
  6341. IR::Instr *
  6342. Lowerer::LowerScopedStFld(IR::Instr * stFldInstr, IR::JnHelperMethod helperMethod, bool withInlineCache,
  6343. bool withPropertyOperationFlags, Js::PropertyOperationFlags flags)
  6344. {
  6345. IR::Instr *instrPrev = stFldInstr->m_prev;
  6346. if (withPropertyOperationFlags)
  6347. {
  6348. m_lowererMD.LoadHelperArgument(stFldInstr,
  6349. IR::IntConstOpnd::New(static_cast<IntConstType>(flags), IRType::TyInt32, m_func, true));
  6350. }
  6351. if(!withInlineCache)
  6352. {
  6353. LoadScriptContext(stFldInstr);
  6354. }
  6355. // Pass the default instance
  6356. IR::Opnd *src = stFldInstr->UnlinkSrc2();
  6357. m_lowererMD.LoadHelperArgument(stFldInstr, src);
  6358. // Pass the value to store
  6359. src = stFldInstr->UnlinkSrc1();
  6360. m_lowererMD.LoadHelperArgument(stFldInstr, src);
  6361. // Pass the property sym to store to
  6362. IR::Opnd *dst = stFldInstr->UnlinkDst();
  6363. AssertMsg(dst->IsSymOpnd() && dst->AsSymOpnd()->m_sym->IsPropertySym(), "Expected property sym as dst of field store");
  6364. this->LoadPropertySymAsArgument(stFldInstr, dst);
  6365. if (withInlineCache)
  6366. {
  6367. AssertMsg(dst->AsSymOpnd()->IsPropertySymOpnd(), "Need property sym operand to find the inline cache");
  6368. m_lowererMD.LoadHelperArgument(
  6369. stFldInstr,
  6370. IR::Opnd::CreateInlineCacheIndexOpnd(dst->AsPropertySymOpnd()->m_inlineCacheIndex, m_func));
  6371. // Not using the polymorphic inline cache because the fast path only uses the monomorphic inline cache
  6372. this->m_lowererMD.LoadHelperArgument(stFldInstr, this->LoadRuntimeInlineCacheOpnd(stFldInstr, dst->AsPropertySymOpnd()));
  6373. m_lowererMD.LoadHelperArgument(stFldInstr, LoadFunctionBodyOpnd(stFldInstr));
  6374. }
  6375. m_lowererMD.ChangeToHelperCall(stFldInstr, helperMethod);
  6376. return instrPrev;
  6377. }
  6378. ///----------------------------------------------------------------------------
  6379. ///
  6380. /// Lowerer::LowerLoadVar
  6381. ///
  6382. ///----------------------------------------------------------------------------
  6383. IR::Instr *
  6384. Lowerer::LowerLoadVar(IR::Instr *instr, IR::Opnd *opnd)
  6385. {
  6386. instr->SetSrc1(opnd);
  6387. return m_lowererMD.ChangeToAssign(instr);
  6388. }
  6389. IR::Instr *
  6390. Lowerer::LoadHelperTemp(IR::Instr * instr, IR::Instr * instrInsert)
  6391. {
  6392. IR::Opnd *tempOpnd;
  6393. IR::Opnd *dst = instr->GetDst();
  6394. AssertMsg(dst != nullptr, "Always expect a dst for these.");
  6395. AssertMsg(instr->dstIsTempNumber, "Should only be loading temps here");
  6396. Assert(dst->IsRegOpnd());
  6397. StackSym * tempNumberSym = this->GetTempNumberSym(dst, instr->dstIsTempNumberTransferred);
  6398. IR::Instr *load = this->m_lowererMD.LoadStackAddress(tempNumberSym);
  6399. instrInsert->InsertBefore(load);
  6400. tempOpnd = load->GetDst();
  6401. m_lowererMD.LoadHelperArgument(instrInsert, tempOpnd);
  6402. return load;
  6403. }
  6404. void
  6405. Lowerer::LoadArgumentCount(IR::Instr *const instr)
  6406. {
  6407. Assert(instr);
  6408. Assert(instr->GetDst());
  6409. Assert(!instr->GetSrc1());
  6410. Assert(!instr->GetSrc2());
  6411. if(instr->m_func->IsInlinee())
  6412. {
  6413. // Argument count including 'this'
  6414. instr->SetSrc1(IR::IntConstOpnd::New(instr->m_func->actualCount, TyUint32, instr->m_func, true));
  6415. LowererMD::ChangeToAssign(instr);
  6416. }
  6417. else if (instr->m_func->GetJnFunction()->IsGenerator())
  6418. {
  6419. IR::SymOpnd* symOpnd = LoadCallInfo(instr);
  6420. instr->SetSrc1(symOpnd);
  6421. LowererMD::ChangeToAssign(instr);
  6422. }
  6423. else
  6424. {
  6425. m_lowererMD.LoadArgumentCount(instr);
  6426. }
  6427. }
  6428. void
  6429. Lowerer::LoadStackArgPtr(IR::Instr *const instr)
  6430. {
  6431. Assert(instr);
  6432. Assert(instr->GetDst());
  6433. Assert(!instr->GetSrc1());
  6434. Assert(!instr->GetSrc2());
  6435. if(instr->m_func->IsInlinee())
  6436. {
  6437. // Address of argument after 'this'
  6438. const auto firstRealArgStackSym = instr->m_func->GetInlineeArgvSlotOpnd()->m_sym->AsStackSym();
  6439. this->m_func->SetArgOffset(firstRealArgStackSym, firstRealArgStackSym->m_offset + MachPtr);
  6440. instr->SetSrc1(IR::SymOpnd::New(firstRealArgStackSym, TyMachPtr, instr->m_func));
  6441. LowererMD::ChangeToLea(instr);
  6442. }
  6443. else
  6444. {
  6445. m_lowererMD.LoadStackArgPtr(instr);
  6446. }
  6447. }
  6448. void
  6449. Lowerer::LoadArgumentsFromFrame(IR::Instr *const instr)
  6450. {
  6451. Assert(instr);
  6452. Assert(instr->GetDst());
  6453. Assert(!instr->GetSrc1());
  6454. Assert(!instr->GetSrc2());
  6455. if(instr->m_func->IsInlinee())
  6456. {
  6457. // Use the inline object meta arg slot for the arguments object
  6458. instr->SetSrc1(instr->m_func->GetInlineeArgumentsObjectSlotOpnd());
  6459. LowererMD::ChangeToAssign(instr);
  6460. }
  6461. else
  6462. {
  6463. m_lowererMD.LoadArgumentsFromFrame(instr);
  6464. }
  6465. }
  6466. IR::Instr *
  6467. Lowerer::LowerUnaryHelper(IR::Instr *instr, IR::JnHelperMethod helperMethod)
  6468. {
  6469. IR::Instr *instrPrev;
  6470. IR::Opnd *src1 = instr->UnlinkSrc1();
  6471. instrPrev = m_lowererMD.LoadHelperArgument(instr, src1);
  6472. m_lowererMD.ChangeToHelperCall(instr, helperMethod);
  6473. return instrPrev;
  6474. }
  6475. // helper takes memory context as second argument
  6476. IR::Instr *
  6477. Lowerer::LowerUnaryHelperMem(IR::Instr *instr, IR::JnHelperMethod helperMethod)
  6478. {
  6479. IR::Instr *instrPrev;
  6480. instrPrev = LoadScriptContext(instr);
  6481. return this->LowerUnaryHelper(instr, helperMethod);
  6482. }
  6483. IR::Instr *
  6484. Lowerer::LowerUnaryHelperMemWithFuncBody(IR::Instr *instr, IR::JnHelperMethod helperMethod)
  6485. {
  6486. m_lowererMD.LoadHelperArgument(instr, this->LoadFunctionBodyOpnd(instr));
  6487. return this->LowerUnaryHelperMem(instr, helperMethod);
  6488. }
  6489. IR::Instr *
  6490. Lowerer::LowerBinaryHelperMemWithFuncBody(IR::Instr *instr, IR::JnHelperMethod helperMethod)
  6491. {
  6492. AssertMsg(Js::OpCodeUtil::GetOpCodeLayout(instr->m_opcode) == Js::OpLayoutType::Reg1Int2, "Expected a binary instruction...");
  6493. m_lowererMD.LoadHelperArgument(instr, this->LoadFunctionBodyOpnd(instr));
  6494. return this->LowerBinaryHelperMem(instr, helperMethod);
  6495. }
  6496. IR::Instr *
  6497. Lowerer::LowerUnaryHelperMemWithTemp(IR::Instr *instr, IR::JnHelperMethod helperMethod)
  6498. {
  6499. AssertMsg(Js::OpCodeUtil::GetOpCodeLayout(instr->m_opcode) == Js::OpLayoutType::Reg2, "Expected a unary instruction...");
  6500. IR::Instr * instrFirst;
  6501. IR::Opnd * tempOpnd;
  6502. if (instr->dstIsTempNumber)
  6503. {
  6504. instrFirst = this->LoadHelperTemp(instr, instr);
  6505. }
  6506. else
  6507. {
  6508. tempOpnd = IR::IntConstOpnd::New(0, TyInt32, this->m_func);
  6509. instrFirst = m_lowererMD.LoadHelperArgument(instr, tempOpnd);
  6510. }
  6511. this->LowerUnaryHelperMem(instr, helperMethod);
  6512. return instrFirst;
  6513. }
  6514. IR::Instr *
  6515. Lowerer::LowerUnaryHelperMemWithTemp2(IR::Instr *instr, IR::JnHelperMethod helperMethod, IR::JnHelperMethod helperMethodWithTemp)
  6516. {
  6517. AssertMsg(Js::OpCodeUtil::GetOpCodeLayout(instr->m_opcode) == Js::OpLayoutType::Reg2, "Expected a unary instruction...");
  6518. if (instr->dstIsTempNumber)
  6519. {
  6520. IR::Instr * instrFirst = this->LoadHelperTemp(instr, instr);
  6521. this->LowerUnaryHelperMem(instr, helperMethodWithTemp);
  6522. return instrFirst;
  6523. }
  6524. return this->LowerUnaryHelperMem(instr, helperMethod);
  6525. }
  6526. ///----------------------------------------------------------------------------
  6527. ///
  6528. /// Lowerer::LowerBinaryHelper
  6529. ///
  6530. ///----------------------------------------------------------------------------
  6531. IR::Instr *
  6532. Lowerer::LowerBinaryHelper(IR::Instr *instr, IR::JnHelperMethod helperMethod)
  6533. {
  6534. // The only case where this would still be null when we return is when
  6535. // helperMethod == HelperOP_CmSrEq_EmptyString; in which case we ignore
  6536. // instrPrev.
  6537. IR::Instr *instrPrev = nullptr;
  6538. AssertMsg((Js::OpCodeUtil::GetOpCodeLayout(instr->m_opcode) == Js::OpLayoutType::Reg1Unsigned1 && !instr->GetDst()) ||
  6539. Js::OpCodeUtil::GetOpCodeLayout(instr->m_opcode) == Js::OpLayoutType::Reg3 ||
  6540. Js::OpCodeUtil::GetOpCodeLayout(instr->m_opcode) == Js::OpLayoutType::Reg2Int1 ||
  6541. Js::OpCodeUtil::GetOpCodeLayout(instr->m_opcode) == Js::OpLayoutType::Reg1Int2 ||
  6542. Js::OpCodeUtil::GetOpCodeLayout(instr->m_opcode) == Js::OpLayoutType::ElementU ||
  6543. instr->m_opcode == Js::OpCode::InvalCachedScope, "Expected a binary instruction...");
  6544. IR::Opnd *src2 = instr->UnlinkSrc2();
  6545. if (helperMethod != IR::HelperOP_CmSrEq_EmptyString)
  6546. instrPrev = m_lowererMD.LoadHelperArgument(instr, src2);
  6547. IR::Opnd *src1 = instr->UnlinkSrc1();
  6548. m_lowererMD.LoadHelperArgument(instr, src1);
  6549. m_lowererMD.ChangeToHelperCall(instr, helperMethod);
  6550. return instrPrev;
  6551. }
  6552. // helper takes memory context as third argument
  6553. IR::Instr *
  6554. Lowerer::LowerBinaryHelperMem(IR::Instr *instr, IR::JnHelperMethod helperMethod)
  6555. {
  6556. IR::Instr *instrPrev;
  6557. AssertMsg(Js::OpCodeUtil::GetOpCodeLayout(instr->m_opcode) == Js::OpLayoutType::Reg3 ||
  6558. Js::OpCodeUtil::GetOpCodeLayout(instr->m_opcode) == Js::OpLayoutType::Reg2Int1 ||
  6559. Js::OpCodeUtil::GetOpCodeLayout(instr->m_opcode) == Js::OpLayoutType::Reg1Int2, "Expected a binary instruction...");
  6560. instrPrev = LoadScriptContext(instr);
  6561. return this->LowerBinaryHelper(instr, helperMethod);
  6562. }
  6563. IR::Instr *
  6564. Lowerer::LowerBinaryHelperMemWithTemp(IR::Instr *instr, IR::JnHelperMethod helperMethod)
  6565. {
  6566. AssertMsg(Js::OpCodeUtil::GetOpCodeLayout(instr->m_opcode) == Js::OpLayoutType::Reg3, "Expected a binary instruction...");
  6567. IR::Instr * instrFirst;
  6568. IR::Opnd * tempOpnd;
  6569. if (instr->dstIsTempNumber)
  6570. {
  6571. instrFirst = this->LoadHelperTemp(instr, instr);
  6572. }
  6573. else
  6574. {
  6575. tempOpnd = IR::IntConstOpnd::New(0, TyInt32, this->m_func);
  6576. instrFirst = m_lowererMD.LoadHelperArgument(instr, tempOpnd);
  6577. }
  6578. this->LowerBinaryHelperMem(instr, helperMethod);
  6579. return instrFirst;
  6580. }
  6581. IR::Instr *
  6582. Lowerer::LowerBinaryHelperMemWithTemp2(
  6583. IR::Instr *instr,
  6584. IR::JnHelperMethod helperMethod,
  6585. IR::JnHelperMethod helperMethodWithTemp
  6586. )
  6587. {
  6588. AssertMsg(Js::OpCodeUtil::GetOpCodeLayout(instr->m_opcode) == Js::OpLayoutType::Reg3, "Expected a binary instruction...");
  6589. if (instr->dstIsTempNumber && instr->GetDst() && instr->GetDst()->GetValueType().HasBeenNumber())
  6590. {
  6591. IR::Instr * instrFirst = this->LoadHelperTemp(instr, instr);
  6592. this->LowerBinaryHelperMem(instr, helperMethodWithTemp);
  6593. return instrFirst;
  6594. }
  6595. return this->LowerBinaryHelperMem(instr, helperMethod);
  6596. }
  6597. IR::Instr *
  6598. Lowerer::LowerAddLeftDeadForString(IR::Instr *instr)
  6599. {
  6600. IR::Opnd * opndLeft;
  6601. IR::Opnd * opndRight;
  6602. opndLeft = instr->GetSrc1();
  6603. opndRight = instr->GetSrc2();
  6604. Assert(opndLeft && opndRight);
  6605. bool generateFastPath = this->m_func->DoFastPaths();
  6606. if (!generateFastPath
  6607. || !opndLeft->IsRegOpnd()
  6608. || !opndRight->IsRegOpnd()
  6609. || !instr->GetDst()->IsRegOpnd()
  6610. || !opndLeft->GetValueType().IsLikelyString()
  6611. || !opndRight->GetValueType().IsLikelyString()
  6612. || !opndLeft->IsEqual(instr->GetDst()->AsRegOpnd())
  6613. || opndLeft->IsEqual(opndRight))
  6614. {
  6615. return this->LowerBinaryHelperMemWithTemp(instr, IR::HelperOp_AddLeftDead);
  6616. }
  6617. IR::LabelInstr * labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  6618. IR::LabelInstr * labelFallThrough = instr->GetOrCreateContinueLabel(false);
  6619. IR::LabelInstr *insertBeforeInstr = labelHelper;
  6620. instr->InsertBefore(labelHelper);
  6621. if (!opndLeft->IsNotTaggedValue())
  6622. {
  6623. this->m_lowererMD.GenerateObjectTest(opndLeft->AsRegOpnd(), insertBeforeInstr, labelHelper);
  6624. }
  6625. InsertCompareBranch(
  6626. IR::IndirOpnd::New(opndLeft->AsRegOpnd(), 0, TyMachPtr, m_func),
  6627. this->LoadVTableValueOpnd(insertBeforeInstr, VTableValue::VtableCompoundString),
  6628. Js::OpCode::BrNeq_A,
  6629. labelHelper,
  6630. insertBeforeInstr);
  6631. GenerateStringTest(opndRight->AsRegOpnd(), insertBeforeInstr, labelHelper);
  6632. // left->m_charLength <= JavascriptArray::MaxCharLength
  6633. IR::IndirOpnd *indirLeftCharLengthOpnd = IR::IndirOpnd::New(opndLeft->AsRegOpnd(), Js::JavascriptString::GetOffsetOfcharLength(), TyUint32, m_func);
  6634. IR::RegOpnd *regLeftCharLengthOpnd = IR::RegOpnd::New(TyUint32, m_func);
  6635. InsertMove(regLeftCharLengthOpnd, indirLeftCharLengthOpnd, insertBeforeInstr);
  6636. InsertCompareBranch(
  6637. regLeftCharLengthOpnd,
  6638. IR::IntConstOpnd::New(Js::JavascriptString::MaxCharLength, TyUint32, m_func),
  6639. Js::OpCode::BrGt_A,
  6640. labelHelper,
  6641. insertBeforeInstr);
  6642. // left->m_pszValue == NULL (!left->IsFinalized())
  6643. InsertCompareBranch(
  6644. IR::IndirOpnd::New(opndLeft->AsRegOpnd(), offsetof(Js::JavascriptString, m_pszValue), TyMachPtr, this->m_func),
  6645. IR::AddrOpnd::NewNull(m_func),
  6646. Js::OpCode::BrNeq_A,
  6647. labelHelper,
  6648. insertBeforeInstr);
  6649. // right->m_pszValue != NULL (right->IsFinalized())
  6650. InsertCompareBranch(
  6651. IR::IndirOpnd::New(opndRight->AsRegOpnd(), offsetof(Js::JavascriptString, m_pszValue), TyMachPtr, this->m_func),
  6652. IR::AddrOpnd::NewNull(m_func),
  6653. Js::OpCode::BrEq_A,
  6654. labelHelper,
  6655. insertBeforeInstr);
  6656. // if ownsLastBlock != 0
  6657. InsertCompareBranch(
  6658. IR::IndirOpnd::New(opndLeft->AsRegOpnd(), (int32)Js::CompoundString::GetOffsetOfOwnsLastBlock(), TyUint8, m_func),
  6659. IR::IntConstOpnd::New(0, TyUint8, m_func),
  6660. Js::OpCode::BrEq_A,
  6661. labelHelper,
  6662. insertBeforeInstr);
  6663. // if right->m_charLength == 1
  6664. InsertCompareBranch(IR::IndirOpnd::New(opndRight->AsRegOpnd(), offsetof(Js::JavascriptString, m_charLength), TyUint32, m_func),
  6665. IR::IntConstOpnd::New(1, TyUint32, m_func),
  6666. Js::OpCode::BrNeq_A, labelHelper, insertBeforeInstr);
  6667. // if left->m_directCharLength == -1
  6668. InsertCompareBranch(IR::IndirOpnd::New(opndLeft->AsRegOpnd(), (int32)Js::CompoundString::GetOffsetOfDirectCharLength(), TyUint32, m_func),
  6669. IR::IntConstOpnd::New(UINT32_MAX, TyUint32, m_func),
  6670. Js::OpCode::BrNeq_A, labelHelper, insertBeforeInstr);
  6671. // if lastBlockInfo.charLength < lastBlockInfo.charCapacity
  6672. IR::IndirOpnd *indirCharLength = IR::IndirOpnd::New(opndLeft->AsRegOpnd(), (int32)Js::CompoundString::GetOffsetOfLastBlockInfo()+ (int32)Js::CompoundString::GetOffsetOfLastBlockInfoCharLength(), TyMachPtr, m_func);
  6673. IR::RegOpnd *charLengthOpnd = IR::RegOpnd::New(TyUint32, this->m_func);
  6674. InsertMove(charLengthOpnd, indirCharLength, insertBeforeInstr);
  6675. InsertCompareBranch(charLengthOpnd, IR::IndirOpnd::New(opndLeft->AsRegOpnd(), (int32)Js::CompoundString::GetOffsetOfLastBlockInfo() + (int32)Js::CompoundString::GetOffsetOfLastBlockInfoCharCapacity(), TyMachPtr, m_func), Js::OpCode::BrGe_A, labelHelper, insertBeforeInstr);
  6676. // load c= right->m_pszValue[0]
  6677. IR::RegOpnd *pszValue0Opnd = IR::RegOpnd::New(TyMachPtr, this->m_func);
  6678. IR::IndirOpnd *indirRightPszOpnd = IR::IndirOpnd::New(opndRight->AsRegOpnd(), offsetof(Js::JavascriptString, m_pszValue), TyMachPtr, this->m_func);
  6679. InsertMove(pszValue0Opnd, indirRightPszOpnd, insertBeforeInstr);
  6680. IR::RegOpnd *charResultOpnd = IR::RegOpnd::New(TyUint16, this->m_func);
  6681. InsertMove(charResultOpnd, IR::IndirOpnd::New(pszValue0Opnd, 0, TyUint16, this->m_func), insertBeforeInstr);
  6682. // lastBlockInfo.buffer[blockCharLength] = c;
  6683. IR::RegOpnd *baseOpnd = IR::RegOpnd::New(TyMachPtr, this->m_func);
  6684. InsertMove(baseOpnd, IR::IndirOpnd::New(opndLeft->AsRegOpnd(), (int32)Js::CompoundString::GetOffsetOfLastBlockInfo() + (int32)Js::CompoundString::GetOffsetOfLastBlockInfoBuffer(), TyMachPtr, m_func), insertBeforeInstr);
  6685. IR::IndirOpnd *indirBufferToStore = IR::IndirOpnd::New(baseOpnd, charLengthOpnd, (byte)Math::Log2(sizeof(wchar_t)), TyUint16, m_func);
  6686. InsertMove(indirBufferToStore, charResultOpnd, insertBeforeInstr);
  6687. // left->m_charLength++
  6688. InsertAdd(false, indirLeftCharLengthOpnd, regLeftCharLengthOpnd, IR::IntConstOpnd::New(1, TyUint32, this->m_func), insertBeforeInstr);
  6689. // lastBlockInfo.charLength++
  6690. InsertAdd(false, indirCharLength, indirCharLength, IR::IntConstOpnd::New(1, TyUint32, this->m_func), insertBeforeInstr);
  6691. InsertBranch(Js::OpCode::Br, labelFallThrough, insertBeforeInstr);
  6692. return this->LowerBinaryHelperMemWithTemp(instr, IR::HelperOp_AddLeftDead);
  6693. }
  6694. IR::Instr *
  6695. Lowerer::LowerBinaryHelperMemWithTemp3(IR::Instr *instr, IR::JnHelperMethod helperMethod, IR::JnHelperMethod helperMethodWithTemp, IR::JnHelperMethod helperMethodLeftDead)
  6696. {
  6697. IR::Opnd *src1 = instr->GetSrc1();
  6698. if (src1->IsRegOpnd() && src1->AsRegOpnd()->m_isTempLastUse && !src1->GetValueType().IsNotString())
  6699. {
  6700. Assert(helperMethodLeftDead == IR::HelperOp_AddLeftDead);
  6701. return LowerAddLeftDeadForString(instr);
  6702. }
  6703. else
  6704. {
  6705. return this->LowerBinaryHelperMemWithTemp2(instr, helperMethod, helperMethodWithTemp);
  6706. }
  6707. }
  6708. StackSym *
  6709. Lowerer::GetTempNumberSym(IR::Opnd * opnd, bool isTempTransferred)
  6710. {
  6711. AssertMsg(opnd->IsRegOpnd(), "Expected regOpnd");
  6712. if (isTempTransferred)
  6713. {
  6714. StackSym * tempNumberSym = StackSym::New(TyMisc, m_func);
  6715. this->m_func->StackAllocate(tempNumberSym, sizeof(Js::JavascriptNumber));
  6716. return tempNumberSym;
  6717. }
  6718. StackSym * stackSym = opnd->AsRegOpnd()->m_sym;
  6719. StackSym * tempNumberSym = stackSym->m_tempNumberSym;
  6720. if (tempNumberSym == nullptr)
  6721. {
  6722. tempNumberSym = StackSym::New(TyMisc, m_func);
  6723. this->m_func->StackAllocate(tempNumberSym, sizeof(Js::JavascriptNumber));
  6724. stackSym->m_tempNumberSym = tempNumberSym;
  6725. }
  6726. return tempNumberSym;
  6727. }
  6728. void Lowerer::LowerProfiledLdElemI(IR::JitProfilingInstr *const instr)
  6729. {
  6730. Assert(instr);
  6731. /*
  6732. Var ProfilingHelpers::ProfiledLdElem(
  6733. const Var base,
  6734. const Var varIndex,
  6735. FunctionBody *const functionBody,
  6736. const ProfileId profileId)
  6737. */
  6738. Func *const func = instr->m_func;
  6739. m_lowererMD.LoadHelperArgument(instr, IR::Opnd::CreateProfileIdOpnd(instr->profileId, func));
  6740. m_lowererMD.LoadHelperArgument(instr, CreateFunctionBodyOpnd(func));
  6741. IR::IndirOpnd *const indir = instr->UnlinkSrc1()->AsIndirOpnd();
  6742. IR::Opnd *const indexOpnd = indir->UnlinkIndexOpnd();
  6743. Assert(indexOpnd || indir->GetOffset() >= 0 && !Js::TaggedInt::IsOverflow(indir->GetOffset()));
  6744. m_lowererMD.LoadHelperArgument(
  6745. instr,
  6746. indexOpnd
  6747. ? static_cast<IR::Opnd *>(indexOpnd)
  6748. : IR::AddrOpnd::New(Js::TaggedInt::ToVarUnchecked(indir->GetOffset()), IR::AddrOpndKindDynamicVar, func));
  6749. m_lowererMD.LoadHelperArgument(instr, indir->UnlinkBaseOpnd());
  6750. indir->Free(func);
  6751. instr->SetSrc1(IR::HelperCallOpnd::New(IR::HelperProfiledLdElem, func));
  6752. m_lowererMD.LowerCall(instr, 0);
  6753. }
  6754. void Lowerer::LowerProfiledStElemI(IR::JitProfilingInstr *const instr, const Js::PropertyOperationFlags flags)
  6755. {
  6756. Assert(instr);
  6757. /*
  6758. void ProfilingHelpers::ProfiledStElem(
  6759. const Var base,
  6760. const Var varIndex,
  6761. const Var value,
  6762. FunctionBody *const functionBody,
  6763. const ProfileId profileId,
  6764. const PropertyOperationFlags flags)
  6765. */
  6766. Func *const func = instr->m_func;
  6767. IR::JnHelperMethod helper;
  6768. if(flags == Js::PropertyOperation_None)
  6769. {
  6770. helper = IR::HelperProfiledStElem_DefaultFlags;
  6771. }
  6772. else
  6773. {
  6774. helper = IR::HelperProfiledStElem;
  6775. m_lowererMD.LoadHelperArgument(instr, IR::IntConstOpnd::New(flags, TyInt32, func, true));
  6776. }
  6777. m_lowererMD.LoadHelperArgument(instr, IR::Opnd::CreateProfileIdOpnd(instr->profileId, func));
  6778. m_lowererMD.LoadHelperArgument(instr, CreateFunctionBodyOpnd(func));
  6779. m_lowererMD.LoadHelperArgument(instr, instr->UnlinkSrc1());
  6780. IR::IndirOpnd *const indir = instr->UnlinkDst()->AsIndirOpnd();
  6781. IR::Opnd *const indexOpnd = indir->UnlinkIndexOpnd();
  6782. Assert(indexOpnd || indir->GetOffset() >= 0 && !Js::TaggedInt::IsOverflow(indir->GetOffset()));
  6783. m_lowererMD.LoadHelperArgument(
  6784. instr,
  6785. indexOpnd
  6786. ? static_cast<IR::Opnd *>(indexOpnd)
  6787. : IR::AddrOpnd::New(Js::TaggedInt::ToVarUnchecked(indir->GetOffset()), IR::AddrOpndKindDynamicVar, func));
  6788. m_lowererMD.LoadHelperArgument(instr, indir->UnlinkBaseOpnd());
  6789. indir->Free(func);
  6790. instr->SetSrc1(IR::HelperCallOpnd::New(helper, func));
  6791. m_lowererMD.LowerCall(instr, 0);
  6792. }
  6793. ///----------------------------------------------------------------------------
  6794. ///
  6795. /// Lowerer::LowerStElemI
  6796. ///
  6797. ///----------------------------------------------------------------------------
  6798. IR::Instr *
  6799. Lowerer::LowerStElemI(IR::Instr * instr, Js::PropertyOperationFlags flags, bool isHelper, IR::JnHelperMethod helperMethod)
  6800. {
  6801. IR::Instr *instrPrev = instr->m_prev;
  6802. if (instr->IsJitProfilingInstr())
  6803. {
  6804. Assert(!isHelper);
  6805. LowerProfiledStElemI(instr->AsJitProfilingInstr(), flags);
  6806. return instrPrev;
  6807. }
  6808. IR::Opnd *src1 = instr->GetSrc1();
  6809. IR::Opnd *dst = instr->GetDst();
  6810. IR::Opnd *newDst = nullptr;
  6811. IRType srcType = src1->GetType();
  6812. AssertMsg(dst->IsIndirOpnd(), "Expected indirOpnd on StElementI");
  6813. #if !FLOATVAR
  6814. if (dst->AsIndirOpnd()->GetBaseOpnd()->GetValueType().IsLikelyOptimizedTypedArray() && src1->IsRegOpnd())
  6815. {
  6816. // We allow the source of typedArray StElem to be marked as temp, since we just need the value,
  6817. // however if the array turns out to be a non-typed array, or the index isn't valid (the value is then stored as a property)
  6818. // the temp needs to be boxed if it is a float. The BoxStackNumber helper will box JavascriptNumbers
  6819. // which are on the stack.
  6820. // regVar = BoxStackNumber(src1, scriptContext)
  6821. IR::Instr *newInstr = IR::Instr::New(Js::OpCode::Call, this->m_func);
  6822. IR::RegOpnd *regVar = IR::RegOpnd::New(TyVar, this->m_func);
  6823. newInstr->SetDst(regVar);
  6824. newInstr->SetSrc1(src1);
  6825. instr->InsertBefore(newInstr);
  6826. LowerUnaryHelperMem(newInstr, IR::HelperBoxStackNumber);
  6827. // MOV src1, regVar
  6828. newInstr = IR::Instr::New(Js::OpCode::Ld_A, src1, regVar, this->m_func);
  6829. instr->InsertBefore(m_lowererMD.ChangeToAssign(newInstr));
  6830. }
  6831. #endif
  6832. if(instr->HasBailOutInfo())
  6833. {
  6834. IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  6835. if(bailOutKind & IR::BailOutOnInvalidatedArrayHeadSegment)
  6836. {
  6837. Assert(!(bailOutKind & IR::BailOutOnMissingValue));
  6838. LowerBailOnInvalidatedArrayHeadSegment(instr, isHelper);
  6839. bailOutKind ^= IR::BailOutOnInvalidatedArrayHeadSegment;
  6840. Assert(!bailOutKind || instr->GetBailOutKind() == bailOutKind);
  6841. }
  6842. else if(bailOutKind & IR::BailOutOnMissingValue)
  6843. {
  6844. LowerBailOnCreatedMissingValue(instr, isHelper);
  6845. bailOutKind ^= IR::BailOutOnMissingValue;
  6846. Assert(!bailOutKind || instr->GetBailOutKind() == bailOutKind);
  6847. }
  6848. if(bailOutKind & IR::BailOutOnInvalidatedArrayLength)
  6849. {
  6850. LowerBailOnInvalidatedArrayLength(instr, isHelper);
  6851. bailOutKind ^= IR::BailOutOnInvalidatedArrayLength;
  6852. Assert(!bailOutKind || instr->GetBailOutKind() == bailOutKind);
  6853. }
  6854. if(bailOutKind & IR::BailOutConvertedNativeArray)
  6855. {
  6856. IR::LabelInstr *labelSkipBailOut = IR::LabelInstr::New(Js::OpCode::Label, m_func, isHelper);
  6857. instr->InsertAfter(labelSkipBailOut);
  6858. LowerOneBailOutKind(instr, IR::BailOutConvertedNativeArray, isHelper);
  6859. newDst = IR::RegOpnd::New(TyMachReg, m_func);
  6860. InsertTestBranch(newDst, newDst, Js::OpCode::BrEq_A, labelSkipBailOut, instr->m_next);
  6861. }
  6862. }
  6863. instr->UnlinkDst();
  6864. instr->UnlinkSrc1();
  6865. IR::Opnd *indexOpnd = dst->AsIndirOpnd()->UnlinkIndexOpnd();
  6866. Assert(
  6867. helperMethod == IR::HelperOP_InitElemGetter ||
  6868. helperMethod == IR::HelperOP_InitElemSetter ||
  6869. helperMethod == IR::HelperOP_InitComputedProperty ||
  6870. helperMethod == IR::HelperOp_SetElementI ||
  6871. helperMethod == IR::HelperOp_InitClassMemberComputedName ||
  6872. helperMethod == IR::HelperOp_InitClassMemberGetComputedName ||
  6873. helperMethod == IR::HelperOp_InitClassMemberSetComputedName
  6874. );
  6875. if (indexOpnd && indexOpnd->GetType() != TyVar)
  6876. {
  6877. if (indexOpnd->GetType() == TyInt32)
  6878. {
  6879. helperMethod =
  6880. srcType == TyVar ? IR::HelperOp_SetElementI_Int32 :
  6881. srcType == TyInt32 ? IR::HelperOp_SetNativeIntElementI_Int32 :
  6882. IR::HelperOp_SetNativeFloatElementI_Int32;
  6883. }
  6884. else if (indexOpnd->GetType() == TyUint32)
  6885. {
  6886. helperMethod =
  6887. srcType == TyVar ? IR::HelperOp_SetElementI_UInt32 :
  6888. srcType == TyInt32 ? IR::HelperOp_SetNativeIntElementI_UInt32 :
  6889. IR::HelperOp_SetNativeFloatElementI_UInt32;
  6890. }
  6891. else
  6892. {
  6893. Assert(FALSE);
  6894. }
  6895. }
  6896. else
  6897. {
  6898. if (indexOpnd == nullptr)
  6899. {
  6900. // No index; the offset identifies the element.
  6901. IntConstType offset = (IntConstType)dst->AsIndirOpnd()->GetOffset();
  6902. indexOpnd = IR::AddrOpnd::NewFromNumber(offset, m_func);
  6903. }
  6904. if (srcType != TyVar)
  6905. {
  6906. helperMethod =
  6907. srcType == TyInt32 ? IR::HelperOp_SetNativeIntElementI : IR::HelperOp_SetNativeFloatElementI;
  6908. }
  6909. }
  6910. if (srcType == TyFloat64)
  6911. {
  6912. m_lowererMD.LoadDoubleHelperArgument(instr, src1);
  6913. }
  6914. m_lowererMD.LoadHelperArgument(instr,
  6915. IR::IntConstOpnd::New(static_cast<IntConstType>(flags), IRType::TyInt32, m_func, true));
  6916. LoadScriptContext(instr);
  6917. if (srcType != TyFloat64)
  6918. {
  6919. m_lowererMD.LoadHelperArgument(instr, src1);
  6920. }
  6921. m_lowererMD.LoadHelperArgument(instr, indexOpnd);
  6922. IR::Opnd *baseOpnd = dst->AsIndirOpnd()->UnlinkBaseOpnd();
  6923. m_lowererMD.LoadHelperArgument(instr, baseOpnd);
  6924. dst->Free(this->m_func);
  6925. if (newDst)
  6926. {
  6927. instr->SetDst(newDst);
  6928. }
  6929. m_lowererMD.ChangeToHelperCall(instr, helperMethod, nullptr, nullptr, nullptr, isHelper);
  6930. return instrPrev;
  6931. }
  6932. ///----------------------------------------------------------------------------
  6933. ///
  6934. /// Lowerer::LowerLdElemI
  6935. ///
  6936. ///----------------------------------------------------------------------------
  6937. IR::Instr *
  6938. Lowerer::LowerLdElemI(IR::Instr * instr, IR::JnHelperMethod helperMethod, bool isHelper)
  6939. {
  6940. IR::Instr *instrPrev = instr->m_prev;
  6941. if(instr->IsJitProfilingInstr())
  6942. {
  6943. Assert(helperMethod == IR::HelperOp_GetElementI);
  6944. Assert(!isHelper);
  6945. LowerProfiledLdElemI(instr->AsJitProfilingInstr());
  6946. return instrPrev;
  6947. }
  6948. if (!isHelper && instr->DoStackArgsOpt(this->m_func))
  6949. {
  6950. IR::LabelInstr * labelLdElem = IR::LabelInstr::New(Js::OpCode::Label, instr->m_func);
  6951. // Pass in null for labelFallThru to only generate the LdHeapArgument call
  6952. GenerateFastArgumentsLdElemI(instr, labelLdElem, nullptr);
  6953. instr->InsertBefore(labelLdElem);
  6954. }
  6955. IR::Opnd *src1 = instr->UnlinkSrc1();
  6956. AssertMsg(src1->IsIndirOpnd(), "Expected indirOpnd");
  6957. IR::IndirOpnd *indirOpnd = src1->AsIndirOpnd();
  6958. bool loadScriptContext = true;
  6959. IRType dstType = instr->GetDst()->GetType();
  6960. IR::Opnd *indexOpnd = indirOpnd->UnlinkIndexOpnd();
  6961. if (indexOpnd && indexOpnd->GetType() != TyVar)
  6962. {
  6963. Assert(indexOpnd->GetType() == TyUint32 || indexOpnd->GetType() == TyInt32);
  6964. switch (helperMethod)
  6965. {
  6966. case IR::HelperOp_GetElementI:
  6967. if (indexOpnd->GetType() == TyUint32)
  6968. {
  6969. helperMethod =
  6970. dstType == TyVar ? IR::HelperOp_GetElementI_UInt32 :
  6971. dstType == TyInt32 ? IR::HelperOp_GetNativeIntElementI_UInt32 :
  6972. IR::HelperOp_GetNativeFloatElementI_UInt32;
  6973. }
  6974. else
  6975. {
  6976. helperMethod =
  6977. dstType == TyVar ? IR::HelperOp_GetElementI_Int32 :
  6978. dstType == TyInt32 ? IR::HelperOp_GetNativeIntElementI_Int32 :
  6979. IR::HelperOp_GetNativeFloatElementI_Int32;
  6980. }
  6981. break;
  6982. case IR::HelperOp_GetMethodElement:
  6983. Assert(dstType == TyVar);
  6984. helperMethod = indexOpnd->GetType() == TyUint32?
  6985. IR::HelperOp_GetMethodElement_UInt32 : IR::HelperOp_GetMethodElement_Int32;
  6986. break;
  6987. case IR::HelperOp_TypeofElem:
  6988. Assert(dstType == TyVar);
  6989. helperMethod = indexOpnd->GetType() == TyUint32?
  6990. IR::HelperOp_TypeofElem_UInt32 : IR::HelperOp_TypeofElem_Int32;
  6991. break;
  6992. default:
  6993. Assert(false);
  6994. }
  6995. }
  6996. else
  6997. {
  6998. if (indexOpnd == nullptr)
  6999. {
  7000. // No index; the offset identifies the element.
  7001. IntConstType offset = (IntConstType)src1->AsIndirOpnd()->GetOffset();
  7002. indexOpnd = IR::AddrOpnd::NewFromNumber(offset, m_func);
  7003. }
  7004. if (dstType != TyVar)
  7005. {
  7006. loadScriptContext = false;
  7007. helperMethod =
  7008. dstType == TyInt32 ? IR::HelperOp_GetNativeIntElementI : IR::HelperOp_GetNativeFloatElementI;
  7009. }
  7010. }
  7011. // Jitted loop bodies have volatile information about values created outside the loop, so don't update array creation site
  7012. // profile data from jitted loop bodies
  7013. if(!m_func->IsLoopBody())
  7014. {
  7015. const ValueType baseValueType(indirOpnd->GetBaseOpnd()->GetValueType());
  7016. if( baseValueType.IsLikelyObject() &&
  7017. baseValueType.GetObjectType() == ObjectType::Array &&
  7018. !baseValueType.HasIntElements())
  7019. {
  7020. switch(helperMethod)
  7021. {
  7022. case IR::HelperOp_GetElementI:
  7023. helperMethod =
  7024. baseValueType.HasFloatElements()
  7025. ? IR::HelperOp_GetElementI_ExpectingNativeFloatArray
  7026. : IR::HelperOp_GetElementI_ExpectingVarArray;
  7027. break;
  7028. case IR::HelperOp_GetElementI_UInt32:
  7029. helperMethod =
  7030. baseValueType.HasFloatElements()
  7031. ? IR::HelperOp_GetElementI_UInt32_ExpectingNativeFloatArray
  7032. : IR::HelperOp_GetElementI_UInt32_ExpectingVarArray;
  7033. break;
  7034. case IR::HelperOp_GetElementI_Int32:
  7035. helperMethod =
  7036. baseValueType.HasFloatElements()
  7037. ? IR::HelperOp_GetElementI_Int32_ExpectingNativeFloatArray
  7038. : IR::HelperOp_GetElementI_Int32_ExpectingVarArray;
  7039. break;
  7040. }
  7041. }
  7042. }
  7043. if (loadScriptContext)
  7044. {
  7045. LoadScriptContext(instr);
  7046. }
  7047. m_lowererMD.LoadHelperArgument(instr, indexOpnd);
  7048. IR::Opnd *baseOpnd = indirOpnd->UnlinkBaseOpnd();
  7049. m_lowererMD.LoadHelperArgument(instr, baseOpnd);
  7050. src1->Free(this->m_func);
  7051. m_lowererMD.ChangeToHelperCall(instr, helperMethod, nullptr, nullptr, nullptr, isHelper);
  7052. return instrPrev;
  7053. }
  7054. void Lowerer::LowerLdLen(IR::Instr *const instr, const bool isHelper)
  7055. {
  7056. Assert(instr);
  7057. Assert(instr->m_opcode == Js::OpCode::LdLen_A);
  7058. // LdLen has persisted to this point for the sake of pre-lower opts.
  7059. // Turn it into a LdFld of the "length" property.
  7060. // This is normally a load of the internal "length" of an Array, so it probably doesn't benefit
  7061. // from inline caching.
  7062. // Changing the opcode to LdFld is done in LowerLdFld and needs to remain that way to take into
  7063. // account ProfiledLdLen_A
  7064. IR::RegOpnd * baseOpnd = instr->UnlinkSrc1()->AsRegOpnd();
  7065. PropertySym* fieldSym = PropertySym::FindOrCreate(baseOpnd->m_sym->m_id, Js::PropertyIds::length, (uint32)-1, (uint)-1, PropertyKindData, m_func);
  7066. baseOpnd->Free(this->m_func);
  7067. instr->SetSrc1(IR::SymOpnd::New(fieldSym, TyVar, m_func));
  7068. LowerLdFld(instr, IR::HelperOp_GetProperty, IR::HelperOp_GetProperty, false, nullptr, isHelper);
  7069. }
  7070. IR::Instr *
  7071. Lowerer::LowerLdArrViewElem(IR::Instr * instr)
  7072. {
  7073. Assert(m_func->GetJnFunction()->GetIsAsmjsMode());
  7074. Assert(instr);
  7075. Assert(instr->m_opcode == Js::OpCode::LdInt8ArrViewElem ||
  7076. instr->m_opcode == Js::OpCode::LdUInt8ArrViewElem ||
  7077. instr->m_opcode == Js::OpCode::LdInt16ArrViewElem ||
  7078. instr->m_opcode == Js::OpCode::LdUInt16ArrViewElem ||
  7079. instr->m_opcode == Js::OpCode::LdInt32ArrViewElem ||
  7080. instr->m_opcode == Js::OpCode::LdUInt32ArrViewElem ||
  7081. instr->m_opcode == Js::OpCode::LdFloat32ArrViewElem ||
  7082. instr->m_opcode == Js::OpCode::LdFloat64ArrViewElem);
  7083. IR::Instr * instrPrev = instr->m_prev;
  7084. IR::RegOpnd * indexOpnd = instr->GetSrc1()->AsIndirOpnd()->GetIndexOpnd();
  7085. IR::Opnd * dst = instr->GetDst();
  7086. IR::Opnd * src1 = instr->GetSrc1();
  7087. IR::Opnd * src2 = instr->GetSrc2();
  7088. IR::Instr * done;
  7089. if (indexOpnd || m_func->GetJnFunction()->GetAsmJsFunctionInfo()->AccessNeedsBoundCheck((uint32)src1->AsIndirOpnd()->GetOffset()))
  7090. {
  7091. // CMP indexOpnd, src2(arrSize)
  7092. // JA $helper
  7093. // JMP $load
  7094. // $helper:
  7095. // MOV dst, 0
  7096. // JMP $done
  7097. // $load:
  7098. // MOV dst, src1([arrayBuffer + indexOpnd])
  7099. // $done:
  7100. Assert(!dst->IsFloat32() || src1->IsFloat32());
  7101. Assert(!dst->IsFloat64() || src1->IsFloat64());
  7102. done = m_lowererMD.LowerAsmJsLdElemHelper(instr);
  7103. }
  7104. else
  7105. {
  7106. // any access below 0x10000 is safe
  7107. instr->UnlinkDst();
  7108. instr->UnlinkSrc1();
  7109. if (src2)
  7110. {
  7111. instr->FreeSrc2();
  7112. }
  7113. done = instr;
  7114. }
  7115. InsertMove(dst, src1, done);
  7116. instr->Remove();
  7117. return instrPrev;
  7118. }
  7119. void
  7120. Lowerer::LowerMemset(IR::Instr * instr, IR::RegOpnd * helperRet)
  7121. {
  7122. IR::Opnd * dst = instr->UnlinkDst();
  7123. IR::Opnd * src1 = instr->UnlinkSrc1();
  7124. Assert(dst->IsIndirOpnd());
  7125. IR::Opnd *baseOpnd = dst->AsIndirOpnd()->UnlinkBaseOpnd();
  7126. IR::Opnd *indexOpnd = dst->AsIndirOpnd()->UnlinkIndexOpnd();
  7127. IR::Opnd *sizeOpnd = instr->UnlinkSrc2();
  7128. Assert(baseOpnd);
  7129. Assert(sizeOpnd);
  7130. Assert(indexOpnd);
  7131. IR::JnHelperMethod helperMethod = IR::HelperOp_Memset;
  7132. instr->SetDst(helperRet);
  7133. LoadScriptContext(instr);
  7134. m_lowererMD.LoadHelperArgument(instr, sizeOpnd);
  7135. m_lowererMD.LoadHelperArgument(instr, src1);
  7136. m_lowererMD.LoadHelperArgument(instr, indexOpnd);
  7137. m_lowererMD.LoadHelperArgument(instr, baseOpnd);
  7138. m_lowererMD.ChangeToHelperCall(instr, helperMethod);
  7139. dst->Free(m_func);
  7140. }
  7141. void
  7142. Lowerer::LowerMemcopy(IR::Instr * instr, IR::RegOpnd * helperRet)
  7143. {
  7144. IR::Opnd * dst = instr->UnlinkDst();
  7145. IR::Opnd * src = instr->UnlinkSrc1();
  7146. Assert(dst->IsIndirOpnd());
  7147. Assert(src->IsIndirOpnd());
  7148. IR::Opnd *dstBaseOpnd = dst->AsIndirOpnd()->UnlinkBaseOpnd();
  7149. IR::Opnd *dstIndexOpnd = dst->AsIndirOpnd()->UnlinkIndexOpnd();
  7150. IR::Opnd *srcBaseOpnd = src->AsIndirOpnd()->UnlinkBaseOpnd();
  7151. IR::Opnd *srcIndexOpnd = src->AsIndirOpnd()->UnlinkIndexOpnd();
  7152. IR::Opnd *sizeOpnd = instr->UnlinkSrc2();
  7153. Assert(sizeOpnd);
  7154. Assert(dstBaseOpnd);
  7155. Assert(dstIndexOpnd);
  7156. Assert(srcBaseOpnd);
  7157. Assert(srcIndexOpnd);
  7158. IR::JnHelperMethod helperMethod = IR::HelperOp_Memcopy;
  7159. instr->SetDst(helperRet);
  7160. LoadScriptContext(instr);
  7161. m_lowererMD.LoadHelperArgument(instr, sizeOpnd);
  7162. m_lowererMD.LoadHelperArgument(instr, srcIndexOpnd);
  7163. m_lowererMD.LoadHelperArgument(instr, srcBaseOpnd);
  7164. m_lowererMD.LoadHelperArgument(instr, dstIndexOpnd);
  7165. m_lowererMD.LoadHelperArgument(instr, dstBaseOpnd);
  7166. m_lowererMD.ChangeToHelperCall(instr, helperMethod);
  7167. dst->Free(m_func);
  7168. src->Free(m_func);
  7169. }
  7170. IR::Instr *
  7171. Lowerer::LowerMemOp(IR::Instr * instr)
  7172. {
  7173. Assert(instr->m_opcode == Js::OpCode::Memset || instr->m_opcode == Js::OpCode::Memcopy);
  7174. IR::Instr *instrPrev = instr->m_prev;
  7175. IR::RegOpnd* helperRet = IR::RegOpnd::New(TyInt8, instr->m_func);
  7176. const bool isHelper = false;
  7177. AssertMsg(instr->HasBailOutInfo(), "Expected bailOut on MemOp instruction");
  7178. if (instr->HasBailOutInfo())
  7179. {
  7180. IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  7181. if (bailOutKind & IR::BailOutOnInvalidatedArrayHeadSegment)
  7182. {
  7183. Assert(!(bailOutKind & IR::BailOutOnMissingValue));
  7184. LowerBailOnInvalidatedArrayHeadSegment(instr, isHelper);
  7185. bailOutKind ^= IR::BailOutOnInvalidatedArrayHeadSegment;
  7186. Assert(!bailOutKind || instr->GetBailOutKind() == bailOutKind);
  7187. }
  7188. else if (bailOutKind & IR::BailOutOnMissingValue)
  7189. {
  7190. LowerBailOnCreatedMissingValue(instr, isHelper);
  7191. bailOutKind ^= IR::BailOutOnMissingValue;
  7192. Assert(!bailOutKind || instr->GetBailOutKind() == bailOutKind);
  7193. }
  7194. if (bailOutKind & IR::BailOutOnInvalidatedArrayLength)
  7195. {
  7196. LowerBailOnInvalidatedArrayLength(instr, isHelper);
  7197. bailOutKind ^= IR::BailOutOnInvalidatedArrayLength;
  7198. Assert(!bailOutKind || instr->GetBailOutKind() == bailOutKind);
  7199. }
  7200. AssertMsg(bailOutKind & IR::BailOutOnMemOpError, "Expected BailOutOnMemOpError on MemOp instruction");
  7201. if (bailOutKind & IR::BailOutOnMemOpError)
  7202. {
  7203. // Insert or get continue label
  7204. IR::LabelInstr *const skipBailOutLabel = instr->GetOrCreateContinueLabel(isHelper);
  7205. Func *const func = instr->m_func;
  7206. LowerOneBailOutKind(instr, IR::BailOutOnMemOpError, isHelper);
  7207. IR::Instr *const insertBeforeInstr = instr->m_next;
  7208. // test helperRet, helperRet
  7209. // jz $skipBailOut
  7210. InsertCompareBranch(
  7211. helperRet,
  7212. IR::IntConstOpnd::New(0, TyInt8, func),
  7213. Js::OpCode::BrNeq_A,
  7214. skipBailOutLabel,
  7215. insertBeforeInstr);
  7216. // (Bail out with IR::BailOutOnMemOpError)
  7217. // $skipBailOut:
  7218. bailOutKind ^= IR::BailOutOnMemOpError;
  7219. Assert(!bailOutKind || instr->GetBailOutKind() == bailOutKind);
  7220. }
  7221. instr->ClearBailOutInfo();
  7222. }
  7223. if (instr->m_opcode == Js::OpCode::Memset)
  7224. {
  7225. LowerMemset(instr, helperRet);
  7226. }
  7227. else if (instr->m_opcode == Js::OpCode::Memcopy)
  7228. {
  7229. LowerMemcopy(instr, helperRet);
  7230. }
  7231. return instrPrev;
  7232. }
  7233. IR::Instr *
  7234. Lowerer::LowerStArrViewElem(IR::Instr * instr)
  7235. {
  7236. Assert(m_func->GetJnFunction()->GetIsAsmjsMode());
  7237. Assert(instr);
  7238. Assert(instr->m_opcode == Js::OpCode::StInt8ArrViewElem ||
  7239. instr->m_opcode == Js::OpCode::StUInt8ArrViewElem ||
  7240. instr->m_opcode == Js::OpCode::StInt16ArrViewElem ||
  7241. instr->m_opcode == Js::OpCode::StUInt16ArrViewElem ||
  7242. instr->m_opcode == Js::OpCode::StInt32ArrViewElem ||
  7243. instr->m_opcode == Js::OpCode::StUInt32ArrViewElem ||
  7244. instr->m_opcode == Js::OpCode::StFloat32ArrViewElem ||
  7245. instr->m_opcode == Js::OpCode::StFloat64ArrViewElem);
  7246. IR::Instr * instrPrev = instr->m_prev;
  7247. IR::Opnd * dst = instr->GetDst();
  7248. IR::Opnd * src1 = instr->GetSrc1();
  7249. IR::Opnd * src2 = instr->GetSrc2();
  7250. // type of dst is the type of array
  7251. IR::RegOpnd * indexOpnd = dst->AsIndirOpnd()->GetIndexOpnd();
  7252. Assert(!dst->IsFloat32() || src1->IsFloat32());
  7253. Assert(!dst->IsFloat64() || src1->IsFloat64());
  7254. IR::Instr * done;
  7255. if (indexOpnd || m_func->GetJnFunction()->GetAsmJsFunctionInfo()->AccessNeedsBoundCheck((uint32)dst->AsIndirOpnd()->GetOffset()))
  7256. {
  7257. // CMP indexOpnd, src2(arrSize)
  7258. // JA $helper
  7259. // JMP $store
  7260. // $helper:
  7261. // JMP $done
  7262. // $store:
  7263. // MOV dst([arrayBuffer + indexOpnd]), src1
  7264. // $done:
  7265. done = m_lowererMD.LowerAsmJsStElemHelper(instr);
  7266. }
  7267. else
  7268. {
  7269. // any constant access below 0x10000 is safe, as that is the min heap size
  7270. instr->UnlinkDst();
  7271. instr->UnlinkSrc1();
  7272. done = instr;
  7273. if (src2)
  7274. {
  7275. instr->FreeSrc2();
  7276. }
  7277. }
  7278. InsertMove(dst, src1, done);
  7279. instr->Remove();
  7280. return instrPrev;
  7281. }
  7282. IR::Instr *
  7283. Lowerer::LowerArrayDetachedCheck(IR::Instr * instr)
  7284. {
  7285. // TEST isDetached, isDetached
  7286. // JE Done
  7287. // Helper:
  7288. // CALL Js::Throw::OutOfMemory
  7289. // Done:
  7290. Assert(m_func->GetJnFunction()->GetIsAsmjsMode());
  7291. IR::Instr * instrPrev = instr->m_prev;
  7292. IR::Opnd * isDetachedOpnd = instr->UnlinkSrc1();
  7293. Assert(isDetachedOpnd->IsIndirOpnd() || isDetachedOpnd->IsMemRefOpnd());
  7294. IR::LabelInstr * doneLabel = InsertLabel(false, instr->m_next);
  7295. IR::LabelInstr * helperLabel = InsertLabel(true, instr);
  7296. InsertTestBranch(isDetachedOpnd, isDetachedOpnd, Js::OpCode::BrNotNeq_A, doneLabel, helperLabel);
  7297. m_lowererMD.ChangeToHelperCall(instr, IR::HelperOp_OutOfMemoryError);
  7298. return instrPrev;
  7299. }
  7300. ///----------------------------------------------------------------------------
  7301. ///
  7302. /// Lowerer::LowerDeleteElemI
  7303. ///
  7304. ///----------------------------------------------------------------------------
  7305. IR::Instr *
  7306. Lowerer::LowerDeleteElemI(IR::Instr * instr, bool strictMode)
  7307. {
  7308. IR::Instr *instrPrev;
  7309. IR::Opnd *src1 = instr->UnlinkSrc1();
  7310. AssertMsg(src1->IsIndirOpnd(), "Expected indirOpnd on DeleteElementI");
  7311. Js::PropertyOperationFlags propertyOperationFlag = Js::PropertyOperation_None;
  7312. if (strictMode)
  7313. {
  7314. propertyOperationFlag = Js::PropertyOperation_StrictMode;
  7315. }
  7316. instrPrev = instr->m_prev;
  7317. IR::JnHelperMethod helperMethod = IR::HelperOp_DeleteElementI;
  7318. IR::Opnd *indexOpnd = src1->AsIndirOpnd()->UnlinkIndexOpnd();
  7319. if (indexOpnd)
  7320. {
  7321. if (indexOpnd->GetType() == TyInt32)
  7322. {
  7323. helperMethod = IR::HelperOp_DeleteElementI_Int32;
  7324. }
  7325. else if (indexOpnd->GetType() == TyUint32)
  7326. {
  7327. helperMethod = IR::HelperOp_DeleteElementI_UInt32;
  7328. }
  7329. else
  7330. {
  7331. Assert(indexOpnd->GetType() == TyVar);
  7332. }
  7333. }
  7334. else
  7335. {
  7336. // No index; the offset identifies the element.
  7337. IntConstType offset = (IntConstType)src1->AsIndirOpnd()->GetOffset();
  7338. indexOpnd = IR::AddrOpnd::NewFromNumber(offset, m_func);
  7339. }
  7340. m_lowererMD.LoadHelperArgument(instr, IR::IntConstOpnd::New((IntConstType)propertyOperationFlag, TyInt32, m_func, true));
  7341. LoadScriptContext(instr);
  7342. m_lowererMD.LoadHelperArgument(instr, indexOpnd);
  7343. IR::Opnd *baseOpnd = src1->AsIndirOpnd()->UnlinkBaseOpnd();
  7344. m_lowererMD.LoadHelperArgument(instr, baseOpnd);
  7345. src1->Free(this->m_func);
  7346. m_lowererMD.ChangeToHelperCall(instr, helperMethod);
  7347. return instrPrev;
  7348. }
  7349. ///----------------------------------------------------------------------------
  7350. ///
  7351. /// Lowerer::LowerBrB - lower 1-operand (boolean) conditional branch
  7352. ///
  7353. ///----------------------------------------------------------------------------
  7354. IR::Instr *
  7355. Lowerer::LowerBrBReturn(IR::Instr * instr, IR::JnHelperMethod helperMethod, bool isHelper)
  7356. {
  7357. IR::Instr * instrPrev;
  7358. IR::Instr * instrCall;
  7359. IR::HelperCallOpnd * opndHelper;
  7360. IR::Opnd * opndSrc;
  7361. IR::Opnd * opndDst;
  7362. AssertMsg(instr->GetSrc1() != nullptr && instr->GetSrc2() == nullptr, "Expected 1 src opnds on BrB");
  7363. Assert(instr->m_opcode == Js::OpCode::BrOnEmpty || instr->m_opcode == Js::OpCode::BrOnNotEmpty);
  7364. opndSrc = instr->UnlinkSrc1();
  7365. instrPrev = m_lowererMD.LoadHelperArgument(instr, opndSrc);
  7366. // Generate helper call to convert the unknown operand to boolean
  7367. opndHelper = IR::HelperCallOpnd::New(helperMethod, this->m_func);
  7368. opndDst = instr->UnlinkDst();
  7369. instrCall = IR::Instr::New(Js::OpCode::Call, opndDst, opndHelper, this->m_func);
  7370. instr->InsertBefore(instrCall);
  7371. instrCall = m_lowererMD.LowerCall(instrCall, 0);
  7372. // Branch on the result of the call
  7373. instr->m_opcode = (instr->m_opcode == Js::OpCode::BrOnNotEmpty? Js::OpCode::BrTrue_A : Js::OpCode::BrFalse_A);
  7374. instr->SetSrc1(opndDst);
  7375. IR::Instr *loweredInstr;
  7376. loweredInstr = this->LowerCondBranchCheckBailOut(instr->AsBranchInstr(), instrCall, isHelper);
  7377. #if DBG
  7378. if (isHelper)
  7379. {
  7380. if (!loweredInstr->IsBranchInstr())
  7381. {
  7382. loweredInstr = loweredInstr->GetNextBranchOrLabel();
  7383. }
  7384. if (loweredInstr->IsBranchInstr())
  7385. {
  7386. loweredInstr->AsBranchInstr()->m_isHelperToNonHelperBranch = true;
  7387. }
  7388. }
  7389. #endif
  7390. return instrPrev;
  7391. }
  7392. ///----------------------------------------------------------------------------
  7393. ///
  7394. /// Lowerer::LowerMultiBr
  7395. /// - Lowers the instruction for dictionary look up(string case arms)
  7396. ///
  7397. ///----------------------------------------------------------------------------
  7398. IR::Instr* Lowerer::LowerMultiBr(IR::Instr * instr, IR::JnHelperMethod helperMethod)
  7399. {
  7400. IR::Instr * instrPrev = instr->m_prev;
  7401. IR::Instr * instrCall;
  7402. IR::HelperCallOpnd * opndHelper;
  7403. IR::Opnd * opndSrc;
  7404. IR::Opnd * opndDst;
  7405. StackSym * symDst;
  7406. AssertMsg(instr->GetSrc1() != nullptr && instr->GetSrc2() == nullptr, "Expected 1 src opnd on BrB");
  7407. // Push the args in reverse order.
  7408. // The end and start labels for the function are used to guarantee
  7409. // that the dictionary jump destinations haven't been tampered with, so we
  7410. // will always jump to some location within this function
  7411. IR::LabelOpnd * endFuncOpnd = IR::LabelOpnd::New(m_func->EnsureFuncEndLabel(), m_func);
  7412. m_lowererMD.LoadHelperArgument(instr, endFuncOpnd);
  7413. IR::LabelOpnd * startFuncOpnd = IR::LabelOpnd::New(m_func->EnsureFuncStartLabel(), m_func);
  7414. m_lowererMD.LoadHelperArgument(instr, startFuncOpnd);
  7415. //Load the address of the dictionary pair- Js::StringDictionaryWrapper
  7416. IR::AddrOpnd* nativestringDictionaryOpnd = IR::AddrOpnd::New(instr->AsBranchInstr()->AsMultiBrInstr()->GetBranchDictionary(), IR::AddrOpndKindDynamicMisc, this->m_func);
  7417. m_lowererMD.LoadHelperArgument(instr, nativestringDictionaryOpnd);
  7418. //Load the String passed in the Switch expression for look up - JavascriptString
  7419. opndSrc = instr->UnlinkSrc1();
  7420. m_lowererMD.LoadHelperArgument(instr, opndSrc);
  7421. // Generate helper call for dictionary lookup.
  7422. opndHelper = IR::HelperCallOpnd::New(helperMethod, this->m_func);
  7423. symDst = StackSym::New(TyMachPtr,this->m_func);
  7424. opndDst = IR::RegOpnd::New(symDst, TyMachPtr, this->m_func);
  7425. instrCall = IR::Instr::New(Js::OpCode::Call, opndDst, opndHelper, this->m_func);
  7426. instr->InsertBefore(instrCall);
  7427. instrCall = m_lowererMD.LowerCall(instrCall, 0);
  7428. instr->SetSrc1(instrCall->GetDst());
  7429. m_lowererMD.LowerMultiBranch(instr);
  7430. return instrPrev;
  7431. }
  7432. void
  7433. Lowerer::LowerJumpTableMultiBranch(IR::MultiBranchInstr * multiBrInstr, IR::RegOpnd * indexOpnd)
  7434. {
  7435. Func * func = this->m_func;
  7436. IR::Opnd * opndDst = IR::RegOpnd::New(TyMachPtr, func);
  7437. //Move the native address of the jump table to a register
  7438. IR::LabelInstr * nativeJumpTableLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  7439. nativeJumpTableLabel->m_isDataLabel = true;
  7440. IR::LabelOpnd * nativeJumpTable = IR::LabelOpnd::New(nativeJumpTableLabel, m_func);
  7441. IR::RegOpnd * nativeJumpTableReg = IR::RegOpnd::New(TyMachPtr, func);
  7442. m_lowererMD.CreateAssign(nativeJumpTableReg, nativeJumpTable, multiBrInstr);
  7443. BranchJumpTableWrapper * branchJumpTable = multiBrInstr->GetBranchJumpTable();
  7444. AssertMsg(branchJumpTable->labelInstr == nullptr, "Should not be already assigned");
  7445. branchJumpTable->labelInstr = nativeJumpTableLabel;
  7446. //Indirect addressing @ target location in the jump table.
  7447. //MOV eax, [nativeJumpTableReg + (offset * indirScale)]
  7448. BYTE indirScale = this->m_lowererMD.GetDefaultIndirScale();
  7449. IR::Opnd * opndSrc = IR::IndirOpnd::New(nativeJumpTableReg, indexOpnd, indirScale, TyMachReg, this->m_func);
  7450. IR::Instr * indirInstr = m_lowererMD.CreateAssign(opndDst, opndSrc, multiBrInstr);
  7451. //MultiBr eax
  7452. multiBrInstr->SetSrc1(indirInstr->GetDst());
  7453. //Jump to the address at the target location in the jump table
  7454. m_lowererMD.LowerMultiBranch(multiBrInstr);
  7455. }
  7456. ///----------------------------------------------------------------------------
  7457. ///
  7458. /// Lowerer::LowerMultiBr
  7459. /// - Lowers the instruction for jump table(consecutive integer case arms)
  7460. ///
  7461. ///----------------------------------------------------------------------------
  7462. IR::Instr* Lowerer::LowerMultiBr(IR::Instr * instr)
  7463. {
  7464. IR::Instr * instrPrev = instr->m_prev;
  7465. AssertMsg(instr->GetSrc1() != nullptr && instr->GetSrc2() == nullptr, "Expected 1 src opnd on BrB");
  7466. AssertMsg(instr->IsBranchInstr() && instr->AsBranchInstr()->IsMultiBranch(), "Bad Instruction Lowering Call to LowerMultiBr()");
  7467. IR::MultiBranchInstr * multiBrInstr = instr->AsBranchInstr()->AsMultiBrInstr();
  7468. IR::RegOpnd * offset = instr->UnlinkSrc1()->AsRegOpnd();
  7469. LowerJumpTableMultiBranch(multiBrInstr, offset);
  7470. return instrPrev;
  7471. }
  7472. IR::Instr* Lowerer::LowerBrBMem(IR::Instr * instr, IR::JnHelperMethod helperMethod)
  7473. {
  7474. IR::Instr * instrPrev;
  7475. IR::Instr * instrCall;
  7476. IR::HelperCallOpnd * opndHelper;
  7477. IR::Opnd * opndSrc;
  7478. IR::Opnd * opndDst;
  7479. StackSym * symDst;
  7480. AssertMsg(instr->GetSrc1() != nullptr && instr->GetSrc2() == nullptr, "Expected 1 src opnds on BrB");
  7481. instrPrev = LoadScriptContext(instr);
  7482. opndSrc = instr->UnlinkSrc1();
  7483. m_lowererMD.LoadHelperArgument(instr, opndSrc);
  7484. // Generate helper call to convert the unknown operand to boolean
  7485. opndHelper = IR::HelperCallOpnd::New(helperMethod, this->m_func);
  7486. symDst = StackSym::New(TyVar, this->m_func);
  7487. opndDst = IR::RegOpnd::New(symDst, TyVar, this->m_func);
  7488. instrCall = IR::Instr::New(Js::OpCode::Call, opndDst, opndHelper, this->m_func);
  7489. instr->InsertBefore(instrCall);
  7490. instrCall = m_lowererMD.LowerCall(instrCall, 0);
  7491. // Branch on the result of the call
  7492. instr->SetSrc1(opndDst);
  7493. m_lowererMD.LowerCondBranch(instr);
  7494. return instrPrev;
  7495. }
  7496. IR::Instr* Lowerer::LowerBrOnObject(IR::Instr * instr, IR::JnHelperMethod helperMethod)
  7497. {
  7498. IR::Instr * instrPrev;
  7499. IR::Instr * instrCall;
  7500. IR::HelperCallOpnd * opndHelper;
  7501. IR::Opnd * opndSrc;
  7502. IR::Opnd * opndDst;
  7503. StackSym * symDst;
  7504. AssertMsg(instr->GetSrc1() != nullptr && instr->GetSrc2() == nullptr, "Expected 1 src opnds on BrB");
  7505. opndSrc = instr->UnlinkSrc1();
  7506. instrPrev = m_lowererMD.LoadHelperArgument(instr, opndSrc);
  7507. // Generate helper call to check if the operand's type is object
  7508. opndHelper = IR::HelperCallOpnd::New(helperMethod, this->m_func);
  7509. symDst = StackSym::New(TyVar, this->m_func);
  7510. opndDst = IR::RegOpnd::New(symDst, TyVar, this->m_func);
  7511. instrCall = IR::Instr::New(Js::OpCode::Call, opndDst, opndHelper, this->m_func);
  7512. instr->InsertBefore(instrCall);
  7513. instrCall = m_lowererMD.LowerCall(instrCall, 0);
  7514. // Branch on the result of the call
  7515. instr->SetSrc1(opndDst);
  7516. m_lowererMD.LowerCondBranch(instr);
  7517. return instrPrev;
  7518. }
  7519. IR::Instr * Lowerer::LowerBrOnClassConstructor(IR::Instr * instr, IR::JnHelperMethod helperMethod)
  7520. {
  7521. IR::Instr * instrPrev;
  7522. IR::Instr * instrCall;
  7523. IR::HelperCallOpnd * opndHelper;
  7524. IR::Opnd * opndSrc;
  7525. IR::Opnd * opndDst;
  7526. StackSym * symDst;
  7527. AssertMsg(instr->GetSrc1() != nullptr && instr->GetSrc2() == nullptr, "Expected 1 src opnds on BrB");
  7528. opndSrc = instr->UnlinkSrc1();
  7529. instrPrev = m_lowererMD.LoadHelperArgument(instr, opndSrc);
  7530. // Generate helper call to check if the operand's type is object
  7531. opndHelper = IR::HelperCallOpnd::New(helperMethod, this->m_func);
  7532. symDst = StackSym::New(TyVar, this->m_func);
  7533. opndDst = IR::RegOpnd::New(symDst, TyVar, this->m_func);
  7534. instrCall = IR::Instr::New(Js::OpCode::Call, opndDst, opndHelper, this->m_func);
  7535. instr->InsertBefore(instrCall);
  7536. instrCall = m_lowererMD.LowerCall(instrCall, 0);
  7537. // Branch on the result of the call
  7538. instr->SetSrc1(opndDst);
  7539. m_lowererMD.LowerCondBranch(instr);
  7540. return instrPrev;
  7541. }
  7542. IR::Instr *
  7543. Lowerer::LowerBrCMem(IR::Instr * instr, IR::JnHelperMethod helperMethod, bool noMathFastPath, bool isHelper)
  7544. {
  7545. IR::Instr * instrPrev = instr->m_prev;
  7546. IR::Instr * instrCall;
  7547. IR::HelperCallOpnd * opndHelper;
  7548. IR::Opnd * opndSrc;
  7549. IR::Opnd * opndDst;
  7550. StackSym * symDst;
  7551. bool inverted = false;
  7552. AssertMsg(instr->GetSrc1() != nullptr && instr->GetSrc2() != nullptr, "Expected 2 src opnds on BrC");
  7553. if (!noMathFastPath && !this->GenerateFastCondBranch(instr->AsBranchInstr(), &isHelper))
  7554. {
  7555. return instrPrev;
  7556. }
  7557. // Push the args in reverse order.
  7558. const bool loadScriptContext = !(helperMethod == IR::HelperOp_StrictEqualString || helperMethod == IR::HelperOp_StrictEqualEmptyString);
  7559. const bool loadArg2 = !(helperMethod == IR::HelperOp_StrictEqualEmptyString);
  7560. if (helperMethod == IR::HelperOp_NotEqual)
  7561. {
  7562. // Op_NotEqual() returns !Op_Equal(). It is faster to call Op_Equal() directly.
  7563. helperMethod = IR::HelperOp_Equal;
  7564. instr->AsBranchInstr()->Invert();
  7565. inverted = true;
  7566. }
  7567. else if(helperMethod == IR::HelperOp_NotStrictEqual)
  7568. {
  7569. // Op_NotStrictEqual() returns !Op_StrictEqual(). It is faster to call Op_StrictEqual() directly.
  7570. helperMethod = IR::HelperOp_StrictEqual;
  7571. instr->AsBranchInstr()->Invert();
  7572. inverted = true;
  7573. }
  7574. if (loadScriptContext)
  7575. LoadScriptContext(instr);
  7576. opndSrc = instr->UnlinkSrc2();
  7577. if (loadArg2)
  7578. m_lowererMD.LoadHelperArgument(instr, opndSrc);
  7579. opndSrc = instr->UnlinkSrc1();
  7580. m_lowererMD.LoadHelperArgument(instr, opndSrc);
  7581. // Generate helper call to compare the source operands.
  7582. opndHelper = IR::HelperCallOpnd::New(helperMethod, this->m_func);
  7583. symDst = StackSym::New(TyMachReg, this->m_func);
  7584. opndDst = IR::RegOpnd::New(symDst, TyMachReg, this->m_func);
  7585. instrCall = IR::Instr::New(Js::OpCode::Call, opndDst, opndHelper, this->m_func);
  7586. instr->InsertBefore(instrCall);
  7587. instrCall = m_lowererMD.LowerCall(instrCall, 0);
  7588. switch (instr->m_opcode)
  7589. {
  7590. case Js::OpCode::BrNotEq_A:
  7591. case Js::OpCode::BrNotNeq_A:
  7592. case Js::OpCode::BrSrNotEq_A:
  7593. case Js::OpCode::BrSrNotNeq_A:
  7594. if (instr->HasBailOutInfo())
  7595. {
  7596. instr->GetBailOutInfo()->isInvertedBranch = true;
  7597. }
  7598. break;
  7599. case Js::OpCode::BrNotGe_A:
  7600. case Js::OpCode::BrNotGt_A:
  7601. case Js::OpCode::BrNotLe_A:
  7602. case Js::OpCode::BrNotLt_A:
  7603. inverted = true;
  7604. break;
  7605. }
  7606. // Branch if the result is "true".
  7607. instr->SetSrc1(opndDst);
  7608. instr->m_opcode = (inverted ? Js::OpCode::BrFalse_A : Js::OpCode::BrTrue_A);
  7609. this->LowerCondBranchCheckBailOut(instr->AsBranchInstr(), instrCall, !noMathFastPath && isHelper);
  7610. return instrPrev;
  7611. }
  7612. IR::Instr *
  7613. Lowerer::LowerBrFncApply(IR::Instr * instr, IR::JnHelperMethod helperMethod) {
  7614. IR::Instr * instrPrev = instr->m_prev;
  7615. IR::Instr * instrCall;
  7616. IR::HelperCallOpnd * opndHelper;
  7617. IR::Opnd * opndSrc;
  7618. IR::Opnd * opndDst;
  7619. StackSym * symDst;
  7620. AssertMsg(instr->GetSrc1() != nullptr, "Expected 1 src opnd on BrFncApply");
  7621. LoadScriptContext(instr);
  7622. opndSrc = instr->UnlinkSrc1();
  7623. m_lowererMD.LoadHelperArgument(instr, opndSrc);
  7624. // Generate helper call to compare the source operands.
  7625. opndHelper = IR::HelperCallOpnd::New(helperMethod, this->m_func);
  7626. symDst = StackSym::New(TyMachReg, this->m_func);
  7627. opndDst = IR::RegOpnd::New(symDst, TyMachReg, this->m_func);
  7628. instrCall = IR::Instr::New(Js::OpCode::Call, opndDst, opndHelper, this->m_func);
  7629. instr->InsertBefore(instrCall);
  7630. instrCall = m_lowererMD.LowerCall(instrCall, 0);
  7631. // Branch if the result is "true".
  7632. instr->SetSrc1(opndDst);
  7633. instr->m_opcode = Js::OpCode::BrTrue_A;
  7634. m_lowererMD.LowerCondBranch(instr);
  7635. return instrPrev;
  7636. }
  7637. ///----------------------------------------------------------------------------
  7638. ///
  7639. /// Lowerer::LowerBrProperty - lower branch-on-has/no-property
  7640. ///
  7641. ///----------------------------------------------------------------------------
  7642. IR::Instr *
  7643. Lowerer::LowerBrProperty(IR::Instr * instr, IR::JnHelperMethod helper)
  7644. {
  7645. IR::Instr * instrPrev;
  7646. IR::Instr * instrCall;
  7647. IR::HelperCallOpnd * opndHelper;
  7648. IR::Opnd * opndSrc;
  7649. IR::Opnd * opndDst;
  7650. opndSrc = instr->UnlinkSrc1();
  7651. AssertMsg(opndSrc->IsSymOpnd() && opndSrc->AsSymOpnd()->m_sym->IsPropertySym(),
  7652. "Expected propertySym as src of BrProperty");
  7653. instrPrev = LoadScriptContext(instr);
  7654. this->LoadPropertySymAsArgument(instr, opndSrc);
  7655. opndHelper = IR::HelperCallOpnd::New(helper, this->m_func);
  7656. opndDst = IR::RegOpnd::New(StackSym::New(TyMachReg, this->m_func), TyMachReg, this->m_func);
  7657. instrCall = IR::Instr::New(Js::OpCode::Call, opndDst, opndHelper, this->m_func);
  7658. instr->InsertBefore(instrCall);
  7659. instrCall = m_lowererMD.LowerCall(instrCall, 0);
  7660. // Branch on the result of the call
  7661. instr->SetSrc1(opndDst);
  7662. switch (instr->m_opcode)
  7663. {
  7664. case Js::OpCode::BrOnHasProperty:
  7665. instr->m_opcode = Js::OpCode::BrTrue_A;
  7666. break;
  7667. case Js::OpCode::BrOnNoProperty:
  7668. instr->m_opcode = Js::OpCode::BrFalse_A;
  7669. break;
  7670. default:
  7671. AssertMsg(0, "Unknown opcode on BrProperty branch");
  7672. break;
  7673. }
  7674. this->LowerCondBranchCheckBailOut(instr->AsBranchInstr(), instrCall, false);
  7675. return instrPrev;
  7676. }
  7677. ///----------------------------------------------------------------------------
  7678. ///
  7679. /// Lowerer::LowerElementUndefined
  7680. ///
  7681. ///----------------------------------------------------------------------------
  7682. IR::Instr *
  7683. Lowerer::LowerElementUndefined(IR::Instr * instr, IR::JnHelperMethod helper)
  7684. {
  7685. IR::Opnd *dst = instr->UnlinkDst();
  7686. AssertMsg(dst->IsSymOpnd() && dst->AsSymOpnd()->m_sym->IsPropertySym(), "Expected fieldSym as dst of Ld Undefined");
  7687. // Pass the property sym to store to
  7688. this->LoadPropertySymAsArgument(instr, dst);
  7689. m_lowererMD.ChangeToHelperCall(instr, helper);
  7690. return instr;
  7691. }
  7692. IR::Instr *
  7693. Lowerer::LowerElementUndefinedMem(IR::Instr * instr, IR::JnHelperMethod helper)
  7694. {
  7695. // Pass script context
  7696. IR::Instr * instrPrev = LoadScriptContext(instr);
  7697. this->LowerElementUndefined(instr, helper);
  7698. return instrPrev;
  7699. }
  7700. IR::Instr *
  7701. Lowerer::LowerLdElemUndef(IR::Instr * instr)
  7702. {
  7703. if (this->m_func->GetJnFunction()->IsEval())
  7704. {
  7705. return LowerElementUndefinedMem(instr, IR::HelperOp_LdElemUndefDynamic);
  7706. }
  7707. else
  7708. {
  7709. return LowerElementUndefined(instr, IR::HelperOp_LdElemUndef);
  7710. }
  7711. }
  7712. ///----------------------------------------------------------------------------
  7713. ///
  7714. /// Lowerer::LowerElementUndefinedScoped
  7715. ///
  7716. ///----------------------------------------------------------------------------
  7717. IR::Instr *
  7718. Lowerer::LowerElementUndefinedScoped(IR::Instr * instr, IR::JnHelperMethod helper)
  7719. {
  7720. IR::Instr * instrPrev = instr->m_prev;
  7721. // Pass the default instance
  7722. IR::Opnd *src = instr->UnlinkSrc1();
  7723. m_lowererMD.LoadHelperArgument(instr, src);
  7724. // Pass the property sym to store to
  7725. IR::Opnd * dst = instr->UnlinkDst();
  7726. AssertMsg(dst->IsSymOpnd() && dst->AsSymOpnd()->m_sym->IsPropertySym(), "Expected fieldSym as dst of Ld Undefined Scoped");
  7727. this->LoadPropertySymAsArgument(instr, dst);
  7728. m_lowererMD.ChangeToHelperCall(instr, helper);
  7729. return instrPrev;
  7730. }
  7731. IR::Instr *
  7732. Lowerer::LowerElementUndefinedScopedMem(IR::Instr * instr, IR::JnHelperMethod helper)
  7733. {
  7734. // Pass script context
  7735. IR::Instr * instrPrev = LoadScriptContext(instr);
  7736. this->LowerElementUndefinedScoped(instr, helper);
  7737. return instrPrev;
  7738. }
  7739. void
  7740. Lowerer::LowerStLoopBodyCount(IR::Instr* instr)
  7741. {
  7742. Js::LoopHeader *header = ((JsLoopBodyCodeGen*)m_func->m_workItem)->loopHeader;
  7743. IR::MemRefOpnd *loopBodyCounterOpnd = IR::MemRefOpnd::New((BYTE*)(header) + header->GetOffsetOfProfiledLoopCounter(), TyUint32, this->m_func);
  7744. instr->SetDst(loopBodyCounterOpnd);
  7745. instr->ReplaceSrc1(instr->GetSrc1()->AsRegOpnd()->UseWithNewType(TyUint32, this->m_func));
  7746. IR::AutoReuseOpnd(loopBodyCounterOpnd, this->m_func);
  7747. m_lowererMD.ChangeToAssign(instr);
  7748. return;
  7749. }
  7750. #if !FLOATVAR
  7751. IR::Instr *
  7752. Lowerer::LowerStSlotBoxTemp(IR::Instr *stSlot)
  7753. {
  7754. // regVar = BoxStackNumber(src, scriptContext)
  7755. IR::RegOpnd * regSrc = stSlot->UnlinkSrc1()->AsRegOpnd();
  7756. IR::Instr * instr = IR::Instr::New(Js::OpCode::Call, this->m_func);
  7757. IR::RegOpnd *regVar = IR::RegOpnd::New(TyVar, this->m_func);
  7758. instr->SetDst(regVar);
  7759. instr->SetSrc1(regSrc);
  7760. stSlot->InsertBefore(instr);
  7761. this->LowerUnaryHelperMem(instr, IR::HelperBoxStackNumber);
  7762. stSlot->SetSrc1(regVar);
  7763. return this->LowerStSlot(stSlot);
  7764. }
  7765. #endif
  7766. IR::Opnd *
  7767. Lowerer::CreateOpndForSlotAccess(IR::Opnd * opnd)
  7768. {
  7769. IR::SymOpnd * symOpnd = opnd->AsSymOpnd();
  7770. PropertySym * dstSym = symOpnd->m_sym->AsPropertySym();
  7771. if (!m_func->IsLoopBody() &&
  7772. m_func->DoStackFrameDisplay() &&
  7773. (dstSym->m_stackSym == m_func->GetLocalClosureSym() || dstSym->m_stackSym == m_func->GetLocalFrameDisplaySym()))
  7774. {
  7775. // Stack closure syms are made to look like slot accesses for the benefit of GlobOpt, so that it can do proper
  7776. // copy prop and implicit call bailout. But what we really want is local stack load/store.
  7777. // Don't do this for loop body, though, since we don't have the value saved on the stack.
  7778. return IR::SymOpnd::New(dstSym->m_stackSym, 0, TyMachReg, this->m_func);
  7779. }
  7780. int32 offset = dstSym->m_propertyId;
  7781. if (!m_func->GetJnFunction()->GetIsAsmJsFunction())
  7782. {
  7783. offset = offset * TySize[opnd->GetType()];
  7784. }
  7785. if (m_func->IsTJLoopBody())
  7786. {
  7787. offset = offset - m_func->GetJnFunction()->GetAsmJsFunctionInfo()->GetTotalSizeinBytes();
  7788. }
  7789. IR::IndirOpnd *indirOpnd = IR::IndirOpnd::New(symOpnd->CreatePropertyOwnerOpnd(m_func),
  7790. offset , opnd->GetType(), this->m_func);
  7791. return indirOpnd;
  7792. }
  7793. IR::Instr *
  7794. Lowerer::LowerStSlot(IR::Instr *instr)
  7795. {
  7796. // StSlot stores the nth Var in the buffer pointed to by the property sym's stack sym.
  7797. IR::Opnd * dstOpnd = instr->UnlinkDst();
  7798. AssertMsg(dstOpnd, "Expected dst opnd on StSlot");
  7799. IR::Opnd * dstNew = this->CreateOpndForSlotAccess(dstOpnd);
  7800. dstOpnd->Free(this->m_func);
  7801. instr->SetDst(dstNew);
  7802. m_lowererMD.ChangeToWriteBarrierAssign(instr);
  7803. return instr;
  7804. }
  7805. IR::Instr *
  7806. Lowerer::LowerStSlotChkUndecl(IR::Instr *instrStSlot)
  7807. {
  7808. Assert(instrStSlot->GetSrc2() != nullptr);
  7809. // Src2 is required only to avoid dead store false positives during GlobOpt.
  7810. instrStSlot->FreeSrc2();
  7811. IR::Opnd *dstOpnd = this->CreateOpndForSlotAccess(instrStSlot->GetDst());
  7812. IR::Instr *instr = this->LowerStSlot(instrStSlot);
  7813. this->GenUndeclChk(instr, dstOpnd);
  7814. return instr;
  7815. }
  7816. void Lowerer::LowerProfileLdSlot(IR::Opnd *const valueOpnd, Func *const ldSlotFunc, const Js::ProfileId profileId, IR::Instr *const insertBeforeInstr)
  7817. {
  7818. Assert(valueOpnd);
  7819. Assert(profileId != Js::Constants::NoProfileId);
  7820. Assert(insertBeforeInstr);
  7821. Func *const irFunc = insertBeforeInstr->m_func;
  7822. m_lowererMD.LoadHelperArgument(insertBeforeInstr, IR::Opnd::CreateProfileIdOpnd(profileId, irFunc));
  7823. m_lowererMD.LoadHelperArgument(insertBeforeInstr, CreateFunctionBodyOpnd(ldSlotFunc));
  7824. m_lowererMD.LoadHelperArgument(insertBeforeInstr, valueOpnd);
  7825. IR::Instr *const callInstr = IR::Instr::New(Js::OpCode::Call, irFunc);
  7826. callInstr->SetSrc1(IR::HelperCallOpnd::New(IR::HelperProfileLdSlot, irFunc));
  7827. insertBeforeInstr->InsertBefore(callInstr);
  7828. m_lowererMD.LowerCall(callInstr, 0);
  7829. }
  7830. IR::Instr *
  7831. Lowerer::LowerLdSlot(IR::Instr *instr)
  7832. {
  7833. IR::Opnd * srcOpnd = instr->UnlinkSrc1();
  7834. AssertMsg(srcOpnd, "Expected src opnd on LdSlot");
  7835. IR::Opnd * srcNew = this->CreateOpndForSlotAccess(srcOpnd);
  7836. srcOpnd->Free(this->m_func);
  7837. instr->SetSrc1(srcNew);
  7838. m_lowererMD.ChangeToAssign(instr);
  7839. return instr;
  7840. }
  7841. IR::Instr *
  7842. Lowerer::LowerChkUndecl(IR::Instr *instr)
  7843. {
  7844. IR::Instr *instrPrev = instr->m_prev;
  7845. this->GenUndeclChk(instr, instr->GetSrc1());
  7846. instr->Remove();
  7847. return instrPrev;
  7848. }
  7849. void
  7850. Lowerer::GenUndeclChk(IR::Instr *instrInsert, IR::Opnd *opnd)
  7851. {
  7852. IR::LabelInstr *labelContinue = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  7853. InsertCompareBranch(
  7854. opnd,
  7855. LoadLibraryValueOpnd(instrInsert, LibraryValue::ValueUndeclBlockVar),
  7856. Js::OpCode::BrNeq_A, labelContinue, instrInsert);
  7857. IR::LabelInstr *labelThrow = IR::LabelInstr::New(Js::OpCode::Label, m_func, true);
  7858. instrInsert->InsertBefore(labelThrow);
  7859. IR::Instr *instr = IR::Instr::New(
  7860. Js::OpCode::RuntimeReferenceError,
  7861. IR::RegOpnd::New(TyMachReg, m_func),
  7862. IR::IntConstOpnd::New(SCODE_CODE(JSERR_UseBeforeDeclaration), TyInt32, m_func),
  7863. m_func);
  7864. instrInsert->InsertBefore(instr);
  7865. this->LowerUnaryHelperMem(instr, IR::HelperOp_RuntimeReferenceError);
  7866. instrInsert->InsertBefore(labelContinue);
  7867. }
  7868. ///----------------------------------------------------------------------------
  7869. ///
  7870. /// Lowerer::LowerStElemC
  7871. ///
  7872. ///----------------------------------------------------------------------------
  7873. IR::Instr *
  7874. Lowerer::LowerStElemC(IR::Instr * stElem)
  7875. {
  7876. IR::Instr *instrPrev = stElem->m_prev;
  7877. IR::IndirOpnd * indirOpnd = stElem->GetDst()->AsIndirOpnd();
  7878. IR::RegOpnd *indexOpnd = indirOpnd->UnlinkIndexOpnd();
  7879. Assert(!indexOpnd || indexOpnd->m_sym->IsIntConst());
  7880. IntConstType value;
  7881. if (indexOpnd)
  7882. {
  7883. value = indexOpnd->AsRegOpnd()->m_sym->GetIntConstValue();
  7884. indexOpnd->Free(this->m_func);
  7885. }
  7886. else
  7887. {
  7888. value = (IntConstType)indirOpnd->GetOffset();
  7889. }
  7890. if (stElem->IsJitProfilingInstr())
  7891. {
  7892. Assert(stElem->AsJitProfilingInstr()->profileId == Js::Constants::NoProfileId);
  7893. m_lowererMD.LoadHelperArgument(stElem, stElem->UnlinkSrc1());
  7894. const auto meth = stElem->m_opcode == Js::OpCode::StElemC ? IR::HelperSimpleStoreArrayHelper : IR::HelperSimpleStoreArraySegHelper;
  7895. stElem->SetSrc1(IR::HelperCallOpnd::New(meth, m_func));
  7896. m_lowererMD.LoadHelperArgument(stElem, IR::IntConstOpnd::New(value, TyUint32, m_func));
  7897. m_lowererMD.LoadHelperArgument(stElem, indirOpnd->UnlinkBaseOpnd());
  7898. stElem->UnlinkDst()->Free(m_func);
  7899. m_lowererMD.LowerCall(stElem, 0);
  7900. return instrPrev;
  7901. }
  7902. IntConstType base;
  7903. IR::RegOpnd *baseOpnd = indirOpnd->GetBaseOpnd();
  7904. const ValueType baseValueType(baseOpnd->GetValueType());
  7905. if(baseValueType.IsLikelyNativeArray())
  7906. {
  7907. Assert(stElem->m_opcode == Js::OpCode::StElemC);
  7908. IR::LabelInstr *labelBailOut = nullptr;
  7909. IR::Instr *instrBailOut = nullptr;
  7910. if (stElem->HasBailOutInfo())
  7911. {
  7912. labelBailOut = IR::LabelInstr::New(Js::OpCode::Label, m_func, true);
  7913. instrBailOut = stElem;
  7914. stElem = IR::Instr::New(instrBailOut->m_opcode, m_func);
  7915. instrBailOut->TransferTo(stElem);
  7916. instrBailOut->InsertBefore(stElem);
  7917. IR::LabelInstr *labelDone = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  7918. InsertBranch(Js::OpCode::Br, labelDone, instrBailOut);
  7919. instrBailOut->InsertBefore(labelBailOut);
  7920. instrBailOut->InsertAfter(labelDone);
  7921. instrBailOut->m_opcode = Js::OpCode::BailOut;
  7922. GenerateBailOut(instrBailOut);
  7923. }
  7924. if (!baseValueType.IsObject())
  7925. {
  7926. // Likely native array: do a vtable check and bail if it fails.
  7927. Assert(labelBailOut);
  7928. GenerateArrayTest(baseOpnd, labelBailOut, labelBailOut, stElem, true);
  7929. }
  7930. if (stElem->GetSrc1()->GetType() == TyVar)
  7931. {
  7932. // Storing a non-specialized value. This may cause array conversion, which invalidates all the code
  7933. // that depends on the array check we've already done.
  7934. // Call a helper that returns the type ID of the resulting array, check it here against the one we
  7935. // expect, and bail if it fails.
  7936. Assert(labelBailOut);
  7937. // Call a helper to (try and) unbox the var and store it.
  7938. // If we had to convert the array to do the store, we'll bail.
  7939. LoadScriptContext(stElem);
  7940. m_lowererMD.LoadHelperArgument(stElem, stElem->UnlinkSrc1());
  7941. IR::Opnd *indexOpnd = IR::IntConstOpnd::New(value, TyUint32, m_func);
  7942. m_lowererMD.LoadHelperArgument(stElem, indexOpnd);
  7943. m_lowererMD.LoadHelperArgument(stElem, indirOpnd->UnlinkBaseOpnd());
  7944. IR::JnHelperMethod helperMethod;
  7945. if (baseValueType.HasIntElements())
  7946. {
  7947. helperMethod = IR::HelperScrArr_SetNativeIntElementC;
  7948. }
  7949. else
  7950. {
  7951. helperMethod = IR::HelperScrArr_SetNativeFloatElementC;
  7952. }
  7953. IR::Instr *instrInsertBranch = stElem->m_next;
  7954. IR::RegOpnd *typeIdOpnd = IR::RegOpnd::New(TyUint32, m_func);
  7955. stElem->ReplaceDst(typeIdOpnd);
  7956. m_lowererMD.ChangeToHelperCall(stElem, helperMethod);
  7957. InsertCompareBranch(
  7958. typeIdOpnd,
  7959. IR::IntConstOpnd::New(
  7960. baseValueType.HasIntElements() ?
  7961. Js::TypeIds_NativeIntArray : Js::TypeIds_NativeFloatArray, TyUint32, m_func),
  7962. Js::OpCode::BrNeq_A,
  7963. labelBailOut,
  7964. instrInsertBranch);
  7965. return instrPrev;
  7966. }
  7967. else if (baseValueType.HasIntElements() && labelBailOut)
  7968. {
  7969. Assert(stElem->GetSrc1()->GetType() == GetArrayIndirType(baseValueType));
  7970. IR::Opnd* missingElementOpnd = GetMissingItemOpnd(stElem->GetSrc1()->GetType(), m_func);
  7971. if (!stElem->GetSrc1()->IsEqual(missingElementOpnd))
  7972. {
  7973. InsertCompareBranch(stElem->GetSrc1(), missingElementOpnd , Js::OpCode::BrEq_A, labelBailOut, stElem, true);
  7974. }
  7975. else
  7976. {
  7977. //Its a missing value store and data flow proves that src1 is always missing value. Array cannot be a int array at the first place
  7978. //if this code was ever hit. Just bailout, this code path would be updated with the profile information next time around.
  7979. InsertBranch(Js::OpCode::Br, labelBailOut, stElem);
  7980. #if DBG
  7981. labelBailOut->m_noHelperAssert = true;
  7982. #endif
  7983. stElem->Remove();
  7984. return instrPrev;
  7985. }
  7986. }
  7987. else
  7988. {
  7989. Assert(stElem->GetSrc1()->GetType() == GetArrayIndirType(baseValueType));
  7990. }
  7991. stElem->GetDst()->SetType(stElem->GetSrc1()->GetType());
  7992. Assert(value <= Js::SparseArraySegmentBase::INLINE_CHUNK_SIZE);
  7993. if(baseValueType.HasIntElements())
  7994. {
  7995. base = sizeof(Js::JavascriptNativeIntArray) + offsetof(Js::SparseArraySegment<int32>, elements);
  7996. }
  7997. else
  7998. {
  7999. base = sizeof(Js::JavascriptNativeFloatArray) + offsetof(Js::SparseArraySegment<double>, elements);
  8000. }
  8001. }
  8002. else if(baseValueType.IsLikelyObject() && baseValueType.GetObjectType() == ObjectType::Array)
  8003. {
  8004. Assert(stElem->m_opcode == Js::OpCode::StElemC);
  8005. Assert(value <= Js::SparseArraySegmentBase::INLINE_CHUNK_SIZE);
  8006. base = sizeof(Js::JavascriptArray) + offsetof(Js::SparseArraySegment<Js::Var>, elements);
  8007. }
  8008. else
  8009. {
  8010. Assert(stElem->m_opcode == Js::OpCode::StElemC || stElem->m_opcode == Js::OpCode::StArrSegElemC);
  8011. Assert(indirOpnd->GetBaseOpnd()->GetType() == TyVar);
  8012. base = offsetof(Js::SparseArraySegment<Js::Var>, elements);
  8013. }
  8014. Assert(value >= 0);
  8015. // MOV [r3 + offset(element) + index], src
  8016. const BYTE indirScale =
  8017. baseValueType.IsLikelyAnyOptimizedArray() ? GetArrayIndirScale(baseValueType) : m_lowererMD.GetDefaultIndirScale();
  8018. IntConstType offset = base + (value << indirScale);
  8019. Assert(Math::FitsInDWord(offset));
  8020. indirOpnd->SetOffset((int32)offset);
  8021. m_lowererMD.ChangeToWriteBarrierAssign(stElem);
  8022. return instrPrev;
  8023. }
  8024. void Lowerer::LowerLdArrHead(IR::Instr *const instr)
  8025. {
  8026. IR::RegOpnd *array = instr->UnlinkSrc1()->AsRegOpnd();
  8027. const ValueType arrayValueType(array->GetValueType());
  8028. Assert(arrayValueType.IsAnyOptimizedArray());
  8029. if(arrayValueType.GetObjectType() == ObjectType::ObjectWithArray)
  8030. {
  8031. array = LoadObjectArray(array, instr);
  8032. }
  8033. // mov arrayHeadSegment, [array + offset(headSegment)]
  8034. instr->GetDst()->SetType(TyMachPtr);
  8035. instr->SetSrc1(
  8036. IR::IndirOpnd::New(
  8037. array,
  8038. GetArrayOffsetOfHeadSegment(arrayValueType),
  8039. TyMachPtr,
  8040. instr->m_func));
  8041. LowererMD::ChangeToAssign(instr);
  8042. }
  8043. // Creates the rest parameter array.
  8044. // Var JavascriptArray::OP_NewScArrayWithElements(
  8045. // uint32 elementCount,
  8046. // Var *elements,
  8047. // ScriptContext* scriptContext)
  8048. IR::Instr *Lowerer::LowerRestParameter(IR::Opnd *formalsOpnd, IR::Opnd *dstOpnd, IR::Opnd *excessOpnd, IR::Instr *instr, IR::RegOpnd *generatorArgsPtrOpnd)
  8049. {
  8050. IR::Instr * helperCallInstr = IR::Instr::New(LowererMD::MDCallOpcode, dstOpnd, instr->m_func);
  8051. instr->InsertAfter(helperCallInstr);
  8052. // Var JavascriptArray::OP_NewScArrayWithElements(
  8053. // int32 elementCount,
  8054. // Var *elements,
  8055. // ScriptContext* scriptContext)
  8056. IR::JnHelperMethod helperMethod = IR::HelperScrArr_OP_NewScArrayWithElements;
  8057. LoadScriptContext(helperCallInstr);
  8058. BOOL isGenerator = this->m_func->GetJnFunction()->IsGenerator();
  8059. // Elements pointer = ebp + (formals count + formals offset + 1)*sizeof(Var)
  8060. IR::RegOpnd *srcOpnd = isGenerator ? generatorArgsPtrOpnd : IR::Opnd::CreateFramePointerOpnd(this->m_func);
  8061. uint16 actualOffset = isGenerator ? 0 : GetFormalParamOffset(); //4
  8062. IR::RegOpnd *argPtrOpnd = IR::RegOpnd::New(TyMachPtr, this->m_func);
  8063. InsertAdd(false, argPtrOpnd, srcOpnd, IR::IntConstOpnd::New((formalsOpnd->AsIntConstOpnd()->GetValue() + actualOffset) * MachPtr, TyUint32, this->m_func), helperCallInstr);
  8064. m_lowererMD.LoadHelperArgument(helperCallInstr, argPtrOpnd);
  8065. m_lowererMD.LoadHelperArgument(helperCallInstr, excessOpnd);
  8066. m_lowererMD.ChangeToHelperCall(helperCallInstr, helperMethod);
  8067. return helperCallInstr;
  8068. }
  8069. ///----------------------------------------------------------------------------
  8070. ///
  8071. /// Lowerer::LowerArgIn
  8072. ///
  8073. /// This function checks the passed-in argument count against the index of this
  8074. /// argument and uses null for a param value if the caller didn't explicitly
  8075. /// pass anything.
  8076. ///
  8077. ///----------------------------------------------------------------------------
  8078. IR::Instr *
  8079. Lowerer::LowerArgIn(IR::Instr *instrArgIn)
  8080. {
  8081. IR::LabelInstr * labelDone;
  8082. IR::LabelInstr * labelUndef;
  8083. IR::LabelInstr * labelNormal;
  8084. IR::LabelInstr * labelInit;
  8085. IR::LabelInstr * labelInitNext;
  8086. IR::BranchInstr * instrBranch;
  8087. IR::Instr * instrArgInNext;
  8088. IR::Instr * instrInsert;
  8089. IR::Instr * instrPrev;
  8090. IR::Instr * instrResume = nullptr;
  8091. IR::Opnd * dstOpnd;
  8092. IR::Opnd * srcOpnd;
  8093. IR::Opnd * opndUndef;
  8094. Js::ArgSlot argIndex;
  8095. StackSym * symParam;
  8096. BOOLEAN isDuplicate;
  8097. IR::RegOpnd * generatorArgsPtrOpnd = nullptr;
  8098. // We start with:
  8099. // s1 = ArgIn_A param1
  8100. // s2 = ArgIn_A param2
  8101. // ...
  8102. // sn = ArgIn_A paramn
  8103. //
  8104. // We want to end up with:
  8105. //
  8106. // s1 = ArgIn_A param1 -- Note that this is unconditional
  8107. // count = (load from param area)
  8108. // BrLt_A $start, count, n -- Forward cbranch to the uncommon case
  8109. // Br $Ln
  8110. // $start:
  8111. // sn = assign undef
  8112. // BrGe_A $Ln-1, count, n-1
  8113. // sn-1 = assign undef
  8114. // ...
  8115. // s2 = assign undef
  8116. // Br $done
  8117. // $Ln:
  8118. // sn = assign paramn
  8119. // $Ln-1:
  8120. // sn-1 = assign paramn-1
  8121. // ...
  8122. // s2 = assign param2
  8123. // $done:
  8124. IR::Opnd *restDst = nullptr;
  8125. bool hasRest = instrArgIn->m_opcode == Js::OpCode::ArgIn_Rest;
  8126. if (hasRest)
  8127. {
  8128. IR::Instr *restInstr = instrArgIn;
  8129. restDst = restInstr->UnlinkDst();
  8130. if (m_func->GetJnFunction()->GetHasImplicitArgIns() && m_func->GetInParamsCount() > 1)
  8131. {
  8132. while (instrArgIn->m_opcode != Js::OpCode::ArgIn_A)
  8133. {
  8134. instrArgIn = instrArgIn->m_prev;
  8135. if (instrResume == nullptr)
  8136. {
  8137. instrResume = instrArgIn;
  8138. }
  8139. }
  8140. restInstr->Remove();
  8141. }
  8142. else
  8143. {
  8144. IR::Instr * instrCount = m_lowererMD.LoadInputParamCount(instrArgIn, -this->m_func->GetInParamsCount());
  8145. IR::Opnd * excessOpnd = instrCount->GetDst();
  8146. IR::LabelInstr *createRestArrayLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  8147. // BrGe $createRestArray, excess, 0
  8148. InsertCompareBranch(excessOpnd, IR::IntConstOpnd::New(0, TyUint8, this->m_func), Js::OpCode::BrGe_A, createRestArrayLabel, instrArgIn);
  8149. // MOV excess, 0
  8150. InsertMove(excessOpnd, IR::IntConstOpnd::New(0, TyUint8, this->m_func), instrArgIn);
  8151. // $createRestArray
  8152. instrArgIn->InsertBefore(createRestArrayLabel);
  8153. if (m_func->GetJnFunction()->IsGenerator())
  8154. {
  8155. generatorArgsPtrOpnd = LoadGeneratorArgsPtr(instrArgIn);
  8156. }
  8157. IR::IntConstOpnd * formalsOpnd = IR::IntConstOpnd::New(this->m_func->GetInParamsCount(), TyUint32, this->m_func);
  8158. IR::Instr *prev = LowerRestParameter(formalsOpnd, restDst, excessOpnd, instrArgIn, generatorArgsPtrOpnd);
  8159. instrArgIn->Remove();
  8160. return prev;
  8161. }
  8162. }
  8163. srcOpnd = instrArgIn->GetSrc1();
  8164. symParam = srcOpnd->AsSymOpnd()->m_sym->AsStackSym();
  8165. argIndex = symParam->GetParamSlotNum();
  8166. if (argIndex == 1)
  8167. {
  8168. // The "this" argument is not source-dependent and doesn't need to be checked.
  8169. if (m_func->GetJnFunction()->IsGenerator())
  8170. {
  8171. generatorArgsPtrOpnd = LoadGeneratorArgsPtr(instrArgIn);
  8172. ConvertArgOpndIfGeneratorFunction(instrArgIn, generatorArgsPtrOpnd);
  8173. }
  8174. m_lowererMD.ChangeToAssign(instrArgIn);
  8175. return instrResume == nullptr ? instrArgIn->m_prev : instrResume;
  8176. }
  8177. Js::ArgSlot formalsCount = this->m_func->GetInParamsCount();
  8178. AssertMsg(argIndex == formalsCount, "Expect to see the ArgIn's in numerical order");
  8179. // Because there may be instructions between the ArgIn's, such as saves to the frame object,
  8180. // we find the top of the sequence of ArgIn's and insert everything there. This assumes that
  8181. // ArgIn's use param symbols as src's and not the results of previous instructions.
  8182. instrPrev = instrArgIn;
  8183. instrInsert = instrArgIn->m_next;
  8184. while (argIndex > 2)
  8185. {
  8186. instrPrev = instrPrev->m_prev;
  8187. if (instrPrev->m_opcode == Js::OpCode::ArgIn_A)
  8188. {
  8189. srcOpnd = instrPrev->GetSrc1();
  8190. symParam = srcOpnd->AsSymOpnd()->m_sym->AsStackSym();
  8191. AssertMsg(symParam->GetParamSlotNum() == argIndex - 1, "ArgIn's not in numerical order");
  8192. argIndex = symParam->GetParamSlotNum();
  8193. }
  8194. else
  8195. {
  8196. // Make sure that this instruction gets lowered.
  8197. if (instrResume == nullptr)
  8198. {
  8199. instrResume = instrPrev;
  8200. }
  8201. }
  8202. }
  8203. // The loading of parameters will be inserted above this instruction.
  8204. instrInsert = instrPrev;
  8205. if (instrResume == nullptr)
  8206. {
  8207. // We found no intervening non-ArgIn's, so lowering can resume at the previous instruction.
  8208. instrResume = instrInsert->m_prev;
  8209. }
  8210. // Now insert all the checks and undef-assigns.
  8211. if (m_func->GetJnFunction()->IsGenerator())
  8212. {
  8213. generatorArgsPtrOpnd = LoadGeneratorArgsPtr(instrInsert);
  8214. }
  8215. // excessOpnd = (load from param area) - formalCounts
  8216. IR::Instr * instrCount = this->m_lowererMD.LoadInputParamCount(instrInsert, -formalsCount, true);
  8217. IR::Opnd * excessOpnd = instrCount->GetDst();
  8218. labelUndef = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, /*helperLabel*/ true);
  8219. Lowerer::InsertBranch(Js::OpCode::BrLt_A, labelUndef, instrInsert);
  8220. // Br $Ln
  8221. labelNormal = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  8222. labelInit = labelNormal;
  8223. instrBranch = IR::BranchInstr::New(Js::OpCode::Br, labelNormal, this->m_func);
  8224. instrInsert->InsertBefore(instrBranch);
  8225. this->m_lowererMD.LowerUncondBranch(instrBranch);
  8226. // Insert the labels
  8227. instrInsert->InsertBefore(labelUndef);
  8228. instrInsert->InsertBefore(labelNormal);
  8229. // MOV undefReg, undefAddress
  8230. IR::Opnd* opndUndefAddress = this->LoadLibraryValueOpnd(labelNormal, LibraryValue::ValueUndefined);
  8231. opndUndef = IR::RegOpnd::New(TyMachPtr, this->m_func);
  8232. LowererMD::CreateAssign(opndUndef, opndUndefAddress, labelNormal);
  8233. BVSparse<JitArenaAllocator> *formalsBv = JitAnew(this->m_func->m_alloc, BVSparse<JitArenaAllocator>, this->m_func->m_alloc);
  8234. while (formalsCount > 2)
  8235. {
  8236. dstOpnd = instrArgIn->GetDst();
  8237. Assert(dstOpnd->IsRegOpnd());
  8238. isDuplicate = formalsBv->TestAndSet(dstOpnd->AsRegOpnd()->m_sym->AsStackSym()->m_id);
  8239. // Now insert the undef initialization before the "normal" label
  8240. // sn = assign undef
  8241. LowererMD::CreateAssign(dstOpnd, opndUndef, labelNormal);
  8242. // INC excessOpnd
  8243. // BrEq_A $Ln-1
  8244. formalsCount--;
  8245. InsertAdd(true, excessOpnd, excessOpnd, IR::IntConstOpnd::New(1, TyInt32, this->m_func), labelNormal);
  8246. labelInitNext = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  8247. InsertBranch(Js::OpCode::BrEq_A, labelInitNext, labelNormal);
  8248. // And insert the "normal" initialization before the "done" label
  8249. // sn = assign paramn
  8250. // $Ln-1:
  8251. labelInit->InsertAfter(labelInitNext);
  8252. labelInit = labelInitNext;
  8253. instrArgInNext = instrArgIn->m_prev;
  8254. instrArgIn->Unlink();
  8255. // function foo(x, x) { use(x); }
  8256. // This should refer to the second 'x'. Since we reverse the order here however, we need to skip
  8257. // the initialization of the first 'x' to not override the one for the second. WOOB:1105504
  8258. if (isDuplicate)
  8259. {
  8260. instrArgIn->Free();
  8261. }
  8262. else
  8263. {
  8264. ConvertArgOpndIfGeneratorFunction(instrArgIn, generatorArgsPtrOpnd);
  8265. labelInit->InsertBefore(instrArgIn);
  8266. this->m_lowererMD.ChangeToAssign(instrArgIn);
  8267. }
  8268. instrArgIn = instrArgInNext;
  8269. while (instrArgIn->m_opcode != Js::OpCode::ArgIn_A)
  8270. {
  8271. instrArgIn = instrArgIn->m_prev;
  8272. AssertMsg(instrArgIn, "???");
  8273. }
  8274. AssertMsg(instrArgIn->GetSrc1()->AsSymOpnd()->m_sym->AsStackSym()->GetParamSlotNum() == formalsCount,
  8275. "Expect all ArgIn's to be in numerical order by param slot");
  8276. }
  8277. // Insert final undef and normal initializations, jumping unconditionally to the end
  8278. // rather than checking against the decremented formals count as we did inside the loop above.
  8279. // s2 = assign undef
  8280. dstOpnd = instrArgIn->GetDst();
  8281. Assert(dstOpnd->IsRegOpnd());
  8282. isDuplicate = formalsBv->TestAndSet(dstOpnd->AsRegOpnd()->m_sym->AsStackSym()->m_id);
  8283. LowererMD::CreateAssign(dstOpnd, opndUndef, labelNormal);
  8284. if (hasRest)
  8285. {
  8286. InsertMove(excessOpnd, IR::IntConstOpnd::New(0, TyUint8, this->m_func), labelNormal);
  8287. }
  8288. // Br $done
  8289. labelDone = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  8290. instrBranch = IR::BranchInstr::New(Js::OpCode::Br, labelDone, this->m_func);
  8291. labelNormal->InsertBefore(instrBranch);
  8292. this->m_lowererMD.LowerUncondBranch(instrBranch);
  8293. // s2 = assign param2
  8294. // $done:
  8295. labelInit->InsertAfter(labelDone);
  8296. if (hasRest)
  8297. {
  8298. // The formals count has been tainted, so restore it before lowering rest
  8299. IR::IntConstOpnd * formalsOpnd = IR::IntConstOpnd::New(this->m_func->GetInParamsCount(), TyUint32, this->m_func);
  8300. LowerRestParameter(formalsOpnd, restDst, excessOpnd, labelDone, generatorArgsPtrOpnd);
  8301. }
  8302. instrArgIn->Unlink();
  8303. if (isDuplicate)
  8304. {
  8305. instrArgIn->Free();
  8306. }
  8307. else
  8308. {
  8309. ConvertArgOpndIfGeneratorFunction(instrArgIn, generatorArgsPtrOpnd);
  8310. labelDone->InsertBefore(instrArgIn);
  8311. this->m_lowererMD.ChangeToAssign(instrArgIn);
  8312. }
  8313. return instrResume;
  8314. }
  8315. void
  8316. Lowerer::ConvertArgOpndIfGeneratorFunction(IR::Instr *instrArgIn, IR::RegOpnd *generatorArgsPtrOpnd)
  8317. {
  8318. if (this->m_func->GetJnFunction()->IsGenerator())
  8319. {
  8320. // Replace stack param operand with offset into arguments array held by
  8321. // the generator object.
  8322. IR::Opnd * srcOpnd = instrArgIn->UnlinkSrc1();
  8323. StackSym * symParam = srcOpnd->AsSymOpnd()->m_sym->AsStackSym();
  8324. Js::ArgSlot argIndex = symParam->GetParamSlotNum();
  8325. IR::IndirOpnd * indirOpnd = IR::IndirOpnd::New(generatorArgsPtrOpnd, (argIndex - 1) * MachPtr, TyMachPtr, this->m_func);
  8326. srcOpnd->Free(this->m_func);
  8327. instrArgIn->SetSrc1(indirOpnd);
  8328. }
  8329. }
  8330. IR::RegOpnd *
  8331. Lowerer::LoadGeneratorArgsPtr(IR::Instr *instrInsert)
  8332. {
  8333. IR::Instr * instr = LoadGeneratorObject(instrInsert);
  8334. IR::RegOpnd * generatorRegOpnd = instr->GetDst()->AsRegOpnd();
  8335. IR::IndirOpnd * indirOpnd = IR::IndirOpnd::New(generatorRegOpnd, Js::JavascriptGenerator::GetArgsPtrOffset(), TyMachPtr, instrInsert->m_func);
  8336. IR::RegOpnd * argsPtrOpnd = IR::RegOpnd::New(TyMachReg, instrInsert->m_func);
  8337. LowererMD::CreateAssign(argsPtrOpnd, indirOpnd, instrInsert);
  8338. return argsPtrOpnd;
  8339. }
  8340. IR::Instr *
  8341. Lowerer::LoadGeneratorObject(IR::Instr * instrInsert)
  8342. {
  8343. StackSym * generatorSym = StackSym::NewParamSlotSym(1, instrInsert->m_func);
  8344. instrInsert->m_func->SetArgOffset(generatorSym, LowererMD::GetFormalParamOffset() * MachPtr);
  8345. IR::SymOpnd * generatorSymOpnd = IR::SymOpnd::New(generatorSym, TyMachPtr, instrInsert->m_func);
  8346. IR::RegOpnd * generatorRegOpnd = IR::RegOpnd::New(TyMachPtr, instrInsert->m_func);
  8347. return LowererMD::CreateAssign(generatorRegOpnd, generatorSymOpnd, instrInsert);
  8348. }
  8349. IR::Instr *
  8350. Lowerer::LowerArgInAsmJs(IR::Instr * instrArgIn)
  8351. {
  8352. Assert(m_func->GetJnFunction()->GetIsAsmjsMode());
  8353. Js::ArgSlot argCount = m_func->GetJnFunction()->GetAsmJsFunctionInfo()->GetArgCount();
  8354. IR::Instr * instr = instrArgIn;
  8355. for (int argNum = argCount - 1; argNum >= 0; --argNum)
  8356. {
  8357. IR::Instr * instrPrev = instr->m_prev;
  8358. m_lowererMD.ChangeToAssign(instr);
  8359. instr = instrPrev;
  8360. }
  8361. return instr;
  8362. }
  8363. bool
  8364. Lowerer::InlineBuiltInLibraryCall(IR::Instr *callInstr)
  8365. {
  8366. IR::Opnd *src1 = callInstr->GetSrc1();
  8367. IR::Opnd *src2 = callInstr->GetSrc2();
  8368. // Get the arg count by looking at the slot number of the last arg symbol.
  8369. if (!src2->IsSymOpnd())
  8370. {
  8371. // No args? Not sure this is possible, but handle it.
  8372. return false;
  8373. }
  8374. StackSym *argLinkSym = src2->AsSymOpnd()->m_sym->AsStackSym();
  8375. // Subtract "this" from the arg count.
  8376. IntConstType argCount = argLinkSym->GetArgSlotNum() - 1;
  8377. // Find the callee's built-in index (if any).
  8378. Js::BuiltinFunction index = Func::GetBuiltInIndex(src1);
  8379. // Warning!
  8380. // Don't add new built-in to following switch. Built-ins needs to be inlined in call direct way.
  8381. // Following is only for prejit scenarios where we don't get inlining always and generate fast path in lowerer.
  8382. // Generating fastpath here misses fixed functions and globopt optimizations.
  8383. switch(index)
  8384. {
  8385. case Js::BuiltinFunction::String_CharAt:
  8386. case Js::BuiltinFunction::String_CharCodeAt:
  8387. if (argCount != 1)
  8388. {
  8389. return false;
  8390. }
  8391. if (!callInstr->GetDst())
  8392. {
  8393. // Optimization of Char[Code]At assumes result is used.
  8394. return false;
  8395. }
  8396. break;
  8397. case Js::BuiltinFunction::Math_Abs:
  8398. #ifdef _M_IX86
  8399. if (!AutoSystemInfo::Data.SSE2Available())
  8400. {
  8401. return false;
  8402. }
  8403. #endif
  8404. if (argCount != 1)
  8405. {
  8406. return false;
  8407. }
  8408. if (!callInstr->GetDst())
  8409. {
  8410. // Optimization of Abs assumes result is used.
  8411. return false;
  8412. }
  8413. break;
  8414. case Js::BuiltinFunction::Array_Push:
  8415. {
  8416. if (argCount != 1)
  8417. {
  8418. return false;
  8419. }
  8420. if (callInstr->GetDst())
  8421. {
  8422. // Optimization of push assumes result is unused.
  8423. return false;
  8424. }
  8425. StackSym *linkSym = callInstr->GetSrc2()->AsSymOpnd()->m_sym->AsStackSym();
  8426. Assert(linkSym->IsSingleDef());
  8427. linkSym = linkSym->m_instrDef->GetSrc2()->AsSymOpnd()->m_sym->AsStackSym();
  8428. Assert(linkSym->IsSingleDef());
  8429. IR::Opnd *const arrayOpnd = linkSym->m_instrDef->GetSrc1();
  8430. if(!arrayOpnd->IsRegOpnd())
  8431. {
  8432. // This should be rare, but needs to be handled.
  8433. // By now, we've already started some of the inlining. Simply jmp to the helper.
  8434. // The branch will get peeped later.
  8435. return false;
  8436. }
  8437. if(!ShouldGenerateArrayFastPath(arrayOpnd, false, false, false) ||
  8438. arrayOpnd->GetValueType().IsLikelyNativeArray())
  8439. {
  8440. // Rejecting native array for now, since we have to do a FromVar at the call site and bail out.
  8441. return false;
  8442. }
  8443. break;
  8444. }
  8445. case Js::BuiltinFunction::String_Replace:
  8446. {
  8447. if(argCount != 2)
  8448. {
  8449. return false;
  8450. }
  8451. if(!ShouldGenerateStringReplaceFastPath(callInstr, argCount))
  8452. {
  8453. return false;
  8454. }
  8455. break;
  8456. }
  8457. default:
  8458. return false;
  8459. }
  8460. Assert(Func::IsBuiltInInlinedInLowerer(callInstr->GetSrc1()));
  8461. IR::Opnd *callTargetOpnd = callInstr->GetSrc1();
  8462. IR::LabelInstr *labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  8463. IR::Opnd *objRefOpnd = IR::MemRefOpnd::New((void*)this->GetObjRefForBuiltInTarget(callTargetOpnd->AsRegOpnd()), TyMachReg, this->m_func);
  8464. InsertCompareBranch(callTargetOpnd, objRefOpnd, Js::OpCode::BrNeq_A, labelHelper, callInstr);
  8465. callInstr->InsertBefore(labelHelper);
  8466. Assert(argCount <= 2);
  8467. IR::Opnd *argsOpnd[3];
  8468. IR::Opnd *linkOpnd = callInstr->GetSrc2();
  8469. while(linkOpnd->IsSymOpnd())
  8470. {
  8471. IR::SymOpnd *src2 = linkOpnd->AsSymOpnd();
  8472. StackSym *sym = src2->m_sym->AsStackSym();
  8473. Assert(sym->m_isSingleDef);
  8474. IR::Instr *argInstr = sym->m_instrDef;
  8475. Assert(argCount >= 0);
  8476. argsOpnd[argCount] = argInstr->GetSrc1();
  8477. argCount--;
  8478. argInstr->Unlink();
  8479. labelHelper->InsertAfter(argInstr);
  8480. linkOpnd = argInstr->GetSrc2();
  8481. }
  8482. AnalysisAssert(argCount == -1);
  8483. // Move startcall
  8484. Assert(linkOpnd->IsRegOpnd());
  8485. StackSym *sym = linkOpnd->AsRegOpnd()->m_sym;
  8486. Assert(sym->m_isSingleDef);
  8487. IR::Instr *startCall = sym->m_instrDef;
  8488. Assert(startCall->m_opcode == Js::OpCode::StartCall);
  8489. startCall->Unlink();
  8490. labelHelper->InsertAfter(startCall);
  8491. // $doneLabel:
  8492. IR::LabelInstr *doneLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  8493. callInstr->InsertAfter(doneLabel);
  8494. bool success = true;
  8495. switch(index)
  8496. {
  8497. case Js::BuiltinFunction::Math_Abs:
  8498. this->m_lowererMD.GenerateFastAbs(callInstr->GetDst(), argsOpnd[1], callInstr, labelHelper, labelHelper, doneLabel);
  8499. break;
  8500. case Js::BuiltinFunction::String_CharCodeAt:
  8501. case Js::BuiltinFunction::String_CharAt:
  8502. success = this->m_lowererMD.GenerateFastCharAt(index, callInstr->GetDst(), argsOpnd[0], argsOpnd[1],
  8503. callInstr, labelHelper, labelHelper, doneLabel);
  8504. break;
  8505. case Js::BuiltinFunction::Array_Push:
  8506. success = GenerateFastPush(argsOpnd[0], argsOpnd[1], callInstr, labelHelper, labelHelper, nullptr, doneLabel);
  8507. break;
  8508. case Js::BuiltinFunction::String_Replace:
  8509. success = GenerateFastReplace(argsOpnd[0], argsOpnd[1], argsOpnd[2], callInstr, labelHelper, labelHelper, doneLabel);
  8510. break;
  8511. default:
  8512. Assert(UNREACHED);
  8513. }
  8514. IR::Instr *instr = IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, doneLabel, this->m_func);
  8515. labelHelper->InsertBefore(instr);
  8516. return success;
  8517. }
  8518. // Perform lowerer part of inlining built-in function.
  8519. // For details, see inline.cpp.
  8520. //
  8521. // Description of changes here (note that taking care of Argouts are similar to InlineeStart):
  8522. // - Move ArgOut_A_InlineBuiltIn next to the call instr -- used by bailout processing in register allocator.
  8523. // - Remove StartCall and InlineBuiltInStart for this call.
  8524. // Before:
  8525. // StartCall fn
  8526. // d1 = BIA s1, link1
  8527. // ...
  8528. // InlineBuiltInStart fn, link0
  8529. // After:
  8530. // ...
  8531. // d1 = BIA s1, NULL
  8532. void Lowerer::LowerInlineBuiltIn(IR::Instr* builtInEndInstr)
  8533. {
  8534. Assert(builtInEndInstr->m_opcode == Js::OpCode::InlineBuiltInEnd || builtInEndInstr->m_opcode == Js::OpCode::InlineNonTrackingBuiltInEnd);
  8535. IR::Instr* startCallInstr;
  8536. builtInEndInstr->IterateArgInstrs([&](IR::Instr* argInstr) {
  8537. startCallInstr = argInstr->GetSrc2()->GetStackSym()->m_instrDef;
  8538. return false;
  8539. });
  8540. // Keep the startCall around as bailout refers to it. Just unlink it for now - do not delete it.
  8541. startCallInstr->Unlink();
  8542. builtInEndInstr->Remove();
  8543. }
  8544. Js::JavascriptFunction **
  8545. Lowerer::GetObjRefForBuiltInTarget(IR::RegOpnd * regOpnd)
  8546. {
  8547. Js::JavascriptFunction ** mathFns =
  8548. this->m_func->GetScriptContext()->GetLibrary()->GetBuiltinFunctions();
  8549. Js::BuiltinFunction index = regOpnd->m_sym->m_builtInIndex;
  8550. AssertMsg(index < Js::BuiltinFunction::Count, "Invalid built-in index on a call target marked as built-in");
  8551. return mathFns + index;
  8552. }
  8553. IR::Instr *
  8554. Lowerer::LowerNewRegEx(IR::Instr * instr)
  8555. {
  8556. IR::Opnd *src1 = instr->UnlinkSrc1();
  8557. Assert(src1->IsAddrOpnd());
  8558. #if ENABLE_REGEX_CONFIG_OPTIONS
  8559. if (REGEX_CONFIG_FLAG(RegexTracing))
  8560. {
  8561. Assert(!instr->GetDst()->CanStoreTemp());
  8562. IR::Instr * instrPrev = LoadScriptContext(instr);
  8563. instrPrev = m_lowererMD.LoadHelperArgument(instr, src1);
  8564. m_lowererMD.ChangeToHelperCall(instr, IR::HelperScrRegEx_OP_NewRegEx);
  8565. return instrPrev;
  8566. }
  8567. #endif
  8568. IR::Instr * instrPrev = instr->m_prev;
  8569. IR::RegOpnd * dstOpnd = instr->UnlinkDst()->AsRegOpnd();
  8570. IR::SymOpnd * tempObjectSymOpnd;
  8571. bool isZeroed = GenerateRecyclerOrMarkTempAlloc(instr, dstOpnd, IR::HelperAllocMemForJavascriptRegExp, sizeof(Js::JavascriptRegExp), &tempObjectSymOpnd);
  8572. if (tempObjectSymOpnd && !PHASE_OFF(Js::HoistMarkTempInitPhase, this->m_func) && this->outerMostLoopLabel)
  8573. {
  8574. // Hoist the vtable and pattern init to the outer most loop top as it never changes
  8575. InsertMove(tempObjectSymOpnd,
  8576. LoadVTableValueOpnd(this->outerMostLoopLabel, VTableValue::VtableJavascriptRegExp),
  8577. this->outerMostLoopLabel, false);
  8578. }
  8579. else
  8580. {
  8581. GenerateMemInit(dstOpnd, 0, LoadVTableValueOpnd(instr, VTableValue::VtableJavascriptRegExp), instr, isZeroed);
  8582. }
  8583. GenerateMemInit(dstOpnd, Js::JavascriptRegExp::GetOffsetOfType(),
  8584. this->LoadLibraryValueOpnd(instr, LibraryValue::ValueRegexType), instr, isZeroed);
  8585. GenerateMemInitNull(dstOpnd, Js::JavascriptRegExp::GetOffsetOfAuxSlots(), instr, isZeroed);
  8586. GenerateMemInitNull(dstOpnd, Js::JavascriptRegExp::GetOffsetOfObjectArray(), instr, isZeroed);
  8587. if (tempObjectSymOpnd && !PHASE_OFF(Js::HoistMarkTempInitPhase, this->m_func) && this->outerMostLoopLabel)
  8588. {
  8589. InsertMove(IR::SymOpnd::New(tempObjectSymOpnd->m_sym,
  8590. tempObjectSymOpnd->m_offset + Js::JavascriptRegExp::GetOffsetOfPattern(), TyMachPtr, this->m_func),
  8591. src1, this->outerMostLoopLabel, false);
  8592. }
  8593. else
  8594. {
  8595. GenerateMemInit(dstOpnd, Js::JavascriptRegExp::GetOffsetOfPattern(), src1, instr, isZeroed);
  8596. }
  8597. GenerateMemInitNull(dstOpnd, Js::JavascriptRegExp::GetOffsetOfSplitPattern(), instr, isZeroed);
  8598. GenerateMemInitNull(dstOpnd, Js::JavascriptRegExp::GetOffsetOfLastIndexVar(), instr, isZeroed);
  8599. GenerateMemInit(dstOpnd, Js::JavascriptRegExp::GetOffsetOfLastIndexOrFlag(), 0, instr, isZeroed);
  8600. instr->Remove();
  8601. return instrPrev;
  8602. }
  8603. IR::Instr *
  8604. Lowerer::GenerateRuntimeError(IR::Instr * insertBeforeInstr, Js::MessageId errorCode, IR::JnHelperMethod helper /*= IR::JnHelperMethod::HelperOp_RuntimeTypeError*/)
  8605. {
  8606. IR::Instr * runtimeErrorInstr = IR::Instr::New(Js::OpCode::RuntimeTypeError, this->m_func);
  8607. runtimeErrorInstr->SetSrc1(IR::IntConstOpnd::New(errorCode, TyInt32, this->m_func, true));
  8608. insertBeforeInstr->InsertBefore(runtimeErrorInstr);
  8609. return this->LowerUnaryHelperMem(runtimeErrorInstr, helper);
  8610. }
  8611. bool Lowerer::IsNullOrUndefRegOpnd(IR::RegOpnd *opnd) const
  8612. {
  8613. StackSym *sym = opnd->m_sym;
  8614. if (!sym->IsConst() || sym->IsIntConst() || sym->IsFloatConst())
  8615. {
  8616. return false;
  8617. }
  8618. Js::Var var = sym->GetConstAddress();
  8619. Js::TypeId typeId = Js::RecyclableObject::FromVar(var)->GetTypeId();
  8620. return typeId == Js::TypeIds_Null || typeId == Js::TypeIds_Undefined;
  8621. }
  8622. bool Lowerer::IsConstRegOpnd(IR::RegOpnd *opnd) const
  8623. {
  8624. StackSym *sym = opnd->m_sym;
  8625. if (!sym->IsConst() || sym->IsIntConst() || sym->IsFloatConst())
  8626. {
  8627. return false;
  8628. }
  8629. Js::Var var = sym->GetConstAddress();
  8630. Js::TypeId typeId = Js::RecyclableObject::FromVar(var)->GetTypeId();
  8631. return typeId == Js::TypeIds_Null || typeId == Js::TypeIds_Undefined || typeId == Js::TypeIds_Boolean;
  8632. }
  8633. bool
  8634. Lowerer::HasSideEffects(IR::Instr *instr)
  8635. {
  8636. if (LowererMD::IsCall(instr))
  8637. {
  8638. #ifdef _M_IX86
  8639. IR::Opnd *src1 = instr->GetSrc1();
  8640. if (src1->IsHelperCallOpnd())
  8641. {
  8642. IR::HelperCallOpnd * helper = src1->AsHelperCallOpnd();
  8643. switch(helper->m_fnHelper)
  8644. {
  8645. case IR::HelperOp_Int32ToAtomInPlace:
  8646. case IR::HelperOp_Int32ToAtom:
  8647. case IR::HelperOp_UInt32ToAtom:
  8648. return false;
  8649. }
  8650. }
  8651. #endif
  8652. return true;
  8653. }
  8654. return instr->HasAnySideEffects();
  8655. }
  8656. IR::Instr*
  8657. Lowerer::GenerateFastInlineBuiltInMathRandom(IR::Instr* instr)
  8658. {
  8659. AssertMsg(instr->GetDst()->IsFloat(), "dst must be float.");
  8660. IR::Instr* retInstr = instr->m_prev;
  8661. IR::Opnd* dst = instr->GetDst();
  8662. IR::Opnd* tmpdst = dst;
  8663. if(!dst->IsRegOpnd())
  8664. {
  8665. tmpdst = IR::RegOpnd::New(dst->GetType(), instr->m_func);
  8666. }
  8667. LoadScriptContext(instr);
  8668. IR::Instr * helperCallInstr = IR::Instr::New(LowererMD::MDCallOpcode, tmpdst, instr->m_func);
  8669. instr->InsertBefore(helperCallInstr);
  8670. m_lowererMD.ChangeToHelperCall(helperCallInstr, IR::JnHelperMethod::HelperDirectMath_Random);
  8671. if(tmpdst != dst)
  8672. {
  8673. InsertMove(dst, tmpdst, instr);
  8674. }
  8675. instr->Remove();
  8676. return retInstr;
  8677. }
  8678. IR::Instr *
  8679. Lowerer::LowerCallDirect(IR::Instr * instr)
  8680. {
  8681. IR::Opnd* linkOpnd = instr->UnlinkSrc2();
  8682. StackSym *linkSym = linkOpnd->AsSymOpnd()->m_sym->AsStackSym();
  8683. IR::Instr* argInstr = linkSym->m_instrDef;
  8684. Assert(argInstr->m_opcode == Js::OpCode::ArgOut_A_InlineSpecialized);
  8685. IR::Opnd* funcObj = argInstr->UnlinkSrc1();
  8686. instr->SetSrc2(argInstr->UnlinkSrc2());
  8687. argInstr->Remove();
  8688. if(instr->HasBailOutInfo())
  8689. {
  8690. IR::Instr * bailOutInstr = this->SplitBailOnImplicitCall(instr, instr->m_next, instr->m_next);
  8691. this->LowerBailOnEqualOrNotEqual(bailOutInstr);
  8692. }
  8693. Js::CallFlags flags = instr->GetDst() ? Js::CallFlags_Value : Js::CallFlags_NotUsed;
  8694. return this->GenerateDirectCall(instr, funcObj, (ushort)flags);
  8695. }
  8696. IR::Instr *
  8697. Lowerer::GenerateDirectCall(IR::Instr* inlineInstr, IR::Opnd* funcObj, ushort callflags)
  8698. {
  8699. int32 argCount = m_lowererMD.LowerCallArgs(inlineInstr, callflags);
  8700. m_lowererMD.LoadHelperArgument(inlineInstr, funcObj);
  8701. m_lowererMD.LowerCall(inlineInstr, (Js::ArgSlot)argCount); //to account for function object and callinfo
  8702. return inlineInstr->m_prev;
  8703. }
  8704. /*
  8705. * GenerateHelperToArrayPushFastPath
  8706. * Generates Helper Call and pushes arguments to the Push HelperCall
  8707. */
  8708. IR::Instr *
  8709. Lowerer::GenerateHelperToArrayPushFastPath(IR::Instr * instr, IR::LabelInstr * bailOutLabelHelper)
  8710. {
  8711. IR::Opnd * arrayHelperOpnd = instr->UnlinkSrc1();
  8712. IR::Opnd * elementHelperOpnd = instr->UnlinkSrc2();
  8713. IR::JnHelperMethod helperMethod;
  8714. if(elementHelperOpnd->IsInt32())
  8715. {
  8716. Assert(arrayHelperOpnd->GetValueType().IsLikelyNativeIntArray());
  8717. helperMethod = IR::HelperArray_NativeIntPush;
  8718. m_lowererMD.LoadHelperArgument(instr, elementHelperOpnd);
  8719. }
  8720. else if(elementHelperOpnd->IsFloat())
  8721. {
  8722. Assert(arrayHelperOpnd->GetValueType().IsLikelyNativeFloatArray());
  8723. helperMethod = IR::HelperArray_NativeFloatPush;
  8724. m_lowererMD.LoadDoubleHelperArgument(instr, elementHelperOpnd);
  8725. }
  8726. else
  8727. {
  8728. helperMethod = IR::HelperArray_VarPush;
  8729. m_lowererMD.LoadHelperArgument(instr, elementHelperOpnd);
  8730. }
  8731. m_lowererMD.LoadHelperArgument(instr, arrayHelperOpnd);
  8732. LoadScriptContext(instr);
  8733. return m_lowererMD.ChangeToHelperCall(instr, helperMethod);
  8734. }
  8735. /*
  8736. * GenerateHelperToArrayPopFastPath
  8737. * Generates Helper Call and pushes arguments to the Pop HelperCall
  8738. */
  8739. IR::Instr *
  8740. Lowerer::GenerateHelperToArrayPopFastPath(IR::Instr * instr, IR::LabelInstr * doneLabel, IR::LabelInstr * bailOutLabelHelper)
  8741. {
  8742. IR::Opnd * arrayHelperOpnd = instr->UnlinkSrc1();
  8743. ValueType arrayValueType = arrayHelperOpnd->GetValueType();
  8744. IR::JnHelperMethod helperMethod;
  8745. //Decide the helperMethod based on dst availability and nativity of the array.
  8746. if(arrayValueType.IsLikelyNativeArray() && !instr->GetDst())
  8747. {
  8748. helperMethod = IR::HelperArray_NativePopWithNoDst;
  8749. }
  8750. else if(arrayValueType.IsLikelyNativeIntArray())
  8751. {
  8752. helperMethod = IR::HelperArray_NativeIntPop;
  8753. }
  8754. else if(arrayValueType.IsLikelyNativeFloatArray())
  8755. {
  8756. helperMethod = IR::HelperArray_NativeFloatPop;
  8757. }
  8758. else
  8759. {
  8760. helperMethod = IR::HelperArray_VarPop;
  8761. }
  8762. m_lowererMD.LoadHelperArgument(instr, arrayHelperOpnd);
  8763. //We do not need scriptContext for HelperArray_NativePopWithNoDst call.
  8764. if(helperMethod != IR::HelperArray_NativePopWithNoDst)
  8765. {
  8766. LoadScriptContext(instr);
  8767. }
  8768. IR::Instr * retInstr = m_lowererMD.ChangeToHelperCall(instr, helperMethod, bailOutLabelHelper);
  8769. //We don't need missing item check for var arrays, as there it is taken care by the helper.
  8770. if(arrayValueType.IsLikelyNativeArray())
  8771. {
  8772. if(retInstr->GetDst())
  8773. {
  8774. //Do this check only for native arrays with Dst. For Var arrays, this is taken care in the Runtime helper itself.
  8775. InsertCompareBranch(GetMissingItemOpnd(retInstr->GetDst()->GetType(), m_func), retInstr->GetDst(), Js::OpCode::BrNeq_A, doneLabel, bailOutLabelHelper);
  8776. }
  8777. else
  8778. {
  8779. //We need unconditional jump to doneLabel, if there is no dst in Pop instr.
  8780. InsertBranch(Js::OpCode::Br, true, doneLabel, bailOutLabelHelper);
  8781. }
  8782. }
  8783. return retInstr;
  8784. }
  8785. IR::Instr *
  8786. Lowerer::LowerCondBranchCheckBailOut(IR::BranchInstr * branchInstr, IR::Instr * helperCall, bool isHelper)
  8787. {
  8788. Assert(branchInstr->m_opcode == Js::OpCode::BrTrue_A || branchInstr->m_opcode == Js::OpCode::BrFalse_A);
  8789. if (branchInstr->HasBailOutInfo())
  8790. {
  8791. IR::BailOutKind debuggerBailOutKind = IR::BailOutInvalid;
  8792. if (branchInstr->HasAuxBailOut())
  8793. {
  8794. // We have shared debugger bailout. For branches we lower it here, not in SplitBailForDebugger.
  8795. // See SplitBailForDebugger for details.
  8796. AssertMsg(!(branchInstr->GetBailOutKind() & IR::BailOutForDebuggerBits), "There should be no debugger bits in main bailout kind.");
  8797. debuggerBailOutKind = branchInstr->GetAuxBailOutKind() & IR::BailOutForDebuggerBits;
  8798. AssertMsg((debuggerBailOutKind & ~(IR::BailOutIgnoreException | IR::BailOutForceByFlag)) == 0, "Only IR::BailOutIgnoreException|ForceByFlag supported here.");
  8799. }
  8800. IR::Instr * bailOutInstr = this->SplitBailOnImplicitCall(branchInstr, helperCall, branchInstr);
  8801. IR::Instr* prevInstr = this->LowerBailOnEqualOrNotEqual(bailOutInstr, branchInstr, nullptr, nullptr, isHelper);
  8802. if (debuggerBailOutKind != IR::BailOutInvalid)
  8803. {
  8804. // Note that by this time implicit calls bailout is already lowered.
  8805. // What we do here is use same bailout info and lower debugger bailout which would be shared bailout.
  8806. BailOutInfo* bailOutInfo = bailOutInstr->GetBailOutInfo();
  8807. IR::BailOutInstr* debuggerBailoutInstr = IR::BailOutInstr::New(
  8808. Js::OpCode::BailForDebugger, debuggerBailOutKind, bailOutInfo, bailOutInfo->bailOutFunc);
  8809. prevInstr->InsertAfter(debuggerBailoutInstr);
  8810. // The result of that is:
  8811. // original helper op_* instr, then debugger bailout, then implicit calls bailout/etc with the branch instr.
  8812. // Example:
  8813. // s35(eax).i32 = CALL Op_GreaterEqual.u32 # -- original op_* helper
  8814. // s34.i32 = MOV s35(eax).i32 #
  8815. // BailForDebugger # Bailout: #0042 (BailOutIgnoreException) -- the debugger bailout
  8816. // CMP [0x0003BDE0].i8, 1 (0x1).i8 # -- implicit calls check
  8817. // JEQ $L10 #
  8818. //$L11: [helper] #
  8819. // CALL SaveAllRegistersAndBranchBailOut.u32 # Bailout: #0042 (BailOutOnImplicitCalls)
  8820. // JMP $L5 #
  8821. //$L10: [helper] #
  8822. // BrFalse_A $L3, s34.i32 #0034 -- The BrTrue/BrFalse branch (branch instr)
  8823. //$L6: [helper] #0042
  8824. this->LowerBailForDebugger(debuggerBailoutInstr, isHelper);
  8825. // After lowering this we will have a check which on bailout condition will JMP to $L11.
  8826. }
  8827. }
  8828. return m_lowererMD.LowerCondBranch(branchInstr);
  8829. }
  8830. IR::Instr *
  8831. Lowerer::LoadArgumentsFromStack(IR::Instr * instr)
  8832. {
  8833. IR::Instr * prevInstr = instr->m_prev;
  8834. Assert(instr->GetDst()->IsRegOpnd());
  8835. if (instr->m_func->IsInlinee())
  8836. {
  8837. instr->ReplaceSrc1(instr->m_func->GetInlineeArgumentsObjectSlotOpnd());
  8838. }
  8839. else
  8840. {
  8841. instr->ReplaceSrc1(this->m_lowererMD.CreateStackArgumentsSlotOpnd());
  8842. }
  8843. this->m_lowererMD.ChangeToAssign(instr);
  8844. return prevInstr;
  8845. }
  8846. IR::SymOpnd *
  8847. Lowerer::LoadCallInfo(IR::Instr * instrInsert)
  8848. {
  8849. IR::SymOpnd * srcOpnd;
  8850. Func * func = instrInsert->m_func;
  8851. if (func->GetJnFunction()->IsGenerator())
  8852. {
  8853. // Generator function arguments and ArgumentsInfo are not on the stack. Instead they
  8854. // are accessed off the generator object (which is prm1).
  8855. StackSym * generatorSym = StackSym::NewParamSlotSym(1, func);
  8856. func->SetArgOffset(generatorSym, LowererMD::GetFormalParamOffset() * MachPtr);
  8857. IR::SymOpnd * generatorSymOpnd = IR::SymOpnd::New(generatorSym, TyMachPtr, func);
  8858. IR::RegOpnd * generatorRegOpnd = IR::RegOpnd::New(TyMachPtr, func);
  8859. LowererMD::CreateAssign(generatorRegOpnd, generatorSymOpnd, instrInsert);
  8860. IR::IndirOpnd * indirOpnd = IR::IndirOpnd::New(generatorRegOpnd, Js::JavascriptGenerator::GetCallInfoOffset(), TyMachPtr, func);
  8861. IR::Instr * instr = LowererMD::CreateAssign(IR::RegOpnd::New(TyMachPtr, func), indirOpnd, instrInsert);
  8862. StackSym * callInfoSym = StackSym::New(TyMachReg, func);
  8863. IR::SymOpnd * callInfoSymOpnd = IR::SymOpnd::New(callInfoSym, TyMachReg, func);
  8864. LowererMD::CreateAssign(callInfoSymOpnd, instr->GetDst(), instrInsert);
  8865. srcOpnd = IR::SymOpnd::New(callInfoSym, TyMachReg, func);
  8866. }
  8867. else
  8868. {
  8869. // Otherwise callInfo is always the "second" argument.
  8870. // The stack looks like this:
  8871. //
  8872. // script param N
  8873. // ...
  8874. // script param 1
  8875. // callinfo
  8876. // function object
  8877. // return addr
  8878. // FP -> FP chain
  8879. StackSym * srcSym = LowererMD::GetImplicitParamSlotSym(1, func);
  8880. srcOpnd = IR::SymOpnd::New(srcSym, TyMachReg, func);
  8881. }
  8882. return srcOpnd;
  8883. }
  8884. IR::Instr *
  8885. Lowerer::LowerBailOnNotStackArgs(IR::Instr * instr)
  8886. {
  8887. if (!this->m_func->GetHasStackArgs())
  8888. {
  8889. throw Js::RejitException(RejitReason::InlineApplyDisabled);
  8890. }
  8891. IR::Instr * prevInstr = instr->m_prev;
  8892. // Bail out test
  8893. // Label to skip Bailout and continue
  8894. IR::LabelInstr * continueLabelInstr;
  8895. IR::Instr *instrNext = instr->m_next;
  8896. if (instrNext->IsLabelInstr())
  8897. {
  8898. continueLabelInstr = instrNext->AsLabelInstr();
  8899. }
  8900. else
  8901. {
  8902. continueLabelInstr = IR::LabelInstr::New(Js::OpCode::Label, m_func, false);
  8903. instr->InsertAfter(continueLabelInstr);
  8904. }
  8905. IR::LabelInstr * helperLabelInstr = IR::LabelInstr::New(Js::OpCode::Label, m_func, true);
  8906. if (!instr->m_func->IsInlinee())
  8907. {
  8908. //BailOut if it is not stack args or the number of actuals (except "this" argument) is greater than or equal to 15.
  8909. IR::Opnd* stackArgs = instr->UnlinkSrc1();
  8910. InsertCompareBranch(stackArgs, instr->UnlinkSrc2(), Js::OpCode::BrNeq_A, helperLabelInstr, instr);
  8911. IR::RegOpnd* ldLenDstOpnd = IR::RegOpnd::New(TyUint32, instr->m_func);
  8912. IR::Instr* ldLen = IR::Instr::New(Js::OpCode::LdLen_A, ldLenDstOpnd, stackArgs, instr->m_func);
  8913. ldLenDstOpnd->SetValueType(ValueType::GetTaggedInt()); //LdLen_A works only on stack arguments
  8914. instr->InsertBefore(ldLen);
  8915. this->GenerateFastRealStackArgumentsLdLen(ldLen);
  8916. this->InsertCompareBranch(ldLenDstOpnd, IR::IntConstOpnd::New(Js::InlineeCallInfo::MaxInlineeArgoutCount, TyUint32, m_func, true), Js::OpCode::BrLt_A, true, continueLabelInstr, instr);
  8917. }
  8918. else
  8919. {
  8920. //For Inlined functions, we are sure actuals can't exceed Js::InlineeCallInfo::MaxInlineeArgoutCount (15).
  8921. InsertCompareBranch(instr->UnlinkSrc1(), instr->UnlinkSrc2(), Js::OpCode::BrEq_A, continueLabelInstr, instr);
  8922. }
  8923. instr->InsertBefore(helperLabelInstr);
  8924. this->GenerateBailOut(instr, nullptr, nullptr);
  8925. return prevInstr;
  8926. }
  8927. IR::Instr *
  8928. Lowerer::LowerBailOnNotSpreadable(IR::Instr *instr)
  8929. {
  8930. // We only avoid bailing out / throwing a rejit exception when the array operand is a simple, non-optimized, non-object array.
  8931. IR::Instr * prevInstr = instr->m_prev;
  8932. Func *func = instr->m_func;
  8933. IR::RegOpnd *arrayOpnd = nullptr;
  8934. IR::Opnd *arraySrcOpnd = instr->UnlinkSrc1();
  8935. if (!arraySrcOpnd->IsRegOpnd())
  8936. {
  8937. arrayOpnd = IR::RegOpnd::New(TyMachPtr, func);
  8938. LowererMD::CreateAssign(arrayOpnd, arraySrcOpnd, instr);
  8939. }
  8940. else
  8941. {
  8942. arrayOpnd = arraySrcOpnd->AsRegOpnd();
  8943. }
  8944. const ValueType baseValueType(arrayOpnd->GetValueType());
  8945. // Check if we can just throw a rejit exception based on valuetype alone instead of bailing out.
  8946. if (!baseValueType.IsLikelyArray()
  8947. || baseValueType.IsLikelyAnyOptimizedArray()
  8948. || (baseValueType.IsLikelyObject() && (baseValueType.GetObjectType() == ObjectType::ObjectWithArray))
  8949. // Validate that GenerateArrayTest will not fail.
  8950. || !(baseValueType.IsUninitialized() || baseValueType.HasBeenObject())
  8951. || m_func->IsInlinee())
  8952. {
  8953. throw Js::RejitException(RejitReason::InlineSpreadDisabled);
  8954. }
  8955. // Past this point, we will need to use a bailout.
  8956. IR::LabelInstr *bailOutLabel = IR::LabelInstr::New(Js::OpCode::Label, func, true /* isOpHelper */);
  8957. // See if we can skip various array checks on value type alone
  8958. if (!baseValueType.IsArray())
  8959. {
  8960. GenerateArrayTest(arrayOpnd, bailOutLabel, bailOutLabel, instr, false);
  8961. }
  8962. if (!(baseValueType.IsArray() && baseValueType.HasNoMissingValues()))
  8963. {
  8964. InsertTestBranch(
  8965. IR::IndirOpnd::New(arrayOpnd, Js::JavascriptArray::GetOffsetOfArrayFlags(), TyUint8, func),
  8966. IR::IntConstOpnd::New(static_cast<uint8>(Js::DynamicObjectFlags::HasNoMissingValues), TyUint8, func, true),
  8967. Js::OpCode::BrEq_A,
  8968. bailOutLabel,
  8969. instr);
  8970. }
  8971. IR::IndirOpnd *arrayLenPtrOpnd = IR::IndirOpnd::New(arrayOpnd, Js::JavascriptArray::GetOffsetOfLength(), TyUint32, func);
  8972. InsertCompareBranch(arrayLenPtrOpnd, IR::IntConstOpnd::New(Js::InlineeCallInfo::MaxInlineeArgoutCount - 1, TyUint8, func), Js::OpCode::BrGt_A, true, bailOutLabel, instr);
  8973. IR::LabelInstr *skipBailOutLabel = IR::LabelInstr::New(Js::OpCode::Label, func);
  8974. InsertBranch(Js::OpCode::Br, skipBailOutLabel, instr);
  8975. instr->InsertBefore(bailOutLabel);
  8976. instr->InsertAfter(skipBailOutLabel);
  8977. GenerateBailOut(instr);
  8978. return prevInstr;
  8979. }
  8980. IR::Instr *
  8981. Lowerer::LowerBailOnNotPolymorphicInlinee(IR::Instr * instr)
  8982. {
  8983. Assert(instr->HasBailOutInfo() && (instr->GetBailOutKind() == IR::BailOutOnFailedPolymorphicInlineTypeCheck || instr->GetBailOutKind() == IR::BailOutOnPolymorphicInlineFunction));
  8984. IR::Instr* instrPrev = instr->m_prev;
  8985. this->GenerateBailOut(instr, nullptr, nullptr);
  8986. return instrPrev;
  8987. }
  8988. void
  8989. Lowerer::LowerBailoutCheckAndLabel(IR::Instr *instr, bool onEqual, bool isHelper)
  8990. {
  8991. // Label to skip Bailout and continue
  8992. IR::LabelInstr * continueLabelInstr;
  8993. IR::Instr *instrNext = instr->m_next;
  8994. if (instrNext->IsLabelInstr())
  8995. {
  8996. continueLabelInstr = instrNext->AsLabelInstr();
  8997. }
  8998. else
  8999. {
  9000. continueLabelInstr = IR::LabelInstr::New(Js::OpCode::Label, m_func, isHelper);
  9001. instr->InsertAfter(continueLabelInstr);
  9002. }
  9003. if(instr->GetBailOutKind() == IR::BailOutInjected)
  9004. {
  9005. // BailOnEqual 0, 0
  9006. Assert(onEqual);
  9007. Assert(instr->GetSrc1()->IsEqual(instr->GetSrc2()));
  9008. Assert(instr->GetSrc1()->AsIntConstOpnd()->GetValue() == 0);
  9009. // The operands cannot be equal when generating a compare (assert) but since this is for testing purposes, hoist a src.
  9010. // Ideally, we would just create a BailOut instruction that generates a guaranteed bailout, but there seem to be issues
  9011. // with doing this in a non-helper path. So finally, it would generate:
  9012. // xor s0, s0
  9013. // test s0, s0
  9014. // jnz $continue
  9015. // $bailout:
  9016. // // bailout
  9017. // $continue:
  9018. instr->HoistSrc1(LowererMD::GetLoadOp(instr->GetSrc1()->GetType()));
  9019. }
  9020. InsertCompareBranch(instr->UnlinkSrc1(), instr->UnlinkSrc2(),
  9021. onEqual ? Js::OpCode::BrNeq_A : Js::OpCode::BrEq_A, continueLabelInstr, instr);
  9022. if (!isHelper)
  9023. {
  9024. IR::LabelInstr * helperLabelInstr = IR::LabelInstr::New(Js::OpCode::Label, m_func, true);
  9025. instr->InsertBefore(helperLabelInstr);
  9026. }
  9027. }
  9028. IR::Instr *
  9029. Lowerer::LowerBailOnEqualOrNotEqual(IR::Instr * instr,
  9030. IR::BranchInstr *branchInstr, // = nullptr
  9031. IR::LabelInstr *labelBailOut, // = nullptr
  9032. IR::PropertySymOpnd * propSymOpnd, // = nullptr
  9033. bool isHelper) // = false
  9034. {
  9035. IR::Instr * prevInstr = instr->m_prev;
  9036. // Bail out test
  9037. bool onEqual = instr->m_opcode == Js::OpCode::BailOnEqual;
  9038. LowerBailoutCheckAndLabel(instr, onEqual, isHelper);
  9039. // BailOutOnImplicitCalls is a post-op bailout. Since we look at the profile info for LdFld/StFld to decide whether the instruction may or may not call an accessor,
  9040. // we need to update this profile information on the bailout path for BailOutOnImplicitCalls if the implicit call was an accessor call.
  9041. if(propSymOpnd && ((instr->GetBailOutKind() & ~IR::BailOutKindBits) == IR::BailOutOnImplicitCalls) && (propSymOpnd->m_inlineCacheIndex != -1) &&
  9042. instr->m_func->GetJnFunction()->HasDynamicProfileInfo())
  9043. {
  9044. // result = AND implCallFlags, ~ImplicitCall_None
  9045. // TST result, ImplicitCall_Accessor
  9046. // JEQ $bail
  9047. // OR profiledFlags, FldInfoAccessor
  9048. // $bail
  9049. IR::Opnd * implicitCallFlags = GetImplicitCallFlagsOpnd();
  9050. IR::Opnd * accessorImplicitCall = IR::IntConstOpnd::New(Js::ImplicitCall_Accessor & ~Js::ImplicitCall_None, GetImplicitCallFlagsType(), instr->m_func, true);
  9051. IR::Opnd * maskNoImplicitCall = IR::IntConstOpnd::New((Js::ImplicitCallFlags)~Js::ImplicitCall_None, GetImplicitCallFlagsType(), instr->m_func, true);
  9052. IR::Opnd * fldInfoAccessor = IR::IntConstOpnd::New(Js::FldInfo_FromAccessor, GetFldInfoFlagsType(), instr->m_func, true);
  9053. IR::LabelInstr * label = IR::LabelInstr::New(Js::OpCode::Label, instr->m_func, true);
  9054. IR::Instr * andInstr = InsertAnd(IR::RegOpnd::New(GetImplicitCallFlagsType(), instr->m_func), implicitCallFlags, maskNoImplicitCall, instr);
  9055. InsertTestBranch(andInstr->GetDst(), accessorImplicitCall, Js::OpCode::BrEq_A, label, instr);
  9056. Js::FldInfo * info = instr->m_func->GetJnFunction()->GetAnyDynamicProfileInfo()->GetFldInfo(instr->m_func->GetJnFunction(), propSymOpnd->m_inlineCacheIndex);
  9057. IR::Opnd * profiledFlags = IR::MemRefOpnd::New((char*)info + info->GetOffsetOfFlags(), TyInt8, instr->m_func);
  9058. InsertOr(profiledFlags, profiledFlags, fldInfoAccessor, instr);
  9059. instr->InsertBefore(label);
  9060. }
  9061. this->GenerateBailOut(instr, branchInstr, labelBailOut);
  9062. return prevInstr;
  9063. }
  9064. void Lowerer::LowerBailOnNegative(IR::Instr *const instr)
  9065. {
  9066. Assert(instr);
  9067. Assert(instr->m_opcode == Js::OpCode::BailOnNegative);
  9068. Assert(instr->HasBailOutInfo());
  9069. Assert(!instr->GetDst());
  9070. Assert(instr->GetSrc1());
  9071. Assert(instr->GetSrc1()->GetType() == TyInt32 || instr->GetSrc1()->GetType() == TyUint32);
  9072. Assert(!instr->GetSrc2());
  9073. IR::LabelInstr *const skipBailOutLabel = instr->GetOrCreateContinueLabel(false);
  9074. LowerOneBailOutKind(instr, instr->GetBailOutKind(), false);
  9075. Assert(!instr->HasBailOutInfo());
  9076. IR::Instr *insertBeforeInstr = instr->m_next;
  9077. Func *const func = instr->m_func;
  9078. // test src, src
  9079. // jns $skipBailOut
  9080. InsertCompareBranch(
  9081. instr->UnlinkSrc1(),
  9082. IR::IntConstOpnd::New(0, TyInt32, func, true),
  9083. Js::OpCode::BrGe_A,
  9084. skipBailOutLabel,
  9085. insertBeforeInstr);
  9086. instr->Remove();
  9087. }
  9088. IR::Instr *
  9089. Lowerer::LowerBailOnNotObject(IR::Instr *instr,
  9090. IR::BranchInstr *branchInstr /* = nullptr */,
  9091. IR::LabelInstr *labelBailOut /* = nullptr */)
  9092. {
  9093. IR::Instr *prevInstr = instr->m_prev;
  9094. IR::LabelInstr *continueLabelInstr = IR::LabelInstr::New(Js::OpCode::Label,
  9095. m_func);
  9096. instr->InsertAfter(continueLabelInstr);
  9097. this->m_lowererMD.GenerateObjectTest(instr->UnlinkSrc1(),
  9098. instr,
  9099. continueLabelInstr,
  9100. /* fContinueLabel = */ true);
  9101. this->GenerateBailOut(instr, branchInstr, labelBailOut);
  9102. return prevInstr;
  9103. }
  9104. IR::Instr *
  9105. Lowerer::LowerBailOnNotBuiltIn(IR::Instr *instr,
  9106. IR::BranchInstr *branchInstr /* = nullptr */,
  9107. IR::LabelInstr *labelBailOut /* = nullptr */)
  9108. {
  9109. Assert(instr->GetSrc2()->IsIntConstOpnd());
  9110. IR::Instr *prevInstr = instr->m_prev;
  9111. Js::JavascriptFunction ** builtInFuncs = this->m_func->GetScriptContext()->GetLibrary()->GetBuiltinFunctions();
  9112. Js::BuiltinFunction builtInIndex = instr->UnlinkSrc2()->AsIntConstOpnd()->AsInt32();
  9113. IR::Opnd *builtIn = IR::MemRefOpnd::New((void*)(builtInFuncs + builtInIndex), TyMachReg, instr->m_func);
  9114. #if TESTBUILTINFORNULL
  9115. IR::LabelInstr * continueAfterTestLabel = IR::LabelInstr::New(Js::OpCode::Label, instr->m_func);
  9116. InsertTestBranch(builtIn, builtIn, Js::OpCode::BrNeq_A, continueAfterTestLabel, instr);
  9117. this->m_lowererMD.GenerateDebugBreak(instr);
  9118. instr->InsertBefore(continueAfterTestLabel);
  9119. #endif
  9120. IR::LabelInstr * continueLabel = IR::LabelInstr::New(Js::OpCode::Label, instr->m_func);
  9121. instr->InsertAfter(continueLabel);
  9122. InsertCompareBranch(instr->UnlinkSrc1(), builtIn, Js::OpCode::BrEq_A, continueLabel, instr);
  9123. GenerateBailOut(instr, branchInstr, labelBailOut);
  9124. return prevInstr;
  9125. }
  9126. IR::Instr *
  9127. Lowerer::LowerBailForDebugger(IR::Instr* instr, bool isInsideHelper /* = false */)
  9128. {
  9129. IR::Instr * prevInstr = instr->m_prev;
  9130. IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  9131. AssertMsg(bailOutKind, "bailOutKind should not be zero at this time.");
  9132. AssertMsg(!(bailOutKind & IR::BailOutExplicit) || bailOutKind == IR::BailOutExplicit,
  9133. "BailOutExplicit cannot be combined with any other bailout flags.");
  9134. IR::LabelInstr* bailOutLabel = nullptr;
  9135. if (!(bailOutKind & IR::BailOutExplicit))
  9136. {
  9137. Js::DebugManager* debugManager = this->GetScriptContext()->GetThreadContext()->GetDebugManager();
  9138. DebuggingFlags* flags = debugManager->GetDebuggingFlags();
  9139. // Check 1 (do we need to bail out?)
  9140. // JXX bailoutLabel
  9141. // Check 2 (do we need to bail out?)
  9142. // JXX bailoutLabel
  9143. // ...
  9144. // JMP continueLabel
  9145. // bailoutDocumentLabel:
  9146. // (determine if document boundary reached - if not, JMP to continueLabel)
  9147. // NOTE: THIS BLOCK IS CONDITIONALLY GENERATED BASED ON doGenerateBailOutDocumentBlock
  9148. // bailoutLabel:
  9149. // bail out
  9150. // continueLabel:
  9151. // ...
  9152. IR::LabelInstr* bailOutDocumentLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func, /*isOpHelper*/ true);
  9153. instr->InsertBefore(bailOutDocumentLabel);
  9154. IR::LabelInstr* bailOutLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func, /*isOpHelper*/ true);
  9155. instr->InsertBefore(bailOutLabel);
  9156. IR::LabelInstr* continueLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func, /*isOpHelper*/ isInsideHelper);
  9157. instr->InsertAfter(continueLabel);
  9158. IR::BranchInstr* continueBranchInstr = this->InsertBranch(Js::OpCode::Br, continueLabel, bailOutDocumentLabel); // JMP continueLabel.
  9159. bool doGenerateBailOutDocumentBlock = false;
  9160. const IR::BailOutKind c_forceAndIgnoreEx = IR::BailOutForceByFlag | IR::BailOutIgnoreException;
  9161. if ((bailOutKind & c_forceAndIgnoreEx) == c_forceAndIgnoreEx)
  9162. {
  9163. // It's faster to check these together in 1 check rather than 2 separate checks at run time.
  9164. // CMP [&(flags->m_forceInterpreter, flags->m_isIgnoreException)], 0
  9165. // BNE bailout
  9166. IR::Opnd* opnd1 = IR::MemRefOpnd::New((BYTE*)flags + DebuggingFlags::GetForceInterpreterOffset(), TyInt16, m_func);
  9167. IR::Opnd* opnd2 = IR::IntConstOpnd::New(0, TyInt16, m_func, /*dontEncode*/ true);
  9168. InsertCompareBranch(opnd1, opnd2, Js::OpCode::BrNeq_A, bailOutLabel, continueBranchInstr);
  9169. bailOutKind ^= c_forceAndIgnoreEx;
  9170. }
  9171. else
  9172. {
  9173. if (bailOutKind & IR::BailOutForceByFlag)
  9174. {
  9175. // CMP [&flags->m_forceInterpreter], 0
  9176. // BNE bailout
  9177. IR::Opnd* opnd1 = IR::MemRefOpnd::New((BYTE*)flags + DebuggingFlags::GetForceInterpreterOffset(), TyInt8, m_func);
  9178. IR::Opnd* opnd2 = IR::IntConstOpnd::New(0, TyInt8, m_func, /*dontEncode*/ true);
  9179. InsertCompareBranch(opnd1, opnd2, Js::OpCode::BrNeq_A, bailOutLabel, continueBranchInstr);
  9180. bailOutKind ^= IR::BailOutForceByFlag;
  9181. }
  9182. if (bailOutKind & IR::BailOutIgnoreException)
  9183. {
  9184. // CMP [&flags->m_byteCodeOffsetAfterIgnoreException], DebuggingFlags::InvalidByteCodeOffset
  9185. // BNE bailout
  9186. IR::Opnd* opnd1 = IR::MemRefOpnd::New((BYTE*)flags + flags->GetByteCodeOffsetAfterIgnoreExceptionOffset(), TyInt32, m_func);
  9187. IR::Opnd* opnd2 = IR::IntConstOpnd::New(DebuggingFlags::InvalidByteCodeOffset, TyInt32, m_func, /*dontEncode*/ true);
  9188. InsertCompareBranch(opnd1, opnd2, Js::OpCode::BrNeq_A, bailOutLabel, continueBranchInstr);
  9189. bailOutKind ^= IR::BailOutIgnoreException;
  9190. }
  9191. }
  9192. if (bailOutKind & IR::BailOutBreakPointInFunction)
  9193. {
  9194. // CMP [&functionBody->m_sourceInfo.m_probeCount], 0
  9195. // BNE bailout
  9196. Js::FunctionBody* body = m_func->GetJnFunction();
  9197. IR::Opnd* opnd1 = IR::MemRefOpnd::New(&body->GetSourceInfo()->m_probeCount, TyInt32, m_func);
  9198. IR::Opnd* opnd2 = IR::IntConstOpnd::New(0, TyInt32, m_func, /*dontEncode*/ true);
  9199. InsertCompareBranch(opnd1, opnd2, Js::OpCode::BrNeq_A, bailOutLabel, continueBranchInstr);
  9200. bailOutKind ^= IR::BailOutBreakPointInFunction;
  9201. }
  9202. // on method entry
  9203. if(bailOutKind & IR::BailOutStep)
  9204. {
  9205. // TEST STEP_BAILOUT, [&stepController->StepType]
  9206. // BNE BailoutLabel
  9207. IR::Opnd* opnd1 = IR::MemRefOpnd::New((void*)(debugManager->stepController.GetAddressOfStepType()), TyInt8, m_func);
  9208. IR::Opnd* opnd2 = IR::IntConstOpnd::New(Js::STEP_BAILOUT, TyInt8, this->m_func, /*dontEncode*/ true);
  9209. InsertTestBranch(opnd1, opnd2, Js::OpCode::BrNeq_A, bailOutLabel, continueBranchInstr);
  9210. // CMP STEP_DOCUMENT, [&stepController->StepType]
  9211. // BEQ BailoutDocumentLabel
  9212. opnd1 = IR::MemRefOpnd::New((void*)(debugManager->stepController.GetAddressOfStepType()), TyInt8, m_func);
  9213. opnd2 = IR::IntConstOpnd::New(Js::STEP_DOCUMENT, TyInt8, this->m_func, /*dontEncode*/ true);
  9214. InsertCompareBranch(opnd1, opnd2, Js::OpCode::BrEq_A, /*isUnsigned*/ true, bailOutDocumentLabel, continueBranchInstr);
  9215. doGenerateBailOutDocumentBlock = true;
  9216. bailOutKind ^= IR::BailOutStep;
  9217. }
  9218. // on method exit
  9219. if (bailOutKind & IR::BailOutStackFrameBase)
  9220. {
  9221. // CMP EffectiveFrameBase, [&stepController->frameAddrWhenSet]
  9222. // BA bailoutLabel
  9223. RegNum effectiveFrameBaseReg;
  9224. #ifdef _M_X64
  9225. effectiveFrameBaseReg = m_lowererMD.GetRegStackPointer();
  9226. #else
  9227. effectiveFrameBaseReg = m_lowererMD.GetRegFramePointer();
  9228. #endif
  9229. IR::Opnd* opnd1 = IR::RegOpnd::New(nullptr, effectiveFrameBaseReg, TyMachReg, m_func);
  9230. IR::Opnd* opnd2 = IR::MemRefOpnd::New(debugManager->stepController.GetAddressOfFrameAddress(), TyMachReg, m_func);
  9231. this->InsertCompareBranch(opnd1, opnd2, Js::OpCode::BrGt_A, /*isUnsigned*/ true, bailOutLabel, continueBranchInstr);
  9232. // CMP STEP_DOCUMENT, [&stepController->StepType]
  9233. // BEQ BailoutDocumentLabel
  9234. opnd1 = IR::MemRefOpnd::New((void*)(debugManager->stepController.GetAddressOfStepType()), TyInt8, m_func);
  9235. opnd2 = IR::IntConstOpnd::New(Js::STEP_DOCUMENT, TyInt8, this->m_func, /*dontEncode*/ true);
  9236. InsertCompareBranch(opnd1, opnd2, Js::OpCode::BrEq_A, /*isUnsigned*/ true, bailOutDocumentLabel, continueBranchInstr);
  9237. doGenerateBailOutDocumentBlock = true;
  9238. bailOutKind ^= IR::BailOutStackFrameBase;
  9239. }
  9240. if (bailOutKind & IR::BailOutLocalValueChanged)
  9241. {
  9242. int32 hasLocalVarChangedOffset = m_func->GetHasLocalVarChangedOffset();
  9243. if (hasLocalVarChangedOffset != Js::Constants::InvalidOffset)
  9244. {
  9245. // CMP [EBP + hasLocalVarChangedStackOffset], 0
  9246. // BNE bailout
  9247. StackSym* sym = StackSym::New(TyInt8, m_func);
  9248. sym->m_offset = hasLocalVarChangedOffset;
  9249. sym->m_allocated = true;
  9250. IR::Opnd* opnd1 = IR::SymOpnd::New(sym, TyInt8, m_func);
  9251. IR::Opnd* opnd2 = IR::IntConstOpnd::New(0, TyInt8, m_func);
  9252. InsertCompareBranch(opnd1, opnd2, Js::OpCode::BrNeq_A, bailOutLabel, continueBranchInstr);
  9253. }
  9254. bailOutKind ^= IR::BailOutLocalValueChanged;
  9255. }
  9256. if (doGenerateBailOutDocumentBlock)
  9257. {
  9258. // GENERATE the BailoutDocumentLabel
  9259. // bailOutDocumentLabel:
  9260. // CMP CurrentScriptId, [&stepController->ScriptIdWhenSet]
  9261. // BEQ ContinueLabel
  9262. // bailOutLabel: // (fallthrough bailOutLabel)
  9263. Js::FunctionBody* body = m_func->GetJnFunction();
  9264. IR::Opnd* opnd1 = IR::MemRefOpnd::New(body->GetAddressOfScriptId(), TyInt32, m_func);
  9265. IR::Opnd* opnd2 = IR::MemRefOpnd::New(debugManager->stepController.GetAddressOfScriptIdWhenSet(), TyInt32, m_func);
  9266. IR::RegOpnd* reg1 = IR::RegOpnd::New(TyInt32, m_func);
  9267. InsertMove(reg1, opnd2, bailOutLabel);
  9268. InsertCompareBranch(opnd1, reg1, Js::OpCode::BrEq_A, /*isUnsigned*/ true, continueLabel, bailOutLabel);
  9269. }
  9270. AssertMsg(bailOutKind == (IR::BailOutKind)0, "Some of the bits in BailOutKind were not processed!");
  9271. // Note: at this time the 'instr' is in between bailoutLabel and continueLabel.
  9272. }
  9273. else
  9274. {
  9275. // For explicit/unconditional bailout use label which is not a helper, otherwise we would get a helper in main code path
  9276. // which breaks helper label consistency (you can only get to helper from a conditional branch in main code), see DbCheckPostLower.
  9277. bailOutLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, false);
  9278. }
  9279. this->GenerateBailOut(instr, nullptr, bailOutLabel);
  9280. return prevInstr;
  9281. }
  9282. IR::Instr*
  9283. Lowerer::LowerBailOnException(IR::Instr * instr)
  9284. {
  9285. Assert(instr->HasBailOutInfo());
  9286. IR::Instr * instrPrev = instr->m_prev;
  9287. Assert(instrPrev->m_opcode == Js::OpCode::Catch);
  9288. this->GenerateBailOut(instr, nullptr, nullptr);
  9289. return instrPrev;
  9290. }
  9291. // Generate BailOut Lowerer Instruction if the value is INT_MIN.
  9292. // It it's not INT_MIN, we continue without bailout.
  9293. IR::Instr *
  9294. Lowerer::LowerBailOnIntMin(IR::Instr *instr, IR::BranchInstr *branchInstr /* = nullptr */, IR::LabelInstr *labelBailOut /* = nullptr */)
  9295. {
  9296. Assert(instr);
  9297. Assert(instr->GetSrc1());
  9298. IR::LabelInstr *continueLabelInstr = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  9299. instr->InsertAfter(continueLabelInstr);
  9300. if(!instr->HasBailOutInfo())
  9301. {
  9302. instr->Remove();
  9303. }
  9304. else
  9305. {
  9306. Assert(instr->GetBailOutKind() == IR::BailOnIntMin);
  9307. // Note: src1 must be int32 at this point.
  9308. if (instr->GetSrc1()->IsIntConstOpnd())
  9309. {
  9310. // For consts we can check the value at JIT time. Note: without this check we'll have to legalize the CMP instr.
  9311. IR::IntConstOpnd* intConst = instr->UnlinkSrc1()->AsIntConstOpnd();
  9312. if (intConst->GetValue() == INT_MIN)
  9313. {
  9314. this->GenerateBailOut(instr, branchInstr, labelBailOut);
  9315. intConst->Free(instr->m_func);
  9316. }
  9317. else
  9318. {
  9319. instr->Remove();
  9320. }
  9321. }
  9322. else
  9323. {
  9324. InsertCompareBranch(instr->UnlinkSrc1(), IR::IntConstOpnd::New(INT_MIN, TyInt32, this->m_func), Js::OpCode::BrNeq_A, continueLabelInstr, instr);
  9325. this->GenerateBailOut(instr, branchInstr, labelBailOut);
  9326. }
  9327. }
  9328. return continueLabelInstr;
  9329. }
  9330. ///----------------------------------------------------------------------------
  9331. ///
  9332. /// Lowerer::LowerBailOnNotString
  9333. /// Generate BailOut Lowerer Instruction if not a String
  9334. ///
  9335. ///----------------------------------------------------------------------------
  9336. void Lowerer::LowerBailOnNotString(IR::Instr *instr)
  9337. {
  9338. if (!instr->GetSrc1()->GetValueType().IsString())
  9339. {
  9340. /*Creating a MOV instruction*/
  9341. IR::Instr * movInstr = IR::Instr::New(instr->m_opcode, instr->UnlinkDst(), instr->UnlinkSrc1(), instr->m_func);
  9342. instr->InsertBefore(movInstr);
  9343. IR::LabelInstr *continueLabelInstr = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  9344. IR::LabelInstr *helperLabelInstr = IR::LabelInstr::New(Js::OpCode::Label, m_func, true);
  9345. instr->InsertAfter(continueLabelInstr);
  9346. IR::RegOpnd *srcReg = movInstr->GetSrc1()->IsRegOpnd() ? movInstr->GetSrc1()->AsRegOpnd() : nullptr;
  9347. this->GenerateStringTest(srcReg, instr, helperLabelInstr, continueLabelInstr);
  9348. this->GenerateBailOut(instr, nullptr, helperLabelInstr);
  9349. }
  9350. else
  9351. {
  9352. instr->ClearBailOutInfo();
  9353. }
  9354. }
  9355. void Lowerer::LowerOneBailOutKind(
  9356. IR::Instr *const instr,
  9357. const IR::BailOutKind bailOutKindToLower,
  9358. const bool isInHelperBlock,
  9359. const bool preserveBailOutKindInInstr)
  9360. {
  9361. Assert(instr);
  9362. Assert(bailOutKindToLower);
  9363. Assert(!(bailOutKindToLower & IR::BailOutKindBits) || !(bailOutKindToLower & bailOutKindToLower - 1u));
  9364. Func *const func = instr->m_func;
  9365. // Split bailouts other than the one being lowered here
  9366. BailOutInfo *const bailOutInfo = instr->GetBailOutInfo();
  9367. IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  9368. Assert(
  9369. bailOutKindToLower & IR::BailOutKindBits
  9370. ? bailOutKind & bailOutKindToLower
  9371. : (bailOutKind & ~IR::BailOutKindBits) == bailOutKindToLower);
  9372. if(!preserveBailOutKindInInstr)
  9373. {
  9374. bailOutKind -= bailOutKindToLower;
  9375. }
  9376. if(bailOutKind)
  9377. {
  9378. if(bailOutInfo->bailOutInstr == instr)
  9379. {
  9380. // Create a shared bailout point for the split bailout checks
  9381. IR::Instr *const sharedBail = instr->ShareBailOut();
  9382. Assert(sharedBail->GetBailOutInfo() == bailOutInfo);
  9383. GenerateBailOut(sharedBail);
  9384. }
  9385. instr->SetBailOutKind(bailOutKind);
  9386. }
  9387. else
  9388. {
  9389. instr->UnlinkBailOutInfo();
  9390. if(bailOutInfo->bailOutInstr == instr)
  9391. {
  9392. bailOutInfo->bailOutInstr = nullptr;
  9393. }
  9394. }
  9395. IR::Instr *const insertBeforeInstr = instr->m_next;
  9396. // (Bail out with the requested bail out kind)
  9397. IR::BailOutInstr *const bailOutInstr = IR::BailOutInstr::New(Js::OpCode::BailOut, bailOutKindToLower, bailOutInfo, func);
  9398. bailOutInstr->SetByteCodeOffset(instr);
  9399. insertBeforeInstr->InsertBefore(bailOutInstr);
  9400. GenerateBailOut(bailOutInstr);
  9401. // The caller is expected to generate code to decide whether to bail out
  9402. }
  9403. void Lowerer::SplitBailOnNotArray(
  9404. IR::Instr *const instr,
  9405. IR::Instr * *const bailOnNotArrayRef,
  9406. IR::Instr * *const bailOnMissingValueRef)
  9407. {
  9408. Assert(instr);
  9409. Assert(!instr->GetDst());
  9410. Assert(instr->GetSrc1());
  9411. Assert(instr->GetSrc1()->IsRegOpnd());
  9412. Assert(!instr->GetSrc2());
  9413. Assert(bailOnNotArrayRef);
  9414. Assert(bailOnMissingValueRef);
  9415. IR::Instr *&bailOnNotArray = *bailOnNotArrayRef;
  9416. IR::Instr *&bailOnMissingValue = *bailOnMissingValueRef;
  9417. bailOnNotArray = instr;
  9418. bailOnMissingValue = nullptr;
  9419. IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  9420. if(bailOutKind == IR::BailOutOnNotArray ||
  9421. bailOutKind == IR::BailOutOnNotNativeArray)
  9422. {
  9423. return;
  9424. }
  9425. // Split array checks
  9426. BailOutInfo *const bailOutInfo = instr->GetBailOutInfo();
  9427. if(bailOutInfo->bailOutInstr == instr)
  9428. {
  9429. // Create a shared bailout point for the split bailout checks
  9430. IR::Instr *const sharedBail = instr->ShareBailOut();
  9431. Assert(sharedBail->GetBailOutInfo() == bailOutInfo);
  9432. LowerBailTarget(sharedBail);
  9433. }
  9434. bailOutKind -= IR::BailOutOnMissingValue;
  9435. Assert(bailOutKind == IR::BailOutOnNotArray ||
  9436. bailOutKind == IR::BailOutOnNotNativeArray);
  9437. instr->SetBailOutKind(bailOutKind);
  9438. Func *const func = bailOutInfo->bailOutFunc;
  9439. IR::Instr *const insertBeforeInstr = instr->m_next;
  9440. // Split missing value checks
  9441. bailOnMissingValue = IR::BailOutInstr::New(Js::OpCode::BailOnNotArray, IR::BailOutOnMissingValue, bailOutInfo, func);
  9442. bailOnMissingValue->SetByteCodeOffset(instr);
  9443. insertBeforeInstr->InsertBefore(bailOnMissingValue);
  9444. }
  9445. IR::RegOpnd *Lowerer::LowerBailOnNotArray(IR::Instr *const instr)
  9446. {
  9447. Assert(instr);
  9448. Assert(!instr->GetDst());
  9449. Assert(instr->GetSrc1());
  9450. Assert(instr->GetSrc1()->IsRegOpnd());
  9451. Assert(!instr->GetSrc2());
  9452. Func *const func = instr->m_func;
  9453. // Label to jump to (or fall through to) when bailing out
  9454. const auto bailOutLabel = IR::LabelInstr::New(Js::OpCode::Label, func, true /* isOpHelper */);
  9455. instr->InsertBefore(bailOutLabel);
  9456. // Label to jump to when not bailing out
  9457. const auto skipBailOutLabel = IR::LabelInstr::New(Js::OpCode::Label, func);
  9458. instr->InsertAfter(skipBailOutLabel);
  9459. // Do the array tests and jump to bailOutLabel if it's not an array. Fall through if it is an array.
  9460. IR::RegOpnd *const arrayOpnd =
  9461. GenerateArrayTest(instr->UnlinkSrc1()->AsRegOpnd(), bailOutLabel, bailOutLabel, bailOutLabel, true);
  9462. // Skip bail-out when it is an array
  9463. InsertBranch(Js::OpCode::Br, skipBailOutLabel, bailOutLabel);
  9464. // Generate the bailout helper call. 'instr' will be changed to the CALL into the bailout function, so it can't be used for
  9465. // ordering instructions anymore.
  9466. GenerateBailOut(instr);
  9467. return arrayOpnd;
  9468. }
  9469. void Lowerer::LowerBailOnMissingValue(IR::Instr *const instr, IR::RegOpnd *const arrayOpnd)
  9470. {
  9471. Assert(instr);
  9472. Assert(!instr->GetDst());
  9473. Assert(!instr->GetSrc1());
  9474. Assert(!instr->GetSrc2());
  9475. Assert(arrayOpnd);
  9476. Assert(arrayOpnd->GetValueType().IsArrayOrObjectWithArray());
  9477. Func *const func = instr->m_func;
  9478. // Label to jump to when not bailing out
  9479. const auto skipBailOutLabel = IR::LabelInstr::New(Js::OpCode::Label, func);
  9480. instr->InsertAfter(skipBailOutLabel);
  9481. // Skip bail-out when the array has no missing values
  9482. //
  9483. // test [array + offsetOf(objectArrayOrFlags)], Js::DynamicObjectFlags::HasNoMissingValues
  9484. // jnz $skipBailOut
  9485. const IR::AutoReuseOpnd autoReuseArrayOpnd(arrayOpnd, func);
  9486. CompileAssert(
  9487. static_cast<Js::DynamicObjectFlags>(static_cast<uint8>(Js::DynamicObjectFlags::HasNoMissingValues)) ==
  9488. Js::DynamicObjectFlags::HasNoMissingValues);
  9489. InsertTestBranch(
  9490. IR::IndirOpnd::New(arrayOpnd, Js::JavascriptArray::GetOffsetOfArrayFlags(), TyUint8, func),
  9491. IR::IntConstOpnd::New(static_cast<uint8>(Js::DynamicObjectFlags::HasNoMissingValues), TyUint8, func, true),
  9492. Js::OpCode::BrNeq_A,
  9493. skipBailOutLabel,
  9494. instr);
  9495. // Generate the bailout helper call. 'instr' will be changed to the CALL into the bailout function, so it can't be used for
  9496. // ordering instructions anymore.
  9497. GenerateBailOut(instr);
  9498. }
  9499. void Lowerer::LowerBailOnInvalidatedArrayHeadSegment(IR::Instr *const instr, const bool isInHelperBlock)
  9500. {
  9501. /*
  9502. // Generate checks for whether the head segment or the head segment length changed during the helper call
  9503. if(!(baseValueType.IsArrayOrObjectWithArray() && arrayOpnd && arrayOpnd.HeadSegmentSym()))
  9504. {
  9505. // Record the array head segment before the helper call
  9506. headSegmentBeforeHelperCall = Js::JavascriptArray::Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(base)
  9507. }
  9508. if(!(baseValueType.IsArrayOrObjectWithArray() && arrayOpnd && arrayOpnd.HeadSegmentLengthSym()))
  9509. {
  9510. // Record the array head segment length before the helper call
  9511. if(baseValueType.IsArrayOrObjectWithArray() && arrayOpnd && arrayOpnd.HeadSegmentSym())
  9512. {
  9513. mov headSegmentLengthBeforeHelperCall, [headSegmentBeforeHelperCall + offsetOf(length)]
  9514. }
  9515. else
  9516. {
  9517. headSegmentLengthBeforeHelperCall =
  9518. Js::JavascriptArray::Jit_GetArrayHeadSegmentLength(headSegmentBeforeHelperCall)
  9519. }
  9520. }
  9521. helperCall:
  9522. (Helper call and other bailout checks)
  9523. // If the array has a different head segment or head segment length after the helper call, then this store needs to bail
  9524. // out
  9525. invalidatedHeadSegment =
  9526. JavascriptArray::Jit_OperationInvalidatedArrayHeadSegment(
  9527. headSegmentBeforeHelperCall,
  9528. headSegmentLengthBeforeHelperCall,
  9529. base)
  9530. test invalidatedHeadSegment, invalidatedHeadSegment
  9531. jz $skipBailOut
  9532. (Bail out with IR::BailOutOnInvalidatedArrayHeadSegment)
  9533. $skipBailOut:
  9534. */
  9535. Assert(instr);
  9536. Assert(instr->m_opcode == Js::OpCode::StElemI_A || instr->m_opcode == Js::OpCode::StElemI_A_Strict || instr->m_opcode == Js::OpCode::Memset || instr->m_opcode == Js::OpCode::Memcopy);
  9537. Assert(instr->GetDst());
  9538. Assert(instr->GetDst()->IsIndirOpnd());
  9539. Func *const func = instr->m_func;
  9540. IR::RegOpnd *const baseOpnd = instr->GetDst()->AsIndirOpnd()->GetBaseOpnd();
  9541. const ValueType baseValueType(baseOpnd->GetValueType());
  9542. Assert(!baseValueType.IsNotArrayOrObjectWithArray());
  9543. const bool isArrayOrObjectWithArray = baseValueType.IsArrayOrObjectWithArray();
  9544. IR::ArrayRegOpnd *const arrayOpnd = baseOpnd->IsArrayRegOpnd() ? baseOpnd->AsArrayRegOpnd() : nullptr;
  9545. IR::RegOpnd *headSegmentBeforeHelperCallOpnd;
  9546. IR::AutoReuseOpnd autoReuseHeadSegmentBeforeHelperCallOpnd;
  9547. if(isArrayOrObjectWithArray && arrayOpnd && arrayOpnd->HeadSegmentSym())
  9548. {
  9549. headSegmentBeforeHelperCallOpnd = IR::RegOpnd::New(arrayOpnd->HeadSegmentSym(), TyMachPtr, func);
  9550. autoReuseHeadSegmentBeforeHelperCallOpnd.Initialize(headSegmentBeforeHelperCallOpnd, func);
  9551. }
  9552. else
  9553. {
  9554. // Record the array head segment before the helper call
  9555. // headSegmentBeforeHelperCall = Js::JavascriptArray::Jit_GetArrayHeadSegmentForArrayOrObjectWithArray(base)
  9556. m_lowererMD.LoadHelperArgument(instr, baseOpnd);
  9557. IR::Instr *const callInstr = IR::Instr::New(Js::OpCode::Call, func);
  9558. headSegmentBeforeHelperCallOpnd = IR::RegOpnd::New(StackSym::New(TyMachPtr, func), TyMachPtr, func);
  9559. autoReuseHeadSegmentBeforeHelperCallOpnd.Initialize(headSegmentBeforeHelperCallOpnd, func);
  9560. callInstr->SetDst(headSegmentBeforeHelperCallOpnd);
  9561. instr->InsertBefore(callInstr);
  9562. m_lowererMD.ChangeToHelperCall(callInstr, IR::HelperArray_Jit_GetArrayHeadSegmentForArrayOrObjectWithArray);
  9563. }
  9564. IR::RegOpnd *headSegmentLengthBeforeHelperCallOpnd;
  9565. IR::AutoReuseOpnd autoReuseHeadSegmentLengthBeforeHelperCallOpnd;
  9566. if(isArrayOrObjectWithArray && arrayOpnd && arrayOpnd->HeadSegmentLengthSym())
  9567. {
  9568. headSegmentLengthBeforeHelperCallOpnd = IR::RegOpnd::New(arrayOpnd->HeadSegmentLengthSym(), TyUint32, func);
  9569. autoReuseHeadSegmentLengthBeforeHelperCallOpnd.Initialize(headSegmentLengthBeforeHelperCallOpnd, func);
  9570. }
  9571. else
  9572. {
  9573. headSegmentLengthBeforeHelperCallOpnd = IR::RegOpnd::New(StackSym::New(TyUint32, func), TyUint32, func);
  9574. autoReuseHeadSegmentLengthBeforeHelperCallOpnd.Initialize(headSegmentLengthBeforeHelperCallOpnd, func);
  9575. if(isArrayOrObjectWithArray && arrayOpnd && arrayOpnd->HeadSegmentSym())
  9576. {
  9577. // Record the array head segment length before the helper call
  9578. // mov headSegmentLengthBeforeHelperCall, [headSegmentBeforeHelperCall + offsetOf(length)]
  9579. InsertMove(
  9580. headSegmentLengthBeforeHelperCallOpnd,
  9581. IR::IndirOpnd::New(
  9582. headSegmentBeforeHelperCallOpnd,
  9583. Js::SparseArraySegmentBase::GetOffsetOfLength(),
  9584. TyUint32,
  9585. func),
  9586. instr);
  9587. }
  9588. else
  9589. {
  9590. // Record the array head segment length before the helper call
  9591. // headSegmentLengthBeforeHelperCall =
  9592. // Js::JavascriptArray::Jit_GetArrayHeadSegmentLength(headSegmentBeforeHelperCall)
  9593. m_lowererMD.LoadHelperArgument(instr, headSegmentBeforeHelperCallOpnd);
  9594. IR::Instr *const callInstr = IR::Instr::New(Js::OpCode::Call, func);
  9595. callInstr->SetDst(headSegmentLengthBeforeHelperCallOpnd);
  9596. instr->InsertBefore(callInstr);
  9597. m_lowererMD.ChangeToHelperCall(callInstr, IR::HelperArray_Jit_GetArrayHeadSegmentLength);
  9598. }
  9599. }
  9600. IR::LabelInstr *const skipBailOutLabel = instr->GetOrCreateContinueLabel(isInHelperBlock);
  9601. LowerOneBailOutKind(instr, IR::BailOutOnInvalidatedArrayHeadSegment, isInHelperBlock);
  9602. IR::Instr *const insertBeforeInstr = instr->m_next;
  9603. // If the array has a different head segment or head segment length after the helper call, then this store needs to bail out
  9604. // invalidatedHeadSegment =
  9605. // JavascriptArray::Jit_OperationInvalidatedArrayHeadSegment(
  9606. // headSegmentBeforeHelperCall,
  9607. // headSegmentLengthBeforeHelperCall,
  9608. // base)
  9609. m_lowererMD.LoadHelperArgument(insertBeforeInstr, baseOpnd);
  9610. m_lowererMD.LoadHelperArgument(insertBeforeInstr, headSegmentLengthBeforeHelperCallOpnd);
  9611. m_lowererMD.LoadHelperArgument(insertBeforeInstr, headSegmentBeforeHelperCallOpnd);
  9612. IR::Instr *const callInstr = IR::Instr::New(Js::OpCode::Call, func);
  9613. IR::RegOpnd *const invalidatedHeadSegmentOpnd = IR::RegOpnd::New(TyUint8, func);
  9614. const IR::AutoReuseOpnd autoReuseInvalidatedHeadSegmentOpnd(invalidatedHeadSegmentOpnd, func);
  9615. callInstr->SetDst(invalidatedHeadSegmentOpnd);
  9616. insertBeforeInstr->InsertBefore(callInstr);
  9617. m_lowererMD.ChangeToHelperCall(callInstr, IR::HelperArray_Jit_OperationInvalidatedArrayHeadSegment);
  9618. // test invalidatedHeadSegment, invalidatedHeadSegment
  9619. // jz $skipBailOut
  9620. InsertTestBranch(
  9621. invalidatedHeadSegmentOpnd,
  9622. invalidatedHeadSegmentOpnd,
  9623. Js::OpCode::BrEq_A,
  9624. skipBailOutLabel,
  9625. insertBeforeInstr);
  9626. // (Bail out with IR::BailOutOnInvalidatedArrayHeadSegment)
  9627. // $skipBailOut:
  9628. }
  9629. void Lowerer::LowerBailOnInvalidatedArrayLength(IR::Instr *const instr, const bool isInHelperBlock)
  9630. {
  9631. /*
  9632. // Generate checks for whether the length changed during the helper call
  9633. if(!(arrayOpnd && arrayOpnd.LengthSym() && arrayOpnd.LengthSym() != arrayOpnd.HeadSegmentLengthSym()))
  9634. {
  9635. // Record the array length before the helper call
  9636. lengthBeforeHelperCall = Js::JavascriptArray::Jit_GetArrayLength(base)
  9637. }
  9638. helperCall:
  9639. (Helper call and other bailout checks)
  9640. // If the array has a different length after the helper call, then this store needs to bail out
  9641. invalidatedLength = JavascriptArray::Jit_OperationInvalidatedArrayLength(lengthBeforeHelperCall, base)
  9642. test invalidatedLength, invalidatedLength
  9643. jz $skipBailOut
  9644. (Bail out with IR::BailOutOnInvalidatedArrayLength)
  9645. $skipBailOut:
  9646. */
  9647. Assert(instr);
  9648. Assert(instr->m_opcode == Js::OpCode::StElemI_A || instr->m_opcode == Js::OpCode::StElemI_A_Strict || instr->m_opcode == Js::OpCode::Memset || instr->m_opcode == Js::OpCode::Memcopy);
  9649. Assert(instr->GetDst());
  9650. Assert(instr->GetDst()->IsIndirOpnd());
  9651. Func *const func = instr->m_func;
  9652. IR::RegOpnd *const baseOpnd = instr->GetDst()->AsIndirOpnd()->GetBaseOpnd();
  9653. const ValueType baseValueType(baseOpnd->GetValueType());
  9654. Assert(!baseValueType.IsNotArray());
  9655. IR::ArrayRegOpnd *const arrayOpnd = baseOpnd->IsArrayRegOpnd() ? baseOpnd->AsArrayRegOpnd() : nullptr;
  9656. IR::RegOpnd *lengthBeforeHelperCallOpnd;
  9657. IR::AutoReuseOpnd autoReuseLengthBeforeHelperCallOpnd;
  9658. if(arrayOpnd && arrayOpnd->LengthSym() && arrayOpnd->LengthSym() != arrayOpnd->HeadSegmentLengthSym())
  9659. {
  9660. lengthBeforeHelperCallOpnd = IR::RegOpnd::New(arrayOpnd->LengthSym(), arrayOpnd->LengthSym()->GetType(), func);
  9661. autoReuseLengthBeforeHelperCallOpnd.Initialize(lengthBeforeHelperCallOpnd, func);
  9662. }
  9663. else
  9664. {
  9665. // Record the array length before the helper call
  9666. // lengthBeforeHelperCall = Js::JavascriptArray::Jit_GetArrayLength(base)
  9667. m_lowererMD.LoadHelperArgument(instr, baseOpnd);
  9668. IR::Instr *const callInstr = IR::Instr::New(Js::OpCode::Call, func);
  9669. lengthBeforeHelperCallOpnd = IR::RegOpnd::New(TyUint32, func);
  9670. autoReuseLengthBeforeHelperCallOpnd.Initialize(lengthBeforeHelperCallOpnd, func);
  9671. callInstr->SetDst(lengthBeforeHelperCallOpnd);
  9672. instr->InsertBefore(callInstr);
  9673. m_lowererMD.ChangeToHelperCall(callInstr, IR::HelperArray_Jit_GetArrayLength);
  9674. }
  9675. IR::LabelInstr *const skipBailOutLabel = instr->GetOrCreateContinueLabel(isInHelperBlock);
  9676. LowerOneBailOutKind(instr, IR::BailOutOnInvalidatedArrayLength, isInHelperBlock);
  9677. IR::Instr *const insertBeforeInstr = instr->m_next;
  9678. // If the array has a different length after the helper call, then this store needs to bail out
  9679. // invalidatedLength = JavascriptArray::Jit_OperationInvalidatedArrayLength(lengthBeforeHelperCall, base)
  9680. m_lowererMD.LoadHelperArgument(insertBeforeInstr, baseOpnd);
  9681. m_lowererMD.LoadHelperArgument(insertBeforeInstr, lengthBeforeHelperCallOpnd);
  9682. IR::Instr *const callInstr = IR::Instr::New(Js::OpCode::Call, func);
  9683. IR::RegOpnd *const invalidatedLengthOpnd = IR::RegOpnd::New(TyUint8, func);
  9684. const IR::AutoReuseOpnd autoReuseInvalidatedLengthOpnd(invalidatedLengthOpnd, func);
  9685. callInstr->SetDst(invalidatedLengthOpnd);
  9686. insertBeforeInstr->InsertBefore(callInstr);
  9687. m_lowererMD.ChangeToHelperCall(callInstr, IR::HelperArray_Jit_OperationInvalidatedArrayLength);
  9688. // test invalidatedLength, invalidatedLength
  9689. // jz $skipBailOut
  9690. InsertTestBranch(
  9691. invalidatedLengthOpnd,
  9692. invalidatedLengthOpnd,
  9693. Js::OpCode::BrEq_A,
  9694. skipBailOutLabel,
  9695. insertBeforeInstr);
  9696. // (Bail out with IR::BailOutOnInvalidatedArrayLength)
  9697. // $skipBailOut:
  9698. }
  9699. void Lowerer::LowerBailOnCreatedMissingValue(IR::Instr *const instr, const bool isInHelperBlock)
  9700. {
  9701. /*
  9702. // Generate checks for whether the first missing value was created during the helper call
  9703. if(!(baseValueType.IsArrayOrObjectWithArray() && baseValueType.HasNoMissingValues()))
  9704. {
  9705. // Record whether the array has missing values before the helper call
  9706. arrayFlagsBeforeHelperCall = Js::JavascriptArray::Jit_GetArrayFlagsForArrayOrObjectWithArray(base)
  9707. }
  9708. helperCall:
  9709. (Helper call and other bailout checks)
  9710. // If the array had no missing values before the helper call, and the array has missing values after the helper
  9711. // call, then this store created the first missing value in the array and needs to bail out
  9712. if(baseValueType.IsArrayOrObjectWithArray() && baseValueType.HasNoMissingValues())
  9713. (arrayFlagsBeforeHelperCall = Js::DynamicObjectFlags::HasNoMissingValues)
  9714. createdFirstMissingValue = JavascriptArray::Jit_OperationCreatedFirstMissingValue(arrayFlagsBeforeHelperCall, base)
  9715. test createdFirstMissingValue, createdFirstMissingValue
  9716. jz $skipBailOut
  9717. (Bail out with IR::BailOutOnMissingValue)
  9718. $skipBailOut:
  9719. */
  9720. Assert(instr);
  9721. Assert(instr->m_opcode == Js::OpCode::StElemI_A || instr->m_opcode == Js::OpCode::StElemI_A_Strict || instr->m_opcode == Js::OpCode::Memset || instr->m_opcode == Js::OpCode::Memcopy);
  9722. Assert(instr->GetDst());
  9723. Assert(instr->GetDst()->IsIndirOpnd());
  9724. Func *const func = instr->m_func;
  9725. IR::RegOpnd *const baseOpnd = instr->GetDst()->AsIndirOpnd()->GetBaseOpnd();
  9726. const ValueType baseValueType(baseOpnd->GetValueType());
  9727. Assert(!baseValueType.IsNotArrayOrObjectWithArray());
  9728. IR::Opnd *arrayFlagsBeforeHelperCallOpnd = nullptr;
  9729. IR::AutoReuseOpnd autoReuseArrayFlagsBeforeHelperCallOpnd;
  9730. const IRType arrayFlagsType = sizeof(uintptr_t) == sizeof(uint32) ? TyUint32 : TyUint64;
  9731. if(!(baseValueType.IsArrayOrObjectWithArray() && baseValueType.HasNoMissingValues()))
  9732. {
  9733. // Record whether the array has missing values before the helper call
  9734. // arrayFlagsBeforeHelperCall = Js::JavascriptArray::Jit_GetArrayFlagsForArrayOrObjectWithArray(base)
  9735. m_lowererMD.LoadHelperArgument(instr, baseOpnd);
  9736. IR::Instr *const callInstr = IR::Instr::New(Js::OpCode::Call, func);
  9737. arrayFlagsBeforeHelperCallOpnd = IR::RegOpnd::New(arrayFlagsType, func);
  9738. autoReuseArrayFlagsBeforeHelperCallOpnd.Initialize(arrayFlagsBeforeHelperCallOpnd, func);
  9739. callInstr->SetDst(arrayFlagsBeforeHelperCallOpnd);
  9740. instr->InsertBefore(callInstr);
  9741. m_lowererMD.ChangeToHelperCall(callInstr, IR::HelperArray_Jit_GetArrayFlagsForArrayOrObjectWithArray);
  9742. }
  9743. IR::LabelInstr *const skipBailOutLabel = instr->GetOrCreateContinueLabel(isInHelperBlock);
  9744. LowerOneBailOutKind(instr, IR::BailOutOnMissingValue, isInHelperBlock);
  9745. IR::Instr *const insertBeforeInstr = instr->m_next;
  9746. // If the array had no missing values before the helper call, and the array has missing values after the helper
  9747. // call, then this store created the first missing value in the array and needs to bail out
  9748. if(baseValueType.IsArrayOrObjectWithArray() && baseValueType.HasNoMissingValues())
  9749. {
  9750. // (arrayFlagsBeforeHelperCall = Js::DynamicObjectFlags::HasNoMissingValues)
  9751. Assert(!arrayFlagsBeforeHelperCallOpnd);
  9752. arrayFlagsBeforeHelperCallOpnd =
  9753. arrayFlagsType == TyUint32
  9754. ? static_cast<IR::Opnd *>(
  9755. IR::IntConstOpnd::New(
  9756. static_cast<uintptr_t>(Js::DynamicObjectFlags::HasNoMissingValues),
  9757. arrayFlagsType,
  9758. func,
  9759. true))
  9760. : IR::AddrOpnd::New(
  9761. reinterpret_cast<void *>(Js::DynamicObjectFlags::HasNoMissingValues),
  9762. IR::AddrOpndKindConstantVar,
  9763. func,
  9764. true);
  9765. autoReuseArrayFlagsBeforeHelperCallOpnd.Initialize(arrayFlagsBeforeHelperCallOpnd, func);
  9766. }
  9767. else
  9768. {
  9769. Assert(arrayFlagsBeforeHelperCallOpnd);
  9770. }
  9771. // createdFirstMissingValue = JavascriptArray::Jit_OperationCreatedFirstMissingValue(arrayFlagsBeforeHelperCall, base)
  9772. m_lowererMD.LoadHelperArgument(insertBeforeInstr, baseOpnd);
  9773. m_lowererMD.LoadHelperArgument(insertBeforeInstr, arrayFlagsBeforeHelperCallOpnd);
  9774. IR::Instr *const callInstr = IR::Instr::New(Js::OpCode::Call, func);
  9775. IR::RegOpnd *const createdFirstMissingValueOpnd = IR::RegOpnd::New(TyUint8, func);
  9776. IR::AutoReuseOpnd autoReuseCreatedFirstMissingValueOpnd(createdFirstMissingValueOpnd, func);
  9777. callInstr->SetDst(createdFirstMissingValueOpnd);
  9778. insertBeforeInstr->InsertBefore(callInstr);
  9779. m_lowererMD.ChangeToHelperCall(callInstr, IR::HelperArray_Jit_OperationCreatedFirstMissingValue);
  9780. // test createdFirstMissingValue, createdFirstMissingValue
  9781. // jz $skipBailOut
  9782. InsertCompareBranch(
  9783. createdFirstMissingValueOpnd,
  9784. IR::IntConstOpnd::New(0, createdFirstMissingValueOpnd->GetType(), func, true),
  9785. Js::OpCode::BrEq_A,
  9786. skipBailOutLabel,
  9787. insertBeforeInstr);
  9788. // (Bail out with IR::BailOutOnMissingValue)
  9789. // $skipBailOut:
  9790. }
  9791. void Lowerer::LowerBoundCheck(IR::Instr *const instr)
  9792. {
  9793. Assert(instr);
  9794. Assert(instr->m_opcode == Js::OpCode::BoundCheck || instr->m_opcode == Js::OpCode::UnsignedBoundCheck);
  9795. #if DBG
  9796. if(instr->m_opcode == Js::OpCode::UnsignedBoundCheck)
  9797. {
  9798. // UnsignedBoundCheck is currently only supported for the pattern:
  9799. // UnsignedBoundCheck s1 <= s2 + c, where c == 0 || c == -1
  9800. Assert(instr->GetSrc1()->IsRegOpnd());
  9801. Assert(instr->GetSrc1()->IsInt32());
  9802. Assert(instr->GetSrc2());
  9803. Assert(!instr->GetSrc2()->IsIntConstOpnd());
  9804. if(instr->GetDst())
  9805. {
  9806. const int32 c = instr->GetDst()->AsIntConstOpnd()->AsInt32();
  9807. Assert(c == 0 || c == -1);
  9808. }
  9809. }
  9810. #endif
  9811. const IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  9812. Assert(
  9813. bailOutKind == IR::BailOutOnArrayAccessHelperCall ||
  9814. bailOutKind == IR::BailOutOnInvalidatedArrayHeadSegment ||
  9815. bailOutKind == IR::BailOutOnFailedHoistedBoundCheck ||
  9816. bailOutKind == IR::BailOutOnFailedHoistedLoopCountBasedBoundCheck);
  9817. IR::LabelInstr *const skipBailOutLabel = instr->GetOrCreateContinueLabel(false);
  9818. LowerOneBailOutKind(instr, bailOutKind, false);
  9819. Assert(!instr->HasBailOutInfo());
  9820. IR::Instr *insertBeforeInstr = instr->m_next;
  9821. #if DBG
  9822. const auto VerifyLeftOrRightOpnd = [&](IR::Opnd *const opnd, const bool isRightOpnd)
  9823. {
  9824. if(!opnd)
  9825. {
  9826. Assert(isRightOpnd);
  9827. return;
  9828. }
  9829. if(opnd->IsIntConstOpnd())
  9830. {
  9831. Assert(!isRightOpnd || opnd->AsIntConstOpnd()->GetValue() != 0);
  9832. return;
  9833. }
  9834. Assert(opnd->GetType() == TyInt32 || opnd->GetType() == TyUint32);
  9835. };
  9836. #endif
  9837. // left <= right + offset (src1 <= src2 + dst)
  9838. IR::Opnd *leftOpnd = instr->UnlinkSrc1();
  9839. DebugOnly(VerifyLeftOrRightOpnd(leftOpnd, false));
  9840. IR::Opnd *rightOpnd = instr->UnlinkSrc2();
  9841. DebugOnly(VerifyLeftOrRightOpnd(rightOpnd, true));
  9842. Assert(!leftOpnd->IsIntConstOpnd() || rightOpnd && !rightOpnd->IsIntConstOpnd());
  9843. IR::IntConstOpnd *offsetOpnd = instr->GetDst() ? instr->UnlinkDst()->AsIntConstOpnd() : nullptr;
  9844. Assert(!offsetOpnd || offsetOpnd->GetValue() != 0);
  9845. const bool doUnsignedCompare = instr->m_opcode == Js::OpCode::UnsignedBoundCheck;
  9846. instr->Remove();
  9847. Func *const func = insertBeforeInstr->m_func;
  9848. IntConstType offset = offsetOpnd ? offsetOpnd->GetValue() : 0;
  9849. Js::OpCode compareOpCode = Js::OpCode::BrLe_A;
  9850. if(leftOpnd->IsIntConstOpnd() && rightOpnd->IsRegOpnd() && offset != IntConstMin)
  9851. {
  9852. // Put the constants together: swap the operands, negate the offset, and invert the branch
  9853. IR::Opnd *const tempOpnd = leftOpnd;
  9854. leftOpnd = rightOpnd;
  9855. rightOpnd = tempOpnd;
  9856. offset = -offset;
  9857. compareOpCode = Js::OpCode::BrGe_A;
  9858. }
  9859. if(rightOpnd->IsIntConstOpnd())
  9860. {
  9861. // Try to aggregate right + offset into a constant offset
  9862. IntConstType newOffset;
  9863. if(!IntConstMath::Add(offset, rightOpnd->AsIntConstOpnd()->GetValue(), &newOffset))
  9864. {
  9865. offset = newOffset;
  9866. rightOpnd = nullptr;
  9867. offsetOpnd = nullptr;
  9868. }
  9869. }
  9870. // Determine if the Add for (right + offset) is necessary, and the op code that will be used for the comparison
  9871. IR::AutoReuseOpnd autoReuseAddResultOpnd;
  9872. if(offset == -1 && compareOpCode == Js::OpCode::BrLe_A)
  9873. {
  9874. offset = 0;
  9875. compareOpCode = Js::OpCode::BrLt_A;
  9876. }
  9877. else if(offset == 1 && compareOpCode == Js::OpCode::BrGe_A)
  9878. {
  9879. offset = 0;
  9880. compareOpCode = Js::OpCode::BrGt_A;
  9881. }
  9882. else if(offset != 0 && rightOpnd)
  9883. {
  9884. // Need to Add (right + offset). If it overflows, bail out.
  9885. IR::LabelInstr *const bailOutLabel = insertBeforeInstr->m_prev->GetOrCreateContinueLabel(true);
  9886. insertBeforeInstr = bailOutLabel;
  9887. // mov temp, right
  9888. // add temp, offset
  9889. // jo $bailOut
  9890. // $bailOut: (insertBeforeInstr)
  9891. Assert(!offsetOpnd || offsetOpnd->GetValue() == offset);
  9892. IR::RegOpnd *const addResultOpnd = IR::RegOpnd::New(TyMachReg, func);
  9893. autoReuseAddResultOpnd.Initialize(addResultOpnd, func);
  9894. InsertAdd(
  9895. true,
  9896. addResultOpnd,
  9897. rightOpnd,
  9898. offsetOpnd ? offsetOpnd : IR::IntConstOpnd::New(offset, TyMachReg, func, true),
  9899. insertBeforeInstr);
  9900. InsertBranch(LowererMD::MDOverflowBranchOpcode, bailOutLabel, insertBeforeInstr);
  9901. rightOpnd = addResultOpnd;
  9902. }
  9903. // cmp left, right
  9904. // jl[e] $skipBailOut
  9905. // $bailOut:
  9906. if(!rightOpnd)
  9907. {
  9908. rightOpnd = IR::IntConstOpnd::New(offset, TyInt32, func, true);
  9909. }
  9910. InsertCompareBranch(leftOpnd, rightOpnd, compareOpCode, doUnsignedCompare, skipBailOutLabel, insertBeforeInstr);
  9911. }
  9912. IR::Instr *
  9913. Lowerer::LowerBailTarget(IR::Instr * instr)
  9914. {
  9915. // this is just a bailout target, just skip over it and generate a label before so other bailout can jump here.
  9916. IR::Instr * prevInstr = instr->m_prev;
  9917. IR::LabelInstr * continueLabelInstr = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  9918. instr->InsertAfter(continueLabelInstr);
  9919. IR::BranchInstr * skipInstr = IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, continueLabelInstr, this->m_func);
  9920. instr->InsertBefore(skipInstr);
  9921. this->GenerateBailOut(instr);
  9922. return prevInstr;
  9923. }
  9924. IR::Instr *
  9925. Lowerer::SplitBailOnImplicitCall(IR::Instr *& instr)
  9926. {
  9927. Assert(instr->IsPlainInstr() || instr->IsProfiledInstr());
  9928. const auto bailOutKind = instr->GetBailOutKind();
  9929. Assert(
  9930. BailOutInfo::IsBailOutOnImplicitCalls(bailOutKind) ||
  9931. bailOutKind == IR::BailOutOnLossyToInt32ImplicitCalls ||
  9932. bailOutKind == IR::BailOutExpectingObject);
  9933. IR::Opnd * implicitCallFlags = this->GetImplicitCallFlagsOpnd();
  9934. const IR::AutoReuseOpnd autoReuseImplicitCallFlags(implicitCallFlags, instr->m_func);
  9935. IR::IntConstOpnd * noImplicitCall = IR::IntConstOpnd::New(Js::ImplicitCall_None, TyInt8, this->m_func, true);
  9936. const IR::AutoReuseOpnd autoReuseNoImplicitCall(noImplicitCall, instr->m_func);
  9937. // Reset the implicit call flag on every helper call
  9938. LowererMD::CreateAssign(implicitCallFlags, noImplicitCall, instr);
  9939. IR::Instr *disableImplicitCallsInstr = nullptr, *enableImplicitCallsInstr = nullptr;
  9940. if(bailOutKind == IR::BailOutOnLossyToInt32ImplicitCalls ||
  9941. bailOutKind == IR::BailOutOnImplicitCallsPreOp)
  9942. {
  9943. const auto disableImplicitCallAddress =
  9944. m_lowererMD.GenerateMemRef(
  9945. instr->m_func->GetScriptContext()->GetThreadContext()->GetAddressOfDisableImplicitFlags(),
  9946. TyInt8,
  9947. instr);
  9948. // Disable implicit calls since they will be called after bailing out
  9949. disableImplicitCallsInstr =
  9950. IR::Instr::New(
  9951. Js::OpCode::Ld_A,
  9952. disableImplicitCallAddress,
  9953. IR::IntConstOpnd::New(
  9954. // LossyToInt32 is a special case where we need to disable exceptions because the helper can throw where the interpreter wouldn't
  9955. bailOutKind == IR::BailOutOnLossyToInt32ImplicitCalls ? DisableImplicitCallAndExceptionFlag : DisableImplicitCallFlag,
  9956. TyInt8, instr->m_func, true),
  9957. instr->m_func);
  9958. instr->InsertBefore(disableImplicitCallsInstr);
  9959. // Create instruction for re-enabling implicit calls
  9960. enableImplicitCallsInstr =
  9961. IR::Instr::New(
  9962. Js::OpCode::Ld_A,
  9963. disableImplicitCallAddress,
  9964. IR::IntConstOpnd::New(DisableImplicitNoFlag, TyInt8, instr->m_func, true),
  9965. instr->m_func);
  9966. }
  9967. IR::Instr * bailOutInstr = instr;
  9968. instr = IR::Instr::New(instr->m_opcode, instr->m_func);
  9969. bailOutInstr->TransferTo(instr);
  9970. bailOutInstr->InsertBefore(instr);
  9971. if(disableImplicitCallsInstr)
  9972. {
  9973. // Re-enable implicit calls
  9974. Assert(enableImplicitCallsInstr);
  9975. bailOutInstr->InsertBefore(enableImplicitCallsInstr);
  9976. // Lower both instructions. Lowering an instruction may free the instruction's original operands, so do that last.
  9977. LowererMD::ChangeToAssign(disableImplicitCallsInstr);
  9978. LowererMD::ChangeToAssign(enableImplicitCallsInstr);
  9979. }
  9980. bailOutInstr->m_opcode = Js::OpCode::BailOnNotEqual;
  9981. bailOutInstr->SetSrc1(implicitCallFlags);
  9982. bailOutInstr->SetSrc2(noImplicitCall);
  9983. return bailOutInstr;
  9984. }
  9985. IR::Instr *
  9986. Lowerer::SplitBailOnImplicitCall(IR::Instr * instr, IR::Instr * helperCall, IR::Instr * insertBeforeInstr)
  9987. {
  9988. IR::Opnd * implicitCallFlags = this->GetImplicitCallFlagsOpnd();
  9989. const IR::AutoReuseOpnd autoReuseImplicitCallFlags(implicitCallFlags, instr->m_func);
  9990. IR::IntConstOpnd * noImplicitCall = IR::IntConstOpnd::New(Js::ImplicitCall_None, TyInt8, this->m_func, true);
  9991. const IR::AutoReuseOpnd autoReuseNoImplicitCall(noImplicitCall, instr->m_func);
  9992. // Reset the implicit call flag on every helper call
  9993. LowererMD::CreateAssign(implicitCallFlags, noImplicitCall, helperCall->m_prev);
  9994. BailOutInfo * bailOutInfo = instr->GetBailOutInfo();
  9995. if (bailOutInfo->bailOutInstr == instr)
  9996. {
  9997. bailOutInfo->bailOutInstr = nullptr;
  9998. }
  9999. IR::Instr * bailOutInstr = IR::BailOutInstr::New(Js::OpCode::BailOnNotEqual, IR::BailOutOnImplicitCalls, bailOutInfo, bailOutInfo->bailOutFunc);
  10000. bailOutInstr->SetSrc1(implicitCallFlags);
  10001. bailOutInstr->SetSrc2(noImplicitCall);
  10002. insertBeforeInstr->InsertBefore(bailOutInstr);
  10003. instr->ClearBailOutInfo();
  10004. return bailOutInstr;
  10005. }
  10006. // Split out bailout for debugger into separate bailout instr out of real instr which has bailout for debugger.
  10007. // Returns the instr which needs to lower next, which would normally be last of splitted instr.
  10008. // IR on input:
  10009. // - Real instr with BailOutInfo but it's opcode is not BailForDebugger.
  10010. // - debugger bailout is not shared. In this case we'll have debugger bailout in instr->GetBailOutKind().
  10011. // - debugger bailout is shared. In this case we'll have debugger bailout in instr->GetAuxBailOutKind().
  10012. // IR on output:
  10013. // - Either of:
  10014. // - real instr, then debuggerBailout -- in case we only had debugger bailout.
  10015. // - real instr with BailOutInfo w/o debugger bailout, then debuggerBailout, then sharedBailout -- in case bailout for debugger was shared w/some other b.o.
  10016. IR::Instr* Lowerer::SplitBailForDebugger(IR::Instr* instr)
  10017. {
  10018. Assert(m_func->IsJitInDebugMode() && instr->m_opcode != Js::OpCode::BailForDebugger);
  10019. IR::BailOutKind debuggerBailOutKind; // Used for splitted instr.
  10020. BailOutInfo* bailOutInfo = instr->GetBailOutInfo();
  10021. IR::Instr* sharedBailoutInstr = nullptr;
  10022. if (instr->GetBailOutKind() & IR::BailOutForDebuggerBits)
  10023. {
  10024. // debugger bailout is not shared.
  10025. Assert(!instr->HasAuxBailOut());
  10026. AssertMsg(!(instr->GetBailOutKind() & ~IR::BailOutForDebuggerBits), "There should only be debugger bailout bits in the instr.");
  10027. debuggerBailOutKind = instr->GetBailOutKind() & IR::BailOutForDebuggerBits;
  10028. // There is no non-debugger bailout in the instr, still can't clear bailout info, as we use it for the splitted instr,
  10029. // but we need to mark the bailout as hasn't been generated yet.
  10030. if (bailOutInfo->bailOutInstr == instr)
  10031. {
  10032. // null will be picked up by following BailOutInstr::New which will change it to new bailout instr.
  10033. bailOutInfo->bailOutInstr = nullptr;
  10034. }
  10035. // Remove bailout info from the original instr which from now on becomes just regular instr, w/o deallocating bailout info.
  10036. instr->ClearBailOutInfo();
  10037. }
  10038. else if (instr->IsBranchInstr() && instr->HasBailOutInfo() && instr->HasAuxBailOut())
  10039. {
  10040. // Branches with shared bailout are lowered in LowerCondBranchCheckBailOut,
  10041. // can't do here because we need to use BranchBailOutRecord but don't know which BrTrue/BrFalse to use for it.
  10042. debuggerBailOutKind = IR::BailOutInvalid;
  10043. }
  10044. else if (instr->HasAuxBailOut() && instr->GetAuxBailOutKind() & IR::BailOutForDebuggerBits)
  10045. {
  10046. // debugger bailout is shared.
  10047. AssertMsg(!(instr->GetBailOutKind() & IR::BailOutForDebuggerBits), "There should be no debugger bits in main bailout kind.");
  10048. debuggerBailOutKind = instr->GetAuxBailOutKind() & IR::BailOutForDebuggerBits;
  10049. // This will insert SharedBail instr after current instr and set bailOutInfo->bailOutInstr to the shared one.
  10050. sharedBailoutInstr = instr->ShareBailOut();
  10051. // As we extracted aux bail out, invalidate all tracks of it in the instr.
  10052. instr->ResetAuxBailOut();
  10053. }
  10054. else
  10055. {
  10056. AssertMsg(FALSE, "shouldn't get here");
  10057. debuggerBailOutKind = IR::BailOutInvalid;
  10058. }
  10059. if (debuggerBailOutKind != IR::BailOutInvalid)
  10060. {
  10061. IR::BailOutInstr* debuggerBailoutInstr = IR::BailOutInstr::New(
  10062. Js::OpCode::BailForDebugger, debuggerBailOutKind, bailOutInfo, bailOutInfo->bailOutFunc);
  10063. instr->InsertAfter(debuggerBailoutInstr);
  10064. // Since we go backwards, we need to process extracted out bailout for debugger first.
  10065. instr = sharedBailoutInstr ? sharedBailoutInstr : debuggerBailoutInstr;
  10066. }
  10067. return instr;
  10068. }
  10069. IR::Instr *
  10070. Lowerer::SplitBailOnResultCondition(IR::Instr *const instr) const
  10071. {
  10072. Assert(instr);
  10073. Assert(!instr->IsLowered());
  10074. Assert(
  10075. instr->GetBailOutKind() & IR::BailOutOnResultConditions ||
  10076. instr->GetBailOutKind() == IR::BailOutOnFailedHoistedLoopCountBasedBoundCheck);
  10077. const auto nonBailOutInstr = IR::Instr::New(instr->m_opcode, instr->m_func);
  10078. instr->TransferTo(nonBailOutInstr);
  10079. instr->InsertBefore(nonBailOutInstr);
  10080. return nonBailOutInstr;
  10081. }
  10082. void
  10083. Lowerer::LowerBailOnResultCondition(
  10084. IR::Instr *const instr,
  10085. IR::LabelInstr * *const bailOutLabel,
  10086. IR::LabelInstr * *const skipBailOutLabel)
  10087. {
  10088. Assert(instr);
  10089. Assert(
  10090. instr->GetBailOutKind() & IR::BailOutOnResultConditions ||
  10091. instr->GetBailOutKind() == IR::BailOutOnFailedHoistedLoopCountBasedBoundCheck);
  10092. Assert(bailOutLabel);
  10093. Assert(skipBailOutLabel);
  10094. // Label to jump to (or fall through to) when bailing out. The actual bailout label
  10095. // (bailOutInfo->bailOutInstr->AsLabelInstr()) may be shared, and code may be added to restore values before the jump to the
  10096. // actual bailout label in the cloned bailout case, so always create a new bailout label for this particular path.
  10097. *bailOutLabel = IR::LabelInstr::New(Js::OpCode::Label, instr->m_func, true /* isOpHelper */);
  10098. instr->InsertBefore(*bailOutLabel);
  10099. // Label to jump to when not bailing out
  10100. *skipBailOutLabel = IR::LabelInstr::New(Js::OpCode::Label, instr->m_func);
  10101. instr->InsertAfter(*skipBailOutLabel);
  10102. // Generate the bailout helper call. 'instr' will be changed to the CALL into the bailout function, so it can't be used for
  10103. // ordering instructions anymore.
  10104. GenerateBailOut(instr);
  10105. }
  10106. void
  10107. Lowerer::PreserveSourcesForBailOnResultCondition(IR::Instr *const instr, IR::LabelInstr *const skipBailOutLabel) const
  10108. {
  10109. Assert(instr);
  10110. Assert(!instr->IsLowered());
  10111. Assert(!instr->HasBailOutInfo());
  10112. // Since this instruction may bail out, writing to the destination cannot overwrite one of the sources, or we may lose one
  10113. // of the sources needed to redo the equivalent byte code instruction. Determine if the sources need to be preserved.
  10114. const auto dst = instr->GetDst();
  10115. Assert(dst);
  10116. const auto dstStackSym = dst->GetStackSym();
  10117. if(!dstStackSym || !dstStackSym->HasByteCodeRegSlot())
  10118. {
  10119. // We only need to ensure that a byte-code source is not being overwritten
  10120. return;
  10121. }
  10122. switch(instr->m_opcode)
  10123. {
  10124. // The sources of these instructions don't need restoring, or will be restored in the bailout path
  10125. case Js::OpCode::Neg_I4:
  10126. // In case of overflow or zero, the result is the same as the operand
  10127. case Js::OpCode::Add_I4:
  10128. case Js::OpCode::Sub_I4:
  10129. // In case of overflow, there is always enough information to restore the operands
  10130. return;
  10131. }
  10132. Assert(instr->GetSrc1());
  10133. if(!dst->IsEqual(instr->GetSrc1()) && !(instr->GetSrc2() && dst->IsEqual(instr->GetSrc2())))
  10134. {
  10135. // The destination is different from the sources
  10136. return;
  10137. }
  10138. // The destination is the same as one of the sources and the original sources cannot be restored after the instruction, so
  10139. // use a temporary destination for the result and move it back to the original destination after deciding not to bail out
  10140. LowererMD::ChangeToAssign(instr->SinkDst(Js::OpCode::Ld_I4, RegNOREG, skipBailOutLabel));
  10141. }
  10142. void
  10143. Lowerer::LowerInstrWithBailOnResultCondition(
  10144. IR::Instr *const instr,
  10145. const IR::BailOutKind bailOutKind,
  10146. IR::LabelInstr *const bailOutLabel,
  10147. IR::LabelInstr *const skipBailOutLabel) const
  10148. {
  10149. Assert(instr);
  10150. Assert(!instr->IsLowered());
  10151. Assert(!instr->HasBailOutInfo());
  10152. Assert(bailOutKind & IR::BailOutOnResultConditions || bailOutKind == IR::BailOutOnFailedHoistedLoopCountBasedBoundCheck);
  10153. Assert(bailOutLabel);
  10154. Assert(instr->m_next == bailOutLabel);
  10155. Assert(skipBailOutLabel);
  10156. // Preserve sources that are overwritten by the instruction if needed
  10157. PreserveSourcesForBailOnResultCondition(instr, skipBailOutLabel);
  10158. // Lower the instruction
  10159. switch(instr->m_opcode)
  10160. {
  10161. case Js::OpCode::Neg_I4:
  10162. LowererMD::LowerInt4NegWithBailOut(instr, bailOutKind, bailOutLabel, skipBailOutLabel);
  10163. break;
  10164. case Js::OpCode::Add_I4:
  10165. LowererMD::LowerInt4AddWithBailOut(instr, bailOutKind, bailOutLabel, skipBailOutLabel);
  10166. break;
  10167. case Js::OpCode::Sub_I4:
  10168. LowererMD::LowerInt4SubWithBailOut(instr, bailOutKind, bailOutLabel, skipBailOutLabel);
  10169. break;
  10170. case Js::OpCode::Mul_I4:
  10171. LowererMD::LowerInt4MulWithBailOut(instr, bailOutKind, bailOutLabel, skipBailOutLabel);
  10172. break;
  10173. case Js::OpCode::Rem_I4:
  10174. m_lowererMD.LowerInt4RemWithBailOut(instr, bailOutKind, bailOutLabel, skipBailOutLabel);
  10175. break;
  10176. default:
  10177. Assert(false); // not implemented
  10178. __assume(false);
  10179. }
  10180. }
  10181. void
  10182. Lowerer::GenerateObjectTestAndTypeLoad(IR::Instr *instrLdSt, IR::RegOpnd *opndBase, IR::RegOpnd *opndType, IR::LabelInstr *labelHelper)
  10183. {
  10184. IR::IndirOpnd *opndIndir;
  10185. if (!opndBase->IsNotTaggedValue())
  10186. {
  10187. m_lowererMD.GenerateObjectTest(opndBase, instrLdSt, labelHelper);
  10188. }
  10189. opndIndir = IR::IndirOpnd::New(opndBase, Js::RecyclableObject::GetOffsetOfType(), TyMachReg, this->m_func);
  10190. m_lowererMD.CreateAssign(opndType, opndIndir, instrLdSt);
  10191. }
  10192. IR::LabelInstr *
  10193. Lowerer::GenerateBailOut(IR::Instr * instr, IR::BranchInstr * branchInstr, IR::LabelInstr *bailOutLabel)
  10194. {
  10195. BailOutInfo * bailOutInfo = instr->GetBailOutInfo();
  10196. IR::Instr * bailOutInstr = bailOutInfo->bailOutInstr;
  10197. IR::LabelInstr *collectRuntimeStatsLabel = nullptr;
  10198. if (instr->IsCloned())
  10199. {
  10200. Assert(bailOutInstr != instr);
  10201. // jump to the cloned bail out label
  10202. IR::LabelInstr * bailOutLabelInstr = bailOutInstr->AsLabelInstr();
  10203. IR::BranchInstr * bailOutBranch = IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, bailOutLabelInstr, this->m_func);
  10204. instr->InsertBefore(bailOutBranch);
  10205. instr->Remove();
  10206. return bailOutLabel;
  10207. }
  10208. if (bailOutInstr != instr)
  10209. {
  10210. // this bailOutInfo is shared, just jump to the bailout target
  10211. // Add helper label to trigger layout.
  10212. collectRuntimeStatsLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  10213. instr->InsertBefore(collectRuntimeStatsLabel);
  10214. IR::MemRefOpnd *pIndexOpndForBailOutKind =
  10215. IR::MemRefOpnd::New((BYTE*)bailOutInfo->bailOutRecord + BailOutRecord::GetOffsetOfBailOutKind(), TyUint32, this->m_func, IR::AddrOpndKindDynamicBailOutKindRef);
  10216. m_lowererMD.CreateAssign(
  10217. pIndexOpndForBailOutKind, IR::IntConstOpnd::New(instr->GetBailOutKind(), pIndexOpndForBailOutKind->GetType(), this->m_func), instr);
  10218. // No point in doing this for BailOutFailedEquivalentTypeCheck or BailOutFailedEquivalentFixedFieldTypeCheck,
  10219. // because the respective inline cache is already polymorphic, anyway.
  10220. if (instr->GetBailOutKind() == IR::BailOutFailedTypeCheck || instr->GetBailOutKind() == IR::BailOutFailedFixedFieldTypeCheck)
  10221. {
  10222. // We have a type check bailout that shares a bailout record with other instructions.
  10223. // Generate code to write the cache index into the bailout record before we jump to the call site.
  10224. Assert(bailOutInfo->polymorphicCacheIndex != (uint)-1);
  10225. Assert(bailOutInfo->bailOutRecord);
  10226. IR::MemRefOpnd *pIndexOpnd =
  10227. IR::MemRefOpnd::New((BYTE*)bailOutInfo->bailOutRecord + BailOutRecord::GetOffsetOfPolymorphicCacheIndex(), TyUint32, this->m_func);
  10228. m_lowererMD.CreateAssign(
  10229. pIndexOpnd, IR::IntConstOpnd::New(bailOutInfo->polymorphicCacheIndex, TyUint32, this->m_func), instr);
  10230. }
  10231. // GenerateBailOut should have replaced this as a label as we should have already lowered
  10232. // the main bailOutInstr.
  10233. IR::LabelInstr * bailOutTargetLabel = bailOutInstr->AsLabelInstr();
  10234. #if DBG
  10235. if (bailOutTargetLabel->m_noHelperAssert)
  10236. {
  10237. collectRuntimeStatsLabel->m_noHelperAssert = true;
  10238. }
  10239. #endif
  10240. Assert(bailOutLabel == nullptr || bailOutLabel == bailOutTargetLabel);
  10241. IR::BranchInstr * branchInstr = IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, bailOutTargetLabel, this->m_func);
  10242. instr->InsertAfter(branchInstr);
  10243. instr->Remove();
  10244. return collectRuntimeStatsLabel ? collectRuntimeStatsLabel : bailOutLabel;
  10245. }
  10246. // The bailout hasn't be generated yet.
  10247. Assert(!bailOutInstr->IsLabelInstr());
  10248. // Add helper label to trigger layout.
  10249. collectRuntimeStatsLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  10250. instr->InsertBefore(collectRuntimeStatsLabel);
  10251. // capture the condition for this bailout
  10252. if (bailOutLabel == nullptr)
  10253. {
  10254. // Create a label and place it in the bailout info so that shared bailout point can jump to this one
  10255. if (instr->m_prev->IsLabelInstr())
  10256. {
  10257. bailOutLabel = instr->m_prev->AsLabelInstr();
  10258. Assert(bailOutLabel->isOpHelper);
  10259. }
  10260. else
  10261. {
  10262. bailOutLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  10263. instr->InsertBefore(bailOutLabel);
  10264. }
  10265. }
  10266. else
  10267. {
  10268. instr->InsertBefore(bailOutLabel);
  10269. }
  10270. #if DBG
  10271. if (bailOutInstr->m_opcode == Js::OpCode::BailOnNoSimdTypeSpec || bailOutInstr->m_opcode == Js::OpCode::BailOnNoProfile || bailOutInstr->m_opcode == Js::OpCode::BailOnException || bailOutInstr->m_opcode == Js::OpCode::Yield)
  10272. {
  10273. bailOutLabel->m_noHelperAssert = true;
  10274. }
  10275. #endif
  10276. bailOutInfo->bailOutInstr = bailOutLabel;
  10277. bailOutLabel->m_hasNonBranchRef = true;
  10278. // Create the bail out record
  10279. Assert(bailOutInfo->bailOutRecord == nullptr);
  10280. BailOutRecord * bailOutRecord;
  10281. IR::JnHelperMethod helperMethod;
  10282. if (branchInstr != nullptr)
  10283. {
  10284. Assert(branchInstr->GetSrc2() == nullptr);
  10285. Assert(branchInstr->GetDst() == nullptr);
  10286. IR::LabelInstr * targetLabel = branchInstr->GetTarget();
  10287. Assert(targetLabel->GetByteCodeOffset() != Js::Constants::NoByteCodeOffset);
  10288. uint32 trueOffset;
  10289. uint32 falseOffset;
  10290. IR::Opnd *condOpnd = branchInstr->GetSrc1();
  10291. bool invertTarget = (branchInstr->m_opcode == Js::OpCode::BrFalse_A);
  10292. if (bailOutInfo->isInvertedBranch)
  10293. {
  10294. // Flip the condition
  10295. IR::Instr *subInstr = IR::Instr::New(Js::OpCode::Sub_I4, condOpnd, condOpnd, IR::IntConstOpnd::New(1, TyInt32, instr->m_func), instr->m_func);
  10296. instr->InsertBefore(subInstr);
  10297. this->m_lowererMD.EmitInt4Instr(subInstr);
  10298. // We should really do a DEC/NEG for a full 2's complement flip from 0/1 to 1/0,
  10299. // but DEC is sufficient to flip from 0/1 to -1/0, which is false/true to true/false...
  10300. //instr->InsertBefore(IR::Instr::New(Js::OpCode::Neg_I4, condOpnd, condOpnd, instr->m_func));
  10301. invertTarget = invertTarget ? false : true;
  10302. }
  10303. if (!invertTarget)
  10304. {
  10305. trueOffset = targetLabel->GetByteCodeOffset();
  10306. falseOffset = bailOutInfo->bailOutOffset;
  10307. }
  10308. else
  10309. {
  10310. falseOffset = targetLabel->GetByteCodeOffset();
  10311. trueOffset = bailOutInfo->bailOutOffset;
  10312. }
  10313. bailOutRecord = NativeCodeDataNewZ(this->m_func->GetNativeCodeDataAllocator(),
  10314. BranchBailOutRecord, trueOffset, falseOffset, branchInstr->GetByteCodeReg(), instr->GetBailOutKind(), bailOutInfo->bailOutFunc);
  10315. helperMethod = IR::HelperSaveAllRegistersAndBranchBailOut;
  10316. #ifdef _M_IX86
  10317. if(!AutoSystemInfo::Data.SSE2Available())
  10318. {
  10319. helperMethod = IR::HelperSaveAllRegistersNoSse2AndBranchBailOut;
  10320. }
  10321. #endif
  10322. // Save the condition. The register allocator will generate arguments.
  10323. bailOutInfo->branchConditionOpnd = branchInstr->GetSrc1()->Copy(branchInstr->m_func);
  10324. }
  10325. else
  10326. {
  10327. bailOutRecord = NativeCodeDataNewZ(this->m_func->GetNativeCodeDataAllocator(),
  10328. BailOutRecord, bailOutInfo->bailOutOffset, bailOutInfo->polymorphicCacheIndex, instr->GetBailOutKind(), bailOutInfo->bailOutFunc);
  10329. helperMethod = IR::HelperSaveAllRegistersAndBailOut;
  10330. #ifdef _M_IX86
  10331. if(!AutoSystemInfo::Data.SSE2Available())
  10332. {
  10333. helperMethod = IR::HelperSaveAllRegistersNoSse2AndBailOut;
  10334. }
  10335. #endif
  10336. }
  10337. // Save the bailout record. The register allocator will generate arguments.
  10338. bailOutInfo->bailOutRecord = bailOutRecord;
  10339. #if ENABLE_DEBUG_CONFIG_OPTIONS
  10340. bailOutRecord->bailOutOpcode = bailOutInfo->bailOutOpcode;
  10341. #endif
  10342. // Call the bail out wrapper
  10343. instr->m_opcode = Js::OpCode::Call;
  10344. if(instr->GetDst())
  10345. {
  10346. // To facilitate register allocation, don't assign a destination. The result will anyway go into the return register,
  10347. // but the register allocator does not need to kill that register for the call.
  10348. instr->FreeDst();
  10349. }
  10350. instr->SetSrc1(IR::HelperCallOpnd::New(helperMethod, this->m_func));
  10351. m_lowererMD.LowerCall(instr, 0);
  10352. if (bailOutInstr->GetBailOutKind() != IR::BailOutForGeneratorYield)
  10353. {
  10354. // Defer introducing the JMP to epilog until LowerPrologEpilog phase for Yield bailouts so
  10355. // that Yield does not appear to have flow out of its containing block for the RegAlloc phase.
  10356. // Yield is an unconditional bailout but we want to simulate the flow as if the Yield were
  10357. // just like a call.
  10358. GenerateJumpToEpilogForBailOut(bailOutInfo, instr);
  10359. }
  10360. return collectRuntimeStatsLabel ? collectRuntimeStatsLabel : bailOutLabel;
  10361. }
  10362. void
  10363. Lowerer::GenerateJumpToEpilogForBailOut(BailOutInfo * bailOutInfo, IR::Instr *instr)
  10364. {
  10365. IR::Instr * exitPrevInstr = this->m_func->m_exitInstr->m_prev;
  10366. // JMP to the epilog
  10367. IR::LabelInstr * exitTargetInstr;
  10368. if (exitPrevInstr->IsLabelInstr())
  10369. {
  10370. exitTargetInstr = exitPrevInstr->AsLabelInstr();
  10371. }
  10372. else
  10373. {
  10374. exitTargetInstr = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, false);
  10375. exitPrevInstr->InsertAfter(exitTargetInstr);
  10376. }
  10377. exitTargetInstr = m_lowererMD.GetBailOutStackRestoreLabel(bailOutInfo, exitTargetInstr);
  10378. IR::Instr * instrAfter = instr->m_next;
  10379. IR::BranchInstr * exitInstr = IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, exitTargetInstr, this->m_func);
  10380. instrAfter->InsertBefore(exitInstr);
  10381. }
  10382. ///----------------------------------------------------------------------------
  10383. ///
  10384. /// Lowerer::GenerateFastCondBranch
  10385. ///
  10386. ///----------------------------------------------------------------------------
  10387. bool
  10388. Lowerer::GenerateFastCondBranch(IR::BranchInstr * instrBranch, bool *pIsHelper)
  10389. {
  10390. // The idea is to do an inline compare if we can prove that both sources
  10391. // are tagged ints
  10392. //
  10393. // Given:
  10394. //
  10395. // Brxx_A $L, src1, src2
  10396. //
  10397. // Generate:
  10398. //
  10399. // (If not Int31's, goto $helper)
  10400. // Jxx $L, src1, src2
  10401. // JMP $fallthru
  10402. // $helper:
  10403. // (caller will generate normal helper call sequence)
  10404. // $fallthru:
  10405. IR::LabelInstr * labelHelper = nullptr;
  10406. IR::LabelInstr * labelFallThru;
  10407. IR::BranchInstr * instr;
  10408. IR::Opnd * opndSrc1;
  10409. IR::Opnd * opndSrc2;
  10410. opndSrc1 = instrBranch->GetSrc1();
  10411. opndSrc2 = instrBranch->GetSrc2();
  10412. AssertMsg(opndSrc1 && opndSrc2, "BrC expects 2 src operands");
  10413. // Not tagged ints?
  10414. if (opndSrc1->IsRegOpnd() && opndSrc1->AsRegOpnd()->IsNotInt())
  10415. {
  10416. return true;
  10417. }
  10418. if (opndSrc2->IsRegOpnd() && opndSrc2->AsRegOpnd()->IsNotInt())
  10419. {
  10420. return true;
  10421. }
  10422. // Tagged ints?
  10423. bool isTaggedInts = false;
  10424. if (opndSrc1->IsTaggedInt())
  10425. {
  10426. if (opndSrc2->IsTaggedInt())
  10427. {
  10428. isTaggedInts = true;
  10429. }
  10430. }
  10431. if (!isTaggedInts)
  10432. {
  10433. labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  10434. this->m_lowererMD.GenerateSmIntPairTest(instrBranch, opndSrc1, opndSrc2, labelHelper);
  10435. }
  10436. // Jxx $L, src1, src2
  10437. opndSrc1 = opndSrc1->UseWithNewType(TyInt32, this->m_func);
  10438. opndSrc2 = opndSrc2->UseWithNewType(TyInt32, this->m_func);
  10439. instr = IR::BranchInstr::New(instrBranch->m_opcode, instrBranch->GetTarget(), opndSrc1, opndSrc2, this->m_func);
  10440. instrBranch->InsertBefore(instr);
  10441. this->m_lowererMD.LowerCondBranch(instr);
  10442. if (isTaggedInts)
  10443. {
  10444. instrBranch->Remove();
  10445. // Skip lowering call to helper
  10446. return false;
  10447. }
  10448. // JMP $fallthru
  10449. IR::Instr *instrNext = instrBranch->GetNextRealInstrOrLabel();
  10450. if (instrNext->IsLabelInstr())
  10451. {
  10452. labelFallThru = instrNext->AsLabelInstr();
  10453. }
  10454. else
  10455. {
  10456. labelFallThru = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, /**pIsHelper*/FALSE);
  10457. instrBranch->InsertAfter(labelFallThru);
  10458. }
  10459. instr = IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, labelFallThru, this->m_func);
  10460. instrBranch->InsertBefore(instr);
  10461. // $helper:
  10462. // (caller will generate normal helper call sequence)
  10463. // $fallthru:
  10464. AssertMsg(labelHelper, "Should not be NULL");
  10465. instrBranch->InsertBefore(labelHelper);
  10466. *pIsHelper = true;
  10467. return true;
  10468. }
  10469. void
  10470. Lowerer::LowerInlineeStart(IR::Instr * inlineeStartInstr)
  10471. {
  10472. IR::Opnd *linkOpnd = inlineeStartInstr->GetSrc2();
  10473. if (!linkOpnd)
  10474. {
  10475. Assert(inlineeStartInstr->m_func->m_hasInlineArgsOpt);
  10476. return;
  10477. }
  10478. AssertMsg(inlineeStartInstr->m_func->firstActualStackOffset != -1, "This should have been already done in backward pass");
  10479. IR::Instr *startCall;
  10480. // Free the argOut links and lower them to MOVs
  10481. inlineeStartInstr->IterateArgInstrs([&](IR::Instr* argInstr){
  10482. Assert(argInstr->m_opcode == Js::OpCode::ArgOut_A || argInstr->m_opcode == Js::OpCode::ArgOut_A_Inline);
  10483. startCall = argInstr->GetSrc2()->GetStackSym()->m_instrDef;
  10484. argInstr->FreeSrc2();
  10485. #pragma prefast(suppress:6235, "Non-Zero Constant in Condition")
  10486. if (!PHASE_ON(Js::EliminateArgoutForInlineePhase, this->m_func) || inlineeStartInstr->m_func->GetJnFunction()->GetHasOrParentHasArguments())
  10487. {
  10488. m_lowererMD.ChangeToAssign(argInstr);
  10489. }
  10490. else
  10491. {
  10492. argInstr->m_opcode = Js::OpCode::ArgOut_A_InlineBuiltIn;
  10493. }
  10494. return false;
  10495. });
  10496. IR::Instr *argInsertInstr = inlineeStartInstr;
  10497. uint i = 0;
  10498. inlineeStartInstr->IterateMetaArgs( [&] (IR::Instr* metaArg)
  10499. {
  10500. if(i == 0)
  10501. {
  10502. LowererMD::CreateAssign(metaArg->m_func->GetNextInlineeFrameArgCountSlotOpnd(),
  10503. IR::AddrOpnd::NewNull(metaArg->m_func),
  10504. argInsertInstr);
  10505. }
  10506. if (i == Js::Constants::InlineeMetaArgIndex_FunctionObject)
  10507. {
  10508. metaArg->SetSrc1(inlineeStartInstr->GetSrc1());
  10509. }
  10510. metaArg->Unlink();
  10511. argInsertInstr->InsertBefore(metaArg);
  10512. IR::Instr* prev = metaArg->m_prev;
  10513. m_lowererMD.ChangeToAssign(metaArg);
  10514. if (i == Js::Constants::InlineeMetaArgIndex_Argc)
  10515. {
  10516. #if defined(_M_IX86) || defined(_M_X64)
  10517. Assert(metaArg == prev->m_next);
  10518. #else //defined(_M_ARM)
  10519. Assert(prev->m_next->m_opcode == Js::OpCode::LDIMM);
  10520. #endif
  10521. metaArg = prev->m_next;
  10522. Assert(metaArg->GetSrc1()->AsAddrOpnd()->m_dontEncode == true);
  10523. metaArg->isInlineeEntryInstr = true;
  10524. LowererMD::Legalize(metaArg);
  10525. }
  10526. argInsertInstr = metaArg;
  10527. i++;
  10528. return false;
  10529. });
  10530. if (inlineeStartInstr->m_func->m_hasInlineArgsOpt)
  10531. {
  10532. inlineeStartInstr->FreeSrc1();
  10533. inlineeStartInstr->FreeSrc2();
  10534. inlineeStartInstr->FreeDst();
  10535. }
  10536. else
  10537. {
  10538. inlineeStartInstr->Remove();
  10539. }
  10540. }
  10541. void
  10542. Lowerer::LowerInlineeEnd(IR::Instr *instr)
  10543. {
  10544. Assert(instr->m_func->IsInlinee());
  10545. Assert(m_func->IsTopFunc());
  10546. // No need to emit code if the function wasn't marked as having implicit calls or bailout. Dead-Store should have removed inline overhead.
  10547. if (instr->m_func->GetHasImplicitCalls() || PHASE_OFF(Js::DeadStorePhase, this->m_func))
  10548. {
  10549. LowererMD::CreateAssign(instr->m_func->GetInlineeArgCountSlotOpnd(),
  10550. IR::AddrOpnd::New(0, IR::AddrOpndKindConstantVar, instr->m_func),
  10551. instr);
  10552. }
  10553. // Keep InlineeEnd around as it is used by register allocator, if we have optimized the arguments stack
  10554. if (instr->m_func->m_hasInlineArgsOpt)
  10555. {
  10556. instr->FreeSrc1();
  10557. }
  10558. else
  10559. {
  10560. instr->Remove();
  10561. }
  10562. }
  10563. IR::Instr *
  10564. Lowerer::LoadFloatFromNonReg(IR::Opnd * opndSrc, IR::Opnd * opndDst, IR::Instr * instrInsert)
  10565. {
  10566. double value;
  10567. if (opndSrc->IsAddrOpnd())
  10568. {
  10569. Js::Var var = opndSrc->AsAddrOpnd()->m_address;
  10570. if (Js::TaggedInt::Is(var))
  10571. {
  10572. value = Js::TaggedInt::ToDouble(var);
  10573. }
  10574. else
  10575. {
  10576. value = Js::JavascriptNumber::GetValue(var);
  10577. }
  10578. }
  10579. else if (opndSrc->IsIntConstOpnd())
  10580. {
  10581. if (opndSrc->IsUInt32())
  10582. {
  10583. value = (double)(uint32)opndSrc->AsIntConstOpnd()->GetValue();
  10584. }
  10585. else
  10586. {
  10587. value = (double)opndSrc->AsIntConstOpnd()->GetValue();
  10588. }
  10589. }
  10590. else if (opndSrc->IsFloatConstOpnd())
  10591. {
  10592. value = (double)opndSrc->AsFloatConstOpnd()->m_value;
  10593. }
  10594. else
  10595. {
  10596. AssertMsg(0, "Unexpected opnd type");
  10597. value = 0;
  10598. }
  10599. return LowererMD::LoadFloatValue(opndDst, value, instrInsert);
  10600. }
  10601. void
  10602. Lowerer::LoadInt32FromUntaggedVar(IR::Instr *const instrLoad)
  10603. {
  10604. Assert(instrLoad);
  10605. Assert(instrLoad->GetDst());
  10606. Assert(instrLoad->GetDst()->IsRegOpnd());
  10607. Assert(instrLoad->GetDst()->IsInt32());
  10608. Assert(instrLoad->GetSrc1());
  10609. Assert(instrLoad->GetSrc1()->IsRegOpnd());
  10610. Assert(instrLoad->GetSrc1()->IsVar());
  10611. Assert(!instrLoad->GetSrc2());
  10612. // push src
  10613. // int32Value = call JavascriptNumber::GetNonzeroInt32Value_NoChecks
  10614. // test int32Value, int32Value
  10615. // jne $done
  10616. // (fall through to 'instrLoad'; caller will generate code here)
  10617. // $done:
  10618. // (rest of program)
  10619. Func *const func = instrLoad->m_func;
  10620. IR::LabelInstr *const doneLabel = instrLoad->GetOrCreateContinueLabel();
  10621. // push src
  10622. // int32Value = call JavascriptNumber::GetNonzeroInt32Value_NoChecks
  10623. StackSym *const int32ValueSym = instrLoad->GetDst()->AsRegOpnd()->m_sym;
  10624. IR::Instr *const instr =
  10625. IR::Instr::New(
  10626. Js::OpCode::Call,
  10627. IR::RegOpnd::New(int32ValueSym, TyInt32, func),
  10628. instrLoad->GetSrc1()->AsRegOpnd(),
  10629. func);
  10630. instrLoad->InsertBefore(instr);
  10631. LowerUnaryHelper(instr, IR::HelperGetNonzeroInt32Value_NoTaggedIntCheck);
  10632. // test int32Value, int32Value
  10633. // jne $done
  10634. InsertCompareBranch(
  10635. IR::RegOpnd::New(int32ValueSym, TyInt32, func),
  10636. IR::IntConstOpnd::New(0, TyInt32, func, true),
  10637. Js::OpCode::BrNeq_A,
  10638. doneLabel,
  10639. instrLoad);
  10640. }
  10641. bool
  10642. Lowerer::GetValueFromIndirOpnd(IR::IndirOpnd *indirOpnd, IR::Opnd **pValueOpnd, IntConstType *pValue)
  10643. {
  10644. IR::RegOpnd *indexOpnd = indirOpnd->GetIndexOpnd();
  10645. IR::Opnd* valueOpnd = nullptr;
  10646. IntConstType value = 0;
  10647. if (!indexOpnd)
  10648. {
  10649. value = (IntConstType)indirOpnd->GetOffset();
  10650. if (value < 0)
  10651. {
  10652. // Can't do fast path for negative index
  10653. return false;
  10654. }
  10655. valueOpnd = IR::IntConstOpnd::New(value, TyInt32, this->m_func);
  10656. }
  10657. else if (indexOpnd->m_sym->IsIntConst())
  10658. {
  10659. value = indexOpnd->AsRegOpnd()->m_sym->GetIntConstValue();
  10660. if (value < 0)
  10661. {
  10662. // Can't do fast path for negative index
  10663. return false;
  10664. }
  10665. valueOpnd = IR::IntConstOpnd::New(value, TyInt32, this->m_func);
  10666. }
  10667. *pValueOpnd = valueOpnd;
  10668. *pValue = value;
  10669. return true;
  10670. }
  10671. void
  10672. Lowerer::GenerateFastBrOnObject(IR::Instr *instr)
  10673. {
  10674. Assert(instr->m_opcode == Js::OpCode::BrOnObject_A);
  10675. IR::RegOpnd *object = instr->GetSrc1()->IsRegOpnd() ? instr->GetSrc1()->AsRegOpnd() : nullptr;
  10676. IR::LabelInstr *done = instr->GetOrCreateContinueLabel();
  10677. IR::LabelInstr *target = instr->AsBranchInstr()->GetTarget();
  10678. IR::RegOpnd *typeRegOpnd = IR::RegOpnd::New(TyMachReg, m_func);
  10679. IR::IntConstOpnd *typeIdOpnd = IR::IntConstOpnd::New(Js::TypeIds_LastJavascriptPrimitiveType, TyInt32, instr->m_func);
  10680. if (!object)
  10681. {
  10682. object = IR::RegOpnd::New(TyVar, m_func);
  10683. LowererMD::CreateAssign(object, instr->GetSrc1(), instr);
  10684. }
  10685. // TEST object, 1
  10686. // JNE $done
  10687. // MOV typeRegOpnd, [object + offset(Type)]
  10688. // CMP [typeRegOpnd + offset(TypeId)], TypeIds_LastJavascriptPrimitiveType
  10689. // JGT $target
  10690. // $done:
  10691. m_lowererMD.GenerateObjectTest(object, instr, done);
  10692. InsertMove(typeRegOpnd,
  10693. IR::IndirOpnd::New(object, Js::RecyclableObject::GetOffsetOfType(), TyMachReg, m_func),
  10694. instr);
  10695. InsertCompareBranch(
  10696. IR::IndirOpnd::New(typeRegOpnd, Js::Type::GetOffsetOfTypeId(), TyInt32, m_func),
  10697. typeIdOpnd, Js::OpCode::BrGt_A, target, instr);
  10698. instr->Remove();
  10699. }
  10700. void Lowerer::GenerateObjectHeaderInliningTest(IR::RegOpnd *baseOpnd, IR::LabelInstr * target,IR::Instr *insertBeforeInstr)
  10701. {
  10702. Assert(baseOpnd);
  10703. Assert(target);
  10704. AssertMsg(
  10705. baseOpnd->GetValueType().IsLikelyObject() &&
  10706. baseOpnd->GetValueType().GetObjectType() == ObjectType::ObjectWithArray,
  10707. "Why are we here, when the object is already known not to have an ObjArray");
  10708. Assert(insertBeforeInstr);
  10709. Func *const func = insertBeforeInstr->m_func;
  10710. // mov type, [base + offsetOf(type)]
  10711. IR::RegOpnd *const opnd = IR::RegOpnd::New(TyMachPtr, func);
  10712. m_lowererMD.CreateAssign(
  10713. opnd,
  10714. IR::IndirOpnd::New(
  10715. baseOpnd,
  10716. Js::DynamicObject::GetOffsetOfType(),
  10717. opnd->GetType(),
  10718. func),
  10719. insertBeforeInstr);
  10720. // mov typeHandler, [type + offsetOf(typeHandler)]
  10721. m_lowererMD.CreateAssign(
  10722. opnd,
  10723. IR::IndirOpnd::New(
  10724. opnd,
  10725. Js::DynamicType::GetOffsetOfTypeHandler(),
  10726. opnd->GetType(),
  10727. func),
  10728. insertBeforeInstr);
  10729. IR::IndirOpnd * offsetOfInlineSlotOpnd = IR::IndirOpnd::New(opnd,Js::DynamicTypeHandler::GetOffsetOfOffsetOfInlineSlots(), TyInt16, func);
  10730. IR::IntConstOpnd * objHeaderInlinedSlotOffset = IR::IntConstOpnd::New(Js::DynamicTypeHandler::GetOffsetOfObjectHeaderInlineSlots(), TyInt16, func);
  10731. // CMP [typeHandler + offsetOf(offsetOfInlineSlots)], objHeaderInlinedSlotOffset
  10732. InsertCompareBranch(
  10733. offsetOfInlineSlotOpnd,
  10734. objHeaderInlinedSlotOffset,
  10735. Js::OpCode::BrEq_A,
  10736. target,
  10737. insertBeforeInstr);
  10738. }
  10739. void Lowerer::GenerateObjectTypeTest(IR::RegOpnd *srcReg, IR::Instr *instrInsert, IR::LabelInstr *labelHelper)
  10740. {
  10741. Assert(srcReg);
  10742. if (!srcReg->IsNotTaggedValue())
  10743. {
  10744. m_lowererMD.GenerateObjectTest(srcReg, instrInsert, labelHelper);
  10745. }
  10746. // CMP [srcReg], Js::DynamicObject::`vtable'
  10747. // JNE $helper
  10748. InsertCompareBranch(
  10749. IR::IndirOpnd::New(srcReg, 0, TyMachPtr, m_func),
  10750. LoadVTableValueOpnd(instrInsert, VTableValue::VtableDynamicObject),
  10751. Js::OpCode::BrNeq_A,
  10752. labelHelper,
  10753. instrInsert);
  10754. }
  10755. const VTableValue Lowerer::VtableAddresses[static_cast<ValueType::TSize>(ObjectType::Count)] =
  10756. {
  10757. /* ObjectType::UninitializedObject */ VTableValue::VtableInvalid,
  10758. /* ObjectType::Object */ VTableValue::VtableInvalid,
  10759. /* ObjectType::RegExp */ VTableValue::VtableInvalid,
  10760. /* ObjectType::ObjectWithArray */ VTableValue::VtableJavascriptArray,
  10761. /* ObjectType::Array */ VTableValue::VtableJavascriptArray,
  10762. /* ObjectType::Int8Array */ VTableValue::VtableInt8Array,
  10763. /* ObjectType::Uint8Array */ VTableValue::VtableUint8Array,
  10764. /* ObjectType::Uint8ClampedArray */ VTableValue::VtableUint8ClampedArray,
  10765. /* ObjectType::Int16Array */ VTableValue::VtableInt16Array,
  10766. /* ObjectType::Uint16Array */ VTableValue::VtableUint16Array,
  10767. /* ObjectType::Int32Array */ VTableValue::VtableInt32Array,
  10768. /* ObjectType::Uint32Array */ VTableValue::VtableUint32Array,
  10769. /* ObjectType::Float32Array */ VTableValue::VtableFloat32Array,
  10770. /* ObjectType::Float64Array */ VTableValue::VtableFloat64Array,
  10771. /* ObjectType::Int8VirtualArray */ VTableValue::VtableInt8VirtualArray,
  10772. /* ObjectType::Uint8VirtualArray */ VTableValue::VtableUint8VirtualArray,
  10773. /* ObjectType::Uint8ClampedVirtualArray */ VTableValue::VtableUint8ClampedVirtualArray,
  10774. /* ObjectType::Int16VirtualArray */ VTableValue::VtableInt16VirtualArray,
  10775. /* ObjectType::Uint16VirtualArray */ VTableValue::VtableUint16VirtualArray,
  10776. /* ObjectType::Int32VirtualArray */ VTableValue::VtableInt32VirtualArray,
  10777. /* ObjectType::Uint32VirtualArray */ VTableValue::VtableUint32VirtualArray,
  10778. /* ObjectType::Float32VirtualArray */ VTableValue::VtableFloat32VirtualArray,
  10779. /* ObjectType::Float64VirtualArray */ VTableValue::VtableFloat64VirtualArray,
  10780. /* ObjectType::Int8MixedArray */ VTableValue::VtableInt8Array,
  10781. /* ObjectType::Uint8MixedArray */ VTableValue::VtableUint8Array,
  10782. /* ObjectType::Uint8ClampedMixedArray */ VTableValue::VtableUint8ClampedArray,
  10783. /* ObjectType::Int16MixedArray */ VTableValue::VtableInt16Array,
  10784. /* ObjectType::Uint16MixedArray */ VTableValue::VtableUint16Array,
  10785. /* ObjectType::Int32MixedArray */ VTableValue::VtableInt32Array,
  10786. /* ObjectType::Uint32MixedArray */ VTableValue::VtableUint32Array,
  10787. /* ObjectType::Float32MixedArray */ VTableValue::VtableFloat32Array,
  10788. /* ObjectType::Float64MixedArray */ VTableValue::VtableFloat64Array,
  10789. /* ObjectType::Int64Array */ VTableValue::VtableInt64Array,
  10790. /* ObjectType::Uint64Array */ VTableValue::VtableUint64Array,
  10791. /* ObjectType::BoolArray */ VTableValue::VtableBoolArray,
  10792. /* ObjectType::CharArray */ VTableValue::VtableCharArray
  10793. };
  10794. const uint32 Lowerer::OffsetsOfHeadSegment[static_cast<ValueType::TSize>(ObjectType::Count)] =
  10795. {
  10796. /* ObjectType::UninitializedObject */ static_cast<uint32>(-1),
  10797. /* ObjectType::Object */ static_cast<uint32>(-1),
  10798. /* ObjectType::RegExp */ static_cast<uint32>(-1),
  10799. /* ObjectType::ObjectWithArray */ Js::JavascriptArray::GetOffsetOfHead(),
  10800. /* ObjectType::Array */ Js::JavascriptArray::GetOffsetOfHead(),
  10801. /* ObjectType::Int8Array */ Js::Int8Array::GetOffsetOfBuffer(),
  10802. /* ObjectType::Uint8Array */ Js::Uint8Array::GetOffsetOfBuffer(),
  10803. /* ObjectType::Uint8ClampedArray */ Js::Uint8ClampedArray::GetOffsetOfBuffer(),
  10804. /* ObjectType::Int16Array */ Js::Int16Array::GetOffsetOfBuffer(),
  10805. /* ObjectType::Uint16Array */ Js::Uint16Array::GetOffsetOfBuffer(),
  10806. /* ObjectType::Int32Array */ Js::Int32Array::GetOffsetOfBuffer(),
  10807. /* ObjectType::Uint32Array */ Js::Uint32Array::GetOffsetOfBuffer(),
  10808. /* ObjectType::Float32Array */ Js::Float32Array::GetOffsetOfBuffer(),
  10809. /* ObjectType::Float64Array */ Js::Float64Array::GetOffsetOfBuffer(),
  10810. /* ObjectType::Int8VirtualArray */ Js::Int8VirtualArray::GetOffsetOfBuffer(),
  10811. /* ObjectType::Uint8VirtualArray */ Js::Uint8VirtualArray::GetOffsetOfBuffer(),
  10812. /* ObjectType::Uint8ClampedVirtualArray */ Js::Uint8ClampedVirtualArray::GetOffsetOfBuffer(),
  10813. /* ObjectType::Int16VirtualArray */ Js::Int16VirtualArray::GetOffsetOfBuffer(),
  10814. /* ObjectType::Uint16VirtualArray */ Js::Uint16VirtualArray::GetOffsetOfBuffer(),
  10815. /* ObjectType::Int32VirtualArray */ Js::Int32VirtualArray::GetOffsetOfBuffer(),
  10816. /* ObjectType::Uint32VirtualArray */ Js::Uint32VirtualArray::GetOffsetOfBuffer(),
  10817. /* ObjectType::Float32VirtualArray */ Js::Float32VirtualArray::GetOffsetOfBuffer(),
  10818. /* ObjectType::Float64VirtualArray */ Js::Float64VirtualArray::GetOffsetOfBuffer(),
  10819. /* ObjectType::Int8MixedArray */ Js::Int8Array::GetOffsetOfBuffer(),
  10820. /* ObjectType::Uint8MixedArray */ Js::Uint8Array::GetOffsetOfBuffer(),
  10821. /* ObjectType::Uint8ClampedMixedArray */ Js::Uint8ClampedArray::GetOffsetOfBuffer(),
  10822. /* ObjectType::Int16MixedArray */ Js::Int16Array::GetOffsetOfBuffer(),
  10823. /* ObjectType::Uint16MixedArray */ Js::Uint16Array::GetOffsetOfBuffer(),
  10824. /* ObjectType::Int32MixedArray */ Js::Int32Array::GetOffsetOfBuffer(),
  10825. /* ObjectType::Uint32MixedArray */ Js::Uint32Array::GetOffsetOfBuffer(),
  10826. /* ObjectType::Float32MixedArray */ Js::Float32Array::GetOffsetOfBuffer(),
  10827. /* ObjectType::Float64MixedArray */ Js::Float64Array::GetOffsetOfBuffer(),
  10828. /* ObjectType::Int64Array */ Js::Int64Array::GetOffsetOfBuffer(),
  10829. /* ObjectType::Uint64Array */ Js::Uint64Array::GetOffsetOfBuffer(),
  10830. /* ObjectType::BoolArray */ Js::BoolArray::GetOffsetOfBuffer(),
  10831. /* ObjectType::CharArray */ Js::CharArray::GetOffsetOfBuffer()
  10832. };
  10833. const uint32 Lowerer::OffsetsOfLength[static_cast<ValueType::TSize>(ObjectType::Count)] =
  10834. {
  10835. /* ObjectType::UninitializedObject */ static_cast<uint32>(-1),
  10836. /* ObjectType::Object */ static_cast<uint32>(-1),
  10837. /* ObjectType::RegExp */ static_cast<uint32>(-1),
  10838. /* ObjectType::ObjectWithArray */ Js::JavascriptArray::GetOffsetOfLength(),
  10839. /* ObjectType::Array */ Js::JavascriptArray::GetOffsetOfLength(),
  10840. /* ObjectType::Int8Array */ Js::Int8Array::GetOffsetOfLength(),
  10841. /* ObjectType::Uint8Array */ Js::Uint8Array::GetOffsetOfLength(),
  10842. /* ObjectType::Uint8ClampedArray */ Js::Uint8ClampedArray::GetOffsetOfLength(),
  10843. /* ObjectType::Int16Array */ Js::Int16Array::GetOffsetOfLength(),
  10844. /* ObjectType::Uint16Array */ Js::Uint16Array::GetOffsetOfLength(),
  10845. /* ObjectType::Int32Array */ Js::Int32Array::GetOffsetOfLength(),
  10846. /* ObjectType::Uint32Array */ Js::Uint32Array::GetOffsetOfLength(),
  10847. /* ObjectType::Float32Array */ Js::Float32Array::GetOffsetOfLength(),
  10848. /* ObjectType::Float64Array */ Js::Float64Array::GetOffsetOfLength(),
  10849. /* ObjectType::Int8VirtualArray */ Js::Int8VirtualArray::GetOffsetOfLength(),
  10850. /* ObjectType::Uint8VirtualArray */ Js::Uint8VirtualArray::GetOffsetOfLength(),
  10851. /* ObjectType::Uint8ClampedVirtualArray */ Js::Uint8ClampedVirtualArray::GetOffsetOfLength(),
  10852. /* ObjectType::Int16VirtualArray */ Js::Int16VirtualArray::GetOffsetOfLength(),
  10853. /* ObjectType::Uint16VirtualArray */ Js::Uint16VirtualArray::GetOffsetOfLength(),
  10854. /* ObjectType::Int32VirtualArray */ Js::Int32VirtualArray::GetOffsetOfLength(),
  10855. /* ObjectType::Uint32VirtualArray */ Js::Uint32VirtualArray::GetOffsetOfLength(),
  10856. /* ObjectType::Float32VirtualArray */ Js::Float32VirtualArray::GetOffsetOfLength(),
  10857. /* ObjectType::Float64VirtualArray */ Js::Float64VirtualArray::GetOffsetOfLength(),
  10858. /* ObjectType::Int8MixedArray */ Js::Int8Array::GetOffsetOfLength(),
  10859. /* ObjectType::Uint8MixedArray */ Js::Uint8Array::GetOffsetOfLength(),
  10860. /* ObjectType::Uint8ClampedMixedArray */ Js::Uint8ClampedArray::GetOffsetOfLength(),
  10861. /* ObjectType::Int16MixedArray */ Js::Int16Array::GetOffsetOfLength(),
  10862. /* ObjectType::Uint16MixedArray */ Js::Uint16Array::GetOffsetOfLength(),
  10863. /* ObjectType::Int32MixedArray */ Js::Int32Array::GetOffsetOfLength(),
  10864. /* ObjectType::Uint32MixedArray */ Js::Uint32Array::GetOffsetOfLength(),
  10865. /* ObjectType::Float32MixedArray */ Js::Float32Array::GetOffsetOfLength(),
  10866. /* ObjectType::Float64MixedArray */ Js::Float64Array::GetOffsetOfLength(),
  10867. /* ObjectType::Int64Array */ Js::Int64Array::GetOffsetOfLength(),
  10868. /* ObjectType::Uint64Array */ Js::Uint64Array::GetOffsetOfLength(),
  10869. /* ObjectType::BoolArray */ Js::BoolArray::GetOffsetOfLength(),
  10870. /* ObjectType::CharArray */ Js::CharArray::GetOffsetOfLength()
  10871. };
  10872. const IRType Lowerer::IndirTypes[static_cast<ValueType::TSize>(ObjectType::Count)] =
  10873. {
  10874. /* ObjectType::UninitializedObject */ TyIllegal,
  10875. /* ObjectType::Object */ TyIllegal,
  10876. /* ObjectType::RegExp */ TyIllegal,
  10877. /* ObjectType::ObjectWithArray */ TyVar,
  10878. /* ObjectType::Array */ TyVar,
  10879. /* ObjectType::Int8Array */ TyInt8,
  10880. /* ObjectType::Uint8Array */ TyUint8,
  10881. /* ObjectType::Uint8ClampedArray */ TyUint8,
  10882. /* ObjectType::Int16Array */ TyInt16,
  10883. /* ObjectType::Uint16Array */ TyUint16,
  10884. /* ObjectType::Int32Array */ TyInt32,
  10885. /* ObjectType::Uint32Array */ TyUint32,
  10886. /* ObjectType::Float32Array */ TyFloat32,
  10887. /* ObjectType::Float64Array */ TyFloat64,
  10888. /* ObjectType::Int8VirtualArray */ TyInt8,
  10889. /* ObjectType::Uint8VirtualArray */ TyUint8,
  10890. /* ObjectType::Uint8ClampedVirtualArray */ TyUint8,
  10891. /* ObjectType::Int16VirtualArray */ TyInt16,
  10892. /* ObjectType::Uint16vArray */ TyUint16,
  10893. /* ObjectType::Int32VirtualArray */ TyInt32,
  10894. /* ObjectType::Uint32VirtualArray */ TyUint32,
  10895. /* ObjectType::Float32VirtualArray */ TyFloat32,
  10896. /* ObjectType::Float64VirtualArray */ TyFloat64,
  10897. /* ObjectType::Int8MixedArray */ TyInt8,
  10898. /* ObjectType::Uint8MixedArray */ TyUint8,
  10899. /* ObjectType::Uint8ClampedMixedArray */ TyUint8,
  10900. /* ObjectType::Int16MixedArray */ TyInt16,
  10901. /* ObjectType::Uint16MixedArray */ TyUint16,
  10902. /* ObjectType::Int32MixedArray */ TyInt32,
  10903. /* ObjectType::Uint32MixedArray */ TyUint32,
  10904. /* ObjectType::Float32MixedArray */ TyFloat32,
  10905. /* ObjectType::Float64MixedArray */ TyFloat64,
  10906. /* ObjectType::Int64Array */ TyInt64,
  10907. /* ObjectType::Uint64Array */ TyUint64,
  10908. /* ObjectType::BoolArray */ TyUint8,
  10909. /* ObjectType::CharArray */ TyUint16
  10910. };
  10911. const BYTE Lowerer::IndirScales[static_cast<ValueType::TSize>(ObjectType::Count)] =
  10912. {
  10913. /* ObjectType::UninitializedObject */ static_cast<BYTE>(-1),
  10914. /* ObjectType::Object */ static_cast<BYTE>(-1),
  10915. /* ObjectType::RegExp */ static_cast<BYTE>(-1),
  10916. /* ObjectType::ObjectWithArray */ LowererMD::GetDefaultIndirScale(),
  10917. /* ObjectType::Array */ LowererMD::GetDefaultIndirScale(),
  10918. /* ObjectType::Int8Array */ 0, // log2(sizeof(int8))
  10919. /* ObjectType::Uint8Array */ 0, // log2(sizeof(uint8))
  10920. /* ObjectType::Uint8ClampedArray */ 0, // log2(sizeof(uint8))
  10921. /* ObjectType::Int16Array */ 1, // log2(sizeof(int16))
  10922. /* ObjectType::Uint16Array */ 1, // log2(sizeof(uint16))
  10923. /* ObjectType::Int32Array */ 2, // log2(sizeof(int32))
  10924. /* ObjectType::Uint32Array */ 2, // log2(sizeof(uint32))
  10925. /* ObjectType::Float32Array */ 2, // log2(sizeof(float))
  10926. /* ObjectType::Float64Array */ 3, // log2(sizeof(double))
  10927. /* ObjectType::Int8VirtualArray */ 0, // log2(sizeof(int8))
  10928. /* ObjectType::Uint8VirtualArray */ 0, // log2(sizeof(uint8))
  10929. /* ObjectType::Uint8ClampedVirtualArray */ 0, // log2(sizeof(uint8))
  10930. /* ObjectType::Int16VirtualArray */ 1, // log2(sizeof(int16))
  10931. /* ObjectType::Uint16VirtualArray */ 1, // log2(sizeof(uint16))
  10932. /* ObjectType::Int32VirtualArray */ 2, // log2(sizeof(int32))
  10933. /* ObjectType::Uint32VirtualArray */ 2, // log2(sizeof(uint32))
  10934. /* ObjectType::Float32VirtualArray */ 2, // log2(sizeof(float))
  10935. /* ObjectType::Float64VirtualArray */ 3, // log2(sizeof(double))
  10936. /* ObjectType::Int8MixedArray */ 0, // log2(sizeof(int8))
  10937. /* ObjectType::Uint8MixedArray */ 0, // log2(sizeof(uint8))
  10938. /* ObjectType::Uint8ClampedMixedArray */ 0, // log2(sizeof(uint8))
  10939. /* ObjectType::Int16MixedArray */ 1, // log2(sizeof(int16))
  10940. /* ObjectType::Uint16MixedArray */ 1, // log2(sizeof(uint16))
  10941. /* ObjectType::Int32MixedArray */ 2, // log2(sizeof(int32))
  10942. /* ObjectType::Uint32MixedArray */ 2, // log2(sizeof(uint32))
  10943. /* ObjectType::Float32MixedArray */ 2, // log2(sizeof(float))
  10944. /* ObjectType::Float64MixedArray */ 3, // log2(sizeof(double))
  10945. /* ObjectType::Int64Array */ 3, // log2(sizeof(int64))
  10946. /* ObjectType::Uint64Array */ 3, // log2(sizeof(uint64))
  10947. /* ObjectType::BoolArray */ 0, // log2(sizeof(bool))
  10948. /* ObjectType::CharArray */ 1 // log2(sizeof(wchar_t))
  10949. };
  10950. VTableValue Lowerer::GetArrayVtableAddress(const ValueType valueType, bool getVirtual)
  10951. {
  10952. Assert(valueType.IsLikelyAnyOptimizedArray());
  10953. if(valueType.IsLikelyArrayOrObjectWithArray())
  10954. {
  10955. if(valueType.HasIntElements())
  10956. {
  10957. return VTableValue::VtableNativeIntArray;
  10958. }
  10959. else if(valueType.HasFloatElements())
  10960. {
  10961. return VTableValue::VtableNativeFloatArray;
  10962. }
  10963. }
  10964. if (getVirtual && valueType.IsLikelyMixedTypedArrayType())
  10965. {
  10966. return VtableAddresses[static_cast<ValueType::TSize>(valueType.GetMixedToVirtualTypedArrayObjectType())];
  10967. }
  10968. return VtableAddresses[static_cast<ValueType::TSize>(valueType.GetObjectType())];
  10969. }
  10970. uint32 Lowerer::GetArrayOffsetOfHeadSegment(const ValueType valueType)
  10971. {
  10972. Assert(valueType.IsLikelyAnyOptimizedArray());
  10973. return OffsetsOfHeadSegment[static_cast<ValueType::TSize>(valueType.GetObjectType())];
  10974. }
  10975. uint32 Lowerer::GetArrayOffsetOfLength(const ValueType valueType)
  10976. {
  10977. Assert(valueType.IsLikelyAnyOptimizedArray());
  10978. return OffsetsOfLength[static_cast<ValueType::TSize>(valueType.GetObjectType())];
  10979. }
  10980. IRType Lowerer::GetArrayIndirType(const ValueType valueType)
  10981. {
  10982. Assert(valueType.IsLikelyAnyOptimizedArray());
  10983. if(valueType.IsLikelyArrayOrObjectWithArray())
  10984. {
  10985. if(valueType.HasIntElements())
  10986. {
  10987. return TyInt32;
  10988. }
  10989. else if(valueType.HasFloatElements())
  10990. {
  10991. return TyFloat64;
  10992. }
  10993. }
  10994. return IndirTypes[static_cast<ValueType::TSize>(valueType.GetObjectType())];
  10995. }
  10996. BYTE Lowerer::GetArrayIndirScale(const ValueType valueType) const
  10997. {
  10998. Assert(valueType.IsLikelyAnyOptimizedArray());
  10999. if(valueType.IsLikelyArrayOrObjectWithArray())
  11000. {
  11001. if(valueType.HasIntElements())
  11002. {
  11003. return 2; // log2(sizeof(int32))
  11004. }
  11005. else if(valueType.HasFloatElements())
  11006. {
  11007. return 3; // log2(sizeof(double))
  11008. }
  11009. }
  11010. return IndirScales[static_cast<ValueType::TSize>(valueType.GetObjectType())];
  11011. }
  11012. bool Lowerer::ShouldGenerateArrayFastPath(
  11013. const IR::Opnd *const arrayOpnd,
  11014. const bool supportsObjectsWithArrays,
  11015. const bool supportsTypedArrays,
  11016. const bool requiresSse2ForFloatArrays) const
  11017. {
  11018. Assert(arrayOpnd);
  11019. const ValueType arrayValueType(arrayOpnd->GetValueType());
  11020. if(arrayValueType.IsUninitialized())
  11021. {
  11022. // Don't have info about the value type, better to generate the fast path anyway
  11023. return true;
  11024. }
  11025. if (!arrayValueType.IsLikelyObject())
  11026. {
  11027. if (!arrayValueType.HasBeenObject() || arrayValueType.IsLikelyString())
  11028. {
  11029. return false;
  11030. }
  11031. //We have seen at least once there is an object in the code path. Generate fastpath hoping it to be array.
  11032. //Its nice if we can get all the attributes set but valueType is only 16 bits. Consider expanding the same.
  11033. return true;
  11034. }
  11035. if( !supportsObjectsWithArrays && arrayValueType.GetObjectType() == ObjectType::ObjectWithArray ||
  11036. !supportsTypedArrays && arrayValueType.IsLikelyTypedArray())
  11037. {
  11038. // The fast path likely would not hit
  11039. return false;
  11040. }
  11041. if(arrayValueType.GetObjectType() == ObjectType::UninitializedObject)
  11042. {
  11043. // Don't have info about the object type, better to generate the fast path anyway
  11044. return true;
  11045. }
  11046. #ifdef _M_IX86
  11047. if(requiresSse2ForFloatArrays &&
  11048. (
  11049. arrayValueType.GetObjectType() == ObjectType::Float32Array ||
  11050. arrayValueType.GetObjectType() == ObjectType::Float64Array
  11051. ) &&
  11052. !AutoSystemInfo::Data.SSE2Available())
  11053. {
  11054. // Fast paths for float arrays rely on SSE2
  11055. return false;
  11056. }
  11057. #endif
  11058. return !arrayValueType.IsLikelyAnyUnOptimizedArray();
  11059. }
  11060. IR::RegOpnd *Lowerer::LoadObjectArray(IR::RegOpnd *const baseOpnd, IR::Instr *const insertBeforeInstr)
  11061. {
  11062. Assert(baseOpnd);
  11063. Assert(
  11064. baseOpnd->GetValueType().IsLikelyObject() &&
  11065. baseOpnd->GetValueType().GetObjectType() == ObjectType::ObjectWithArray);
  11066. Assert(insertBeforeInstr);
  11067. Func *const func = insertBeforeInstr->m_func;
  11068. // mov array, [base + offsetOf(objectArrayOrFlags)]
  11069. IR::RegOpnd *const arrayOpnd =
  11070. baseOpnd->IsArrayRegOpnd() ? baseOpnd->AsArrayRegOpnd()->CopyAsRegOpnd(func) : baseOpnd->Copy(func)->AsRegOpnd();
  11071. arrayOpnd->m_sym = StackSym::New(TyVar, func);
  11072. arrayOpnd->SetValueType(arrayOpnd->GetValueType().ToArray());
  11073. const IR::AutoReuseOpnd autoReuseArrayOpnd(arrayOpnd, func, false /* autoDelete */);
  11074. m_lowererMD.CreateAssign(
  11075. arrayOpnd,
  11076. IR::IndirOpnd::New(
  11077. baseOpnd,
  11078. Js::DynamicObject::GetOffsetOfObjectArray(),
  11079. arrayOpnd->GetType(),
  11080. func),
  11081. insertBeforeInstr);
  11082. return arrayOpnd;
  11083. }
  11084. void
  11085. Lowerer::GenerateIsEnabledArraySetElementFastPathCheck(
  11086. IR::LabelInstr * isDisabledLabel,
  11087. IR::Instr * const insertBeforeInstr)
  11088. {
  11089. InsertCompareBranch(
  11090. this->LoadOptimizationOverridesValueOpnd(insertBeforeInstr, OptimizationOverridesValue::OptimizationOverridesArraySetElementFastPathVtable),
  11091. LoadVTableValueOpnd(insertBeforeInstr, VTableValue::VtableInvalid),
  11092. Js::OpCode::BrEq_A,
  11093. isDisabledLabel,
  11094. insertBeforeInstr);
  11095. }
  11096. IR::RegOpnd *Lowerer::GenerateArrayTest(
  11097. IR::RegOpnd *const baseOpnd,
  11098. IR::LabelInstr *const isNotObjectLabel,
  11099. IR::LabelInstr *const isNotArrayLabel,
  11100. IR::Instr *const insertBeforeInstr,
  11101. const bool forceFloat,
  11102. const bool isStore,
  11103. const bool allowDefiniteArray)
  11104. {
  11105. Assert(baseOpnd);
  11106. const ValueType baseValueType(baseOpnd->GetValueType());
  11107. // Shouldn't request to do an array test when it's already known to be an array, or if it's unlikely to be an array
  11108. Assert(!baseValueType.IsAnyOptimizedArray() || allowDefiniteArray || baseValueType.IsNativeArray());
  11109. Assert(baseValueType.IsUninitialized() || baseValueType.HasBeenObject());
  11110. Assert(isNotObjectLabel);
  11111. Assert(isNotArrayLabel);
  11112. Assert(insertBeforeInstr);
  11113. Func *const func = insertBeforeInstr->m_func;
  11114. IR::RegOpnd *arrayOpnd;
  11115. IR::AutoReuseOpnd autoReuseArrayOpnd;
  11116. if(baseValueType.IsLikelyObject() && baseValueType.GetObjectType() == ObjectType::ObjectWithArray)
  11117. {
  11118. // Only DynamicObject is allowed (DynamicObject vtable is ensured) because some object types have special handling for
  11119. // index properties - arguments object, string object, external object, etc.
  11120. GenerateObjectTypeTest(baseOpnd, insertBeforeInstr, isNotObjectLabel);
  11121. GenerateObjectHeaderInliningTest(baseOpnd, isNotArrayLabel, insertBeforeInstr);
  11122. arrayOpnd = LoadObjectArray(baseOpnd, insertBeforeInstr);
  11123. autoReuseArrayOpnd.Initialize(arrayOpnd, func, false /* autoDelete */);
  11124. // test array, array
  11125. // je $isNotArrayLabel
  11126. // test array, 1
  11127. // jne $isNotArrayLabel
  11128. InsertTestBranch(
  11129. arrayOpnd,
  11130. arrayOpnd,
  11131. Js::OpCode::BrEq_A,
  11132. isNotArrayLabel,
  11133. insertBeforeInstr);
  11134. InsertTestBranch(
  11135. arrayOpnd,
  11136. IR::IntConstOpnd::New(1, TyUint8, func, true),
  11137. Js::OpCode::BrNeq_A,
  11138. isNotArrayLabel,
  11139. insertBeforeInstr);
  11140. }
  11141. else
  11142. {
  11143. if(!baseOpnd->IsNotTaggedValue())
  11144. {
  11145. m_lowererMD.GenerateObjectTest(baseOpnd, insertBeforeInstr, isNotObjectLabel);
  11146. }
  11147. arrayOpnd = baseOpnd->Copy(func)->AsRegOpnd();
  11148. if(!baseValueType.IsLikelyAnyOptimizedArray())
  11149. {
  11150. arrayOpnd->SetValueType(
  11151. ValueType::GetObject(ObjectType::Array)
  11152. .ToLikely()
  11153. .SetHasNoMissingValues(false)
  11154. .SetArrayTypeId(Js::TypeIds_Array));
  11155. }
  11156. autoReuseArrayOpnd.Initialize(arrayOpnd, func, false /* autoDelete */);
  11157. }
  11158. VTableValue vtableAddress = baseValueType.IsLikelyAnyOptimizedArray()
  11159. ? GetArrayVtableAddress(baseValueType)
  11160. : VTableValue::VtableJavascriptArray;
  11161. VTableValue virtualVtableAddress = VTableValue::VtableInvalid;
  11162. if (baseValueType.IsLikelyMixedTypedArrayType())
  11163. {
  11164. virtualVtableAddress = GetArrayVtableAddress(baseValueType, true);
  11165. }
  11166. IR::Opnd * vtableOpnd;
  11167. IR::Opnd * vtableVirtualOpnd = nullptr;
  11168. if (isStore &&
  11169. (vtableAddress == VTableValue::VtableJavascriptArray ||
  11170. baseValueType.IsLikelyNativeArray()))
  11171. {
  11172. vtableOpnd = IR::RegOpnd::New(TyMachPtr, func);
  11173. if (baseValueType.IsLikelyNativeArray())
  11174. {
  11175. if (baseValueType.HasIntElements())
  11176. {
  11177. InsertMove(vtableOpnd, this->LoadOptimizationOverridesValueOpnd(insertBeforeInstr, OptimizationOverridesValue::OptimizationOverridesIntArraySetElementFastPathVtable), insertBeforeInstr);
  11178. }
  11179. else
  11180. {
  11181. Assert(baseValueType.HasFloatElements());
  11182. InsertMove(vtableOpnd, this->LoadOptimizationOverridesValueOpnd(insertBeforeInstr, OptimizationOverridesValue::OptimizationOverridesFloatArraySetElementFastPathVtable), insertBeforeInstr);
  11183. }
  11184. }
  11185. else
  11186. {
  11187. InsertMove(vtableOpnd, this->LoadOptimizationOverridesValueOpnd(insertBeforeInstr, OptimizationOverridesValue::OptimizationOverridesArraySetElementFastPathVtable), insertBeforeInstr);
  11188. }
  11189. }
  11190. else
  11191. {
  11192. vtableOpnd = LoadVTableValueOpnd(insertBeforeInstr, vtableAddress);
  11193. }
  11194. // cmp [array], vtableAddress
  11195. // jne $isNotArrayLabel
  11196. if (forceFloat && baseValueType.IsLikelyNativeFloatArray())
  11197. {
  11198. // We expect a native float array. If we get native int instead, convert it on the spot and bail out afterward.
  11199. const auto goodArrayLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  11200. InsertCompareBranch(
  11201. IR::IndirOpnd::New(arrayOpnd, 0, TyMachPtr, func),
  11202. vtableOpnd,
  11203. Js::OpCode::BrEq_A,
  11204. goodArrayLabel,
  11205. insertBeforeInstr);
  11206. IR::LabelInstr *notFloatArrayLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func, true);
  11207. insertBeforeInstr->InsertBefore(notFloatArrayLabel);
  11208. if (isStore)
  11209. {
  11210. vtableOpnd = IR::RegOpnd::New(TyMachPtr, func);
  11211. InsertMove(vtableOpnd, IR::MemRefOpnd::New(
  11212. func->GetScriptContext()->optimizationOverrides.GetAddressOfIntArraySetElementFastPathVtable(),
  11213. TyMachPtr, func), insertBeforeInstr);
  11214. }
  11215. else
  11216. {
  11217. vtableOpnd = LoadVTableValueOpnd(insertBeforeInstr, VTableValue::VtableJavascriptNativeIntArray);
  11218. }
  11219. InsertCompareBranch(
  11220. IR::IndirOpnd::New(arrayOpnd, 0, TyMachPtr, func),
  11221. vtableOpnd,
  11222. Js::OpCode::BrNeq_A,
  11223. isNotArrayLabel,
  11224. insertBeforeInstr);
  11225. m_lowererMD.LoadHelperArgument(insertBeforeInstr, arrayOpnd);
  11226. IR::Instr *helperInstr = IR::Instr::New(Js::OpCode::Call, m_func);
  11227. insertBeforeInstr->InsertBefore(helperInstr);
  11228. m_lowererMD.ChangeToHelperCall(helperInstr, IR::HelperIntArr_ToNativeFloatArray);
  11229. // Branch to the (bailout) label, because converting the array may have made our array checks unsafe.
  11230. InsertBranch(Js::OpCode::Br, isNotArrayLabel, insertBeforeInstr);
  11231. insertBeforeInstr->InsertBefore(goodArrayLabel);
  11232. }
  11233. else
  11234. {
  11235. IR::LabelInstr* goodArrayLabel = nullptr;
  11236. if (baseValueType.IsLikelyMixedTypedArrayType())
  11237. {
  11238. goodArrayLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  11239. InsertCompareBranch(
  11240. IR::IndirOpnd::New(arrayOpnd, 0, TyMachPtr, func),
  11241. vtableOpnd,
  11242. Js::OpCode::BrEq_A,
  11243. goodArrayLabel,
  11244. insertBeforeInstr);
  11245. Assert(virtualVtableAddress);
  11246. vtableVirtualOpnd = LoadVTableValueOpnd(insertBeforeInstr, virtualVtableAddress);
  11247. Assert(vtableVirtualOpnd);
  11248. InsertCompareBranch(
  11249. IR::IndirOpnd::New(arrayOpnd, 0, TyMachPtr, func),
  11250. vtableVirtualOpnd,
  11251. Js::OpCode::BrNeq_A,
  11252. isNotArrayLabel,
  11253. insertBeforeInstr);
  11254. insertBeforeInstr->InsertBefore(goodArrayLabel);
  11255. }
  11256. else
  11257. {
  11258. InsertCompareBranch(
  11259. IR::IndirOpnd::New(arrayOpnd, 0, TyMachPtr, func),
  11260. vtableOpnd,
  11261. Js::OpCode::BrNeq_A,
  11262. isNotArrayLabel,
  11263. insertBeforeInstr);
  11264. }
  11265. }
  11266. ValueType arrayValueType(arrayOpnd->GetValueType());
  11267. if(arrayValueType.IsLikelyArrayOrObjectWithArray() && !arrayValueType.IsObject())
  11268. {
  11269. arrayValueType = arrayValueType.SetHasNoMissingValues(false);
  11270. }
  11271. arrayValueType = arrayValueType.ToDefiniteObject();
  11272. arrayOpnd->SetValueType(arrayValueType);
  11273. return arrayOpnd;
  11274. }
  11275. IR::LabelInstr *Lowerer::InsertLabel(const bool isHelper, IR::Instr *const insertBeforeInstr)
  11276. {
  11277. Assert(insertBeforeInstr);
  11278. Func *const func = insertBeforeInstr->m_func;
  11279. IR::LabelInstr *const instr = IR::LabelInstr::New(Js::OpCode::Label, func, isHelper);
  11280. insertBeforeInstr->InsertBefore(instr);
  11281. return instr;
  11282. }
  11283. IR::Instr *Lowerer::InsertMoveWithBarrier(IR::Opnd *dst, IR::Opnd *src, IR::Instr *const insertBeforeInstr)
  11284. {
  11285. return Lowerer::InsertMove(dst, src, insertBeforeInstr, true);
  11286. }
  11287. IR::Instr *Lowerer::InsertMove(IR::Opnd *dst, IR::Opnd *src, IR::Instr *const insertBeforeInstr, bool generateWriteBarrier)
  11288. {
  11289. Assert(dst);
  11290. Assert(src);
  11291. Assert(insertBeforeInstr);
  11292. Func *const func = insertBeforeInstr->m_func;
  11293. if(dst->IsFloat() && src->IsConstOpnd())
  11294. {
  11295. return LoadFloatFromNonReg(src, dst, insertBeforeInstr);
  11296. }
  11297. if(TySize[dst->GetType()] < TySize[src->GetType()])
  11298. {
  11299. src = src->UseWithNewType(dst->GetType(), func);
  11300. }
  11301. IR::Instr *const instr = IR::Instr::New(Js::OpCode::Ld_A, dst, src, func);
  11302. insertBeforeInstr->InsertBefore(instr);
  11303. if (generateWriteBarrier)
  11304. {
  11305. LowererMD::ChangeToWriteBarrierAssign(instr);
  11306. }
  11307. else
  11308. {
  11309. LowererMD::ChangeToAssign(instr);
  11310. }
  11311. return instr;
  11312. }
  11313. IR::BranchInstr *Lowerer::InsertBranch(
  11314. const Js::OpCode opCode,
  11315. IR::LabelInstr *const target,
  11316. IR::Instr *const insertBeforeInstr)
  11317. {
  11318. return InsertBranch(opCode, false /* isUnsigned */, target, insertBeforeInstr);
  11319. }
  11320. IR::BranchInstr *Lowerer::InsertBranch(
  11321. const Js::OpCode opCode,
  11322. const bool isUnsigned,
  11323. IR::LabelInstr *const target,
  11324. IR::Instr *const insertBeforeInstr)
  11325. {
  11326. Assert(target);
  11327. Assert(insertBeforeInstr);
  11328. Func *const func = insertBeforeInstr->m_func;
  11329. IR::BranchInstr *const instr = IR::BranchInstr::New(opCode, target, func);
  11330. if(!instr->IsLowered())
  11331. {
  11332. if(opCode == Js::OpCode::Br)
  11333. {
  11334. instr->m_opcode = LowererMD::MDUncondBranchOpcode;
  11335. }
  11336. else if(isUnsigned)
  11337. {
  11338. instr->m_opcode = LowererMD::MDUnsignedBranchOpcode(opCode);
  11339. }
  11340. else
  11341. {
  11342. instr->m_opcode = LowererMD::MDBranchOpcode(opCode);
  11343. }
  11344. }
  11345. insertBeforeInstr->InsertBefore(instr);
  11346. return instr;
  11347. }
  11348. IR::Instr *Lowerer::InsertCompare(IR::Opnd *const src1, IR::Opnd *const src2, IR::Instr *const insertBeforeInstr)
  11349. {
  11350. Assert(src1);
  11351. Assert(!src1->IsFloat64()); // not implemented
  11352. Assert(src2);
  11353. Assert(!src2->IsFloat64()); // not implemented
  11354. Assert(!src1->IsEqual(src2));
  11355. Assert(insertBeforeInstr);
  11356. Func *const func = insertBeforeInstr->m_func;
  11357. IR::Instr *const instr = IR::Instr::New(Js::OpCode::CMP, func);
  11358. instr->SetSrc1(src1);
  11359. instr->SetSrc2(src2);
  11360. insertBeforeInstr->InsertBefore(instr);
  11361. LowererMD::Legalize(instr);
  11362. return instr;
  11363. }
  11364. IR::BranchInstr *Lowerer::InsertCompareBranch(
  11365. IR::Opnd *const compareSrc1,
  11366. IR::Opnd *const compareSrc2,
  11367. Js::OpCode branchOpCode,
  11368. IR::LabelInstr *const target,
  11369. IR::Instr *const insertBeforeInstr,
  11370. const bool ignoreNaN)
  11371. {
  11372. return InsertCompareBranch(compareSrc1, compareSrc2, branchOpCode, false /* isUnsigned */, target, insertBeforeInstr, ignoreNaN);
  11373. }
  11374. IR::BranchInstr *Lowerer::InsertCompareBranch(
  11375. IR::Opnd *compareSrc1,
  11376. IR::Opnd *compareSrc2,
  11377. Js::OpCode branchOpCode,
  11378. const bool isUnsigned,
  11379. IR::LabelInstr *const target,
  11380. IR::Instr *const insertBeforeInstr,
  11381. const bool ignoreNaN)
  11382. {
  11383. Assert(compareSrc1);
  11384. Assert(compareSrc2);
  11385. Func *const func = insertBeforeInstr->m_func;
  11386. if(compareSrc1->IsFloat64())
  11387. {
  11388. Assert(compareSrc2->IsFloat64());
  11389. Assert(!isUnsigned);
  11390. IR::BranchInstr *const instr = IR::BranchInstr::New(branchOpCode, target, compareSrc1, compareSrc2, func);
  11391. insertBeforeInstr->InsertBefore(instr);
  11392. return LowererMD::LowerFloatCondBranch(instr, ignoreNaN);
  11393. }
  11394. Js::OpCode swapSrcsBranchOpCode;
  11395. switch(branchOpCode)
  11396. {
  11397. case Js::OpCode::BrEq_A:
  11398. case Js::OpCode::BrNeq_A:
  11399. swapSrcsBranchOpCode = branchOpCode;
  11400. goto Common_BrEqNeqGeGtLeLt;
  11401. case Js::OpCode::BrGe_A:
  11402. swapSrcsBranchOpCode = Js::OpCode::BrLe_A;
  11403. goto Common_BrEqNeqGeGtLeLt;
  11404. case Js::OpCode::BrGt_A:
  11405. swapSrcsBranchOpCode = Js::OpCode::BrLt_A;
  11406. goto Common_BrEqNeqGeGtLeLt;
  11407. case Js::OpCode::BrLe_A:
  11408. swapSrcsBranchOpCode = Js::OpCode::BrGe_A;
  11409. goto Common_BrEqNeqGeGtLeLt;
  11410. case Js::OpCode::BrLt_A:
  11411. swapSrcsBranchOpCode = Js::OpCode::BrGt_A;
  11412. // fall through
  11413. Common_BrEqNeqGeGtLeLt:
  11414. // Check if src1 is a constant and src2 is not, and facilitate folding the constant into the Cmp instruction
  11415. if( (
  11416. compareSrc1->IsIntConstOpnd() ||
  11417. (
  11418. compareSrc1->IsAddrOpnd() &&
  11419. Math::FitsInDWord(reinterpret_cast<size_t>(compareSrc1->AsAddrOpnd()->m_address))
  11420. )
  11421. ) &&
  11422. !compareSrc2->IsIntConstOpnd() &&
  11423. !compareSrc2->IsAddrOpnd())
  11424. {
  11425. // Swap the sources and branch
  11426. IR::Opnd *const tempSrc = compareSrc1;
  11427. compareSrc1 = compareSrc2;
  11428. compareSrc2 = tempSrc;
  11429. branchOpCode = swapSrcsBranchOpCode;
  11430. }
  11431. // Check for compare with zero, to prefer using Test instead of Cmp
  11432. if( !compareSrc1->IsRegOpnd() ||
  11433. !(
  11434. compareSrc2->IsIntConstOpnd() && compareSrc2->AsIntConstOpnd()->GetValue() == 0 ||
  11435. compareSrc2->IsAddrOpnd() && !compareSrc2->AsAddrOpnd()->m_address
  11436. ) ||
  11437. branchOpCode == Js::OpCode::BrGt_A || branchOpCode == Js::OpCode::BrLe_A)
  11438. {
  11439. goto Default;
  11440. }
  11441. if(branchOpCode == Js::OpCode::BrGe_A || branchOpCode == Js::OpCode::BrLt_A)
  11442. {
  11443. if(isUnsigned)
  11444. {
  11445. goto Default;
  11446. }
  11447. branchOpCode = LowererMD::MDCompareWithZeroBranchOpcode(branchOpCode);
  11448. }
  11449. if(!compareSrc2->IsInUse())
  11450. {
  11451. compareSrc2->Free(func);
  11452. }
  11453. InsertTest(compareSrc1, compareSrc1, insertBeforeInstr);
  11454. break;
  11455. default:
  11456. Default:
  11457. InsertCompare(compareSrc1, compareSrc2, insertBeforeInstr);
  11458. break;
  11459. }
  11460. return InsertBranch(branchOpCode, isUnsigned, target, insertBeforeInstr);
  11461. }
  11462. IR::Instr *Lowerer::InsertTest(IR::Opnd *const src1, IR::Opnd *const src2, IR::Instr *const insertBeforeInstr)
  11463. {
  11464. Assert(src1);
  11465. Assert(!src1->IsFloat64()); // not implemented
  11466. Assert(src2);
  11467. Assert(!src2->IsFloat64()); // not implemented
  11468. Assert(insertBeforeInstr);
  11469. Func *const func = insertBeforeInstr->m_func;
  11470. IR::Instr *const instr = IR::Instr::New(LowererMD::MDTestOpcode, func);
  11471. instr->SetSrc1(src1);
  11472. instr->SetSrc2(src2);
  11473. insertBeforeInstr->InsertBefore(instr);
  11474. LowererMD::Legalize(instr);
  11475. return instr;
  11476. }
  11477. IR::BranchInstr *Lowerer::InsertTestBranch(
  11478. IR::Opnd *const testSrc1,
  11479. IR::Opnd *const testSrc2,
  11480. const Js::OpCode branchOpCode,
  11481. IR::LabelInstr *const target,
  11482. IR::Instr *const insertBeforeInstr)
  11483. {
  11484. return InsertTestBranch(testSrc1, testSrc2, branchOpCode, false /* isUnsigned */, target, insertBeforeInstr);
  11485. }
  11486. IR::BranchInstr *Lowerer::InsertTestBranch(
  11487. IR::Opnd *const testSrc1,
  11488. IR::Opnd *const testSrc2,
  11489. const Js::OpCode branchOpCode,
  11490. const bool isUnsigned,
  11491. IR::LabelInstr *const target,
  11492. IR::Instr *const insertBeforeInstr)
  11493. {
  11494. InsertTest(testSrc1, testSrc2, insertBeforeInstr);
  11495. return InsertBranch(branchOpCode, isUnsigned, target, insertBeforeInstr);
  11496. }
  11497. IR::Instr *Lowerer::InsertAdd(
  11498. const bool needFlags,
  11499. IR::Opnd *const dst,
  11500. IR::Opnd *src1,
  11501. IR::Opnd *src2,
  11502. IR::Instr *const insertBeforeInstr)
  11503. {
  11504. Assert(dst);
  11505. Assert(src1);
  11506. Assert(src2);
  11507. Assert(insertBeforeInstr);
  11508. Func *const func = insertBeforeInstr->m_func;
  11509. if(src2->IsIntConstOpnd())
  11510. {
  11511. IR::IntConstOpnd *const intConstOpnd = src2->AsIntConstOpnd();
  11512. const IntConstType value = intConstOpnd->GetValue();
  11513. if(value < 0 && value != IntConstMin)
  11514. {
  11515. // Change (s1 = s1 + -5) into (s1 = s1 - 5)
  11516. IR::IntConstOpnd *const newSrc2 = intConstOpnd->CopyInternal(func);
  11517. newSrc2->SetValue(-value);
  11518. return InsertSub(needFlags, dst, src1, newSrc2, insertBeforeInstr);
  11519. }
  11520. }
  11521. else if(src1->IsIntConstOpnd())
  11522. {
  11523. IR::IntConstOpnd *const intConstOpnd = src1->AsIntConstOpnd();
  11524. const IntConstType value = intConstOpnd->GetValue();
  11525. if(value < 0 && value != IntConstMin)
  11526. {
  11527. // Change (s1 = -5 + s1) into (s1 = s1 - 5)
  11528. IR::Opnd *const newSrc1 = src2;
  11529. IR::IntConstOpnd *const newSrc2 = intConstOpnd->CopyInternal(func);
  11530. newSrc2->SetValue(-value);
  11531. return InsertSub(needFlags, dst, newSrc1, newSrc2, insertBeforeInstr);
  11532. }
  11533. }
  11534. IR::Instr *const instr = IR::Instr::New(Js::OpCode::Add_A, dst, src1, src2, func);
  11535. insertBeforeInstr->InsertBefore(instr);
  11536. LowererMD::ChangeToAdd(instr, needFlags);
  11537. LowererMD::Legalize(instr);
  11538. return instr;
  11539. }
  11540. IR::Instr *Lowerer::InsertSub(
  11541. const bool needFlags,
  11542. IR::Opnd *const dst,
  11543. IR::Opnd *src1,
  11544. IR::Opnd *src2,
  11545. IR::Instr *const insertBeforeInstr)
  11546. {
  11547. Assert(dst);
  11548. Assert(src1);
  11549. Assert(src2);
  11550. Assert(insertBeforeInstr);
  11551. Func *const func = insertBeforeInstr->m_func;
  11552. if(src2->IsIntConstOpnd())
  11553. {
  11554. IR::IntConstOpnd *const intConstOpnd = src2->AsIntConstOpnd();
  11555. const IntConstType value = intConstOpnd->GetValue();
  11556. if(value < 0 && value != IntConstMin)
  11557. {
  11558. // Change (s1 = s1 - -5) into (s1 = s1 + 5)
  11559. IR::IntConstOpnd *const newSrc2 = intConstOpnd->CopyInternal(func);
  11560. newSrc2->SetValue(-value);
  11561. return InsertAdd(needFlags, dst, src1, newSrc2, insertBeforeInstr);
  11562. }
  11563. }
  11564. IR::Instr *const instr = IR::Instr::New(Js::OpCode::Sub_A, dst, src1, src2, func);
  11565. insertBeforeInstr->InsertBefore(instr);
  11566. LowererMD::ChangeToSub(instr, needFlags);
  11567. LowererMD::Legalize(instr);
  11568. return instr;
  11569. }
  11570. IR::Instr *Lowerer::InsertLea(IR::RegOpnd *const dst, IR::Opnd *const src, IR::Instr *const insertBeforeInstr)
  11571. {
  11572. Assert(dst);
  11573. Assert(src);
  11574. Assert(src->IsIndirOpnd() || src->IsSymOpnd());
  11575. Assert(insertBeforeInstr);
  11576. Func *const func = insertBeforeInstr->m_func;
  11577. IR::Instr *const instr = IR::Instr::New(Js::OpCode::LEA, dst, src, func);
  11578. insertBeforeInstr->InsertBefore(instr);
  11579. return LowererMD::ChangeToLea(instr);
  11580. }
  11581. IR::Instr *Lowerer::InsertAnd(
  11582. IR::Opnd *const dst,
  11583. IR::Opnd *const src1,
  11584. IR::Opnd *const src2,
  11585. IR::Instr *const insertBeforeInstr)
  11586. {
  11587. Assert(dst);
  11588. Assert(src1);
  11589. Assert(src2);
  11590. Assert(insertBeforeInstr);
  11591. Func *const func = insertBeforeInstr->m_func;
  11592. IR::Instr *const instr = IR::Instr::New(Js::OpCode::AND, dst, src1, src2, func);
  11593. insertBeforeInstr->InsertBefore(instr);
  11594. LowererMD::Legalize(instr);
  11595. return instr;
  11596. }
  11597. IR::Instr *Lowerer::InsertOr(
  11598. IR::Opnd *const dst,
  11599. IR::Opnd *const src1,
  11600. IR::Opnd *const src2,
  11601. IR::Instr *const insertBeforeInstr)
  11602. {
  11603. Assert(dst);
  11604. Assert(src1);
  11605. Assert(src2);
  11606. Assert(insertBeforeInstr);
  11607. Func *const func = insertBeforeInstr->m_func;
  11608. IR::Instr *const instr = IR::Instr::New(LowererMD::MDOrOpcode, dst, src1, src2, func);
  11609. insertBeforeInstr->InsertBefore(instr);
  11610. LowererMD::Legalize(instr);
  11611. return instr;
  11612. }
  11613. IR::Instr *Lowerer::InsertShift(
  11614. const Js::OpCode opCode,
  11615. const bool needFlags,
  11616. IR::Opnd *const dst,
  11617. IR::Opnd *const src1,
  11618. IR::Opnd *const src2,
  11619. IR::Instr *const insertBeforeInstr)
  11620. {
  11621. Assert(dst);
  11622. Assert(!dst->IsFloat64()); // not implemented
  11623. Assert(src1);
  11624. Assert(!src1->IsFloat64()); // not implemented
  11625. Assert(src2);
  11626. Assert(!src2->IsFloat64()); // not implemented
  11627. Assert(insertBeforeInstr);
  11628. Func *const func = insertBeforeInstr->m_func;
  11629. IR::Instr *const instr = IR::Instr::New(opCode, dst, src1, src2, func);
  11630. insertBeforeInstr->InsertBefore(instr);
  11631. LowererMD::ChangeToShift(instr, needFlags);
  11632. LowererMD::Legalize(instr);
  11633. return instr;
  11634. }
  11635. IR::Instr *Lowerer::InsertShiftBranch(
  11636. const Js::OpCode shiftOpCode,
  11637. IR::Opnd *const dst,
  11638. IR::Opnd *const src1,
  11639. IR::Opnd *const src2,
  11640. const Js::OpCode branchOpCode,
  11641. IR::LabelInstr *const target,
  11642. IR::Instr *const insertBeforeInstr)
  11643. {
  11644. return InsertShiftBranch(shiftOpCode, dst, src1, src2, branchOpCode, false /* isUnsigned */, target, insertBeforeInstr);
  11645. }
  11646. IR::Instr *Lowerer::InsertShiftBranch(
  11647. const Js::OpCode shiftOpCode,
  11648. IR::Opnd *const dst,
  11649. IR::Opnd *const src1,
  11650. IR::Opnd *const src2,
  11651. const Js::OpCode branchOpCode,
  11652. const bool isUnsigned,
  11653. IR::LabelInstr *const target,
  11654. IR::Instr *const insertBeforeInstr)
  11655. {
  11656. InsertShift(shiftOpCode, true /* needFlags */, dst, src1, src2, insertBeforeInstr);
  11657. return InsertBranch(branchOpCode, isUnsigned, target, insertBeforeInstr);
  11658. }
  11659. IR::Instr *Lowerer::InsertConvertFloat32ToFloat64(
  11660. IR::Opnd *const dst,
  11661. IR::Opnd *const src,
  11662. IR::Instr *const insertBeforeInstr)
  11663. {
  11664. Assert(dst);
  11665. Assert(dst->IsFloat64());
  11666. Assert(src);
  11667. Assert(src->IsFloat32());
  11668. Assert(insertBeforeInstr);
  11669. Func *const func = insertBeforeInstr->m_func;
  11670. IR::Instr *const instr = IR::Instr::New(LowererMD::MDConvertFloat32ToFloat64Opcode, dst, src, func);
  11671. insertBeforeInstr->InsertBefore(instr);
  11672. LowererMD::Legalize(instr);
  11673. return instr;
  11674. }
  11675. IR::Instr *Lowerer::InsertConvertFloat64ToFloat32(
  11676. IR::Opnd *const dst,
  11677. IR::Opnd *const src,
  11678. IR::Instr *const insertBeforeInstr)
  11679. {
  11680. Assert(dst);
  11681. Assert(dst->IsFloat32());
  11682. Assert(src);
  11683. Assert(src->IsFloat64());
  11684. Assert(insertBeforeInstr);
  11685. Func *const func = insertBeforeInstr->m_func;
  11686. IR::Instr *const instr = IR::Instr::New(LowererMD::MDConvertFloat64ToFloat32Opcode, dst, src, func);
  11687. insertBeforeInstr->InsertBefore(instr);
  11688. LowererMD::Legalize(instr);
  11689. return instr;
  11690. }
  11691. void Lowerer::InsertIncUInt8PreventOverflow(
  11692. IR::Opnd *const dst,
  11693. IR::Opnd *const src,
  11694. IR::Instr *const insertBeforeInstr,
  11695. IR::Instr * *const onOverflowInsertBeforeInstrRef)
  11696. {
  11697. LowererMD::InsertIncUInt8PreventOverflow(dst, src, insertBeforeInstr, onOverflowInsertBeforeInstrRef);
  11698. }
  11699. void Lowerer::InsertDecUInt8PreventOverflow(
  11700. IR::Opnd *const dst,
  11701. IR::Opnd *const src,
  11702. IR::Instr *const insertBeforeInstr,
  11703. IR::Instr * *const onOverflowInsertBeforeInstrRef)
  11704. {
  11705. LowererMD::InsertDecUInt8PreventOverflow(dst, src, insertBeforeInstr, onOverflowInsertBeforeInstrRef);
  11706. }
  11707. void Lowerer::InsertFloatCheckForZeroOrNanBranch(
  11708. IR::Opnd *const src,
  11709. const bool branchOnZeroOrNan,
  11710. IR::LabelInstr *const target,
  11711. IR::LabelInstr *const fallthroughLabel,
  11712. IR::Instr *const insertBeforeInstr)
  11713. {
  11714. Assert(src);
  11715. Assert(src->IsFloat64());
  11716. Assert(target);
  11717. Assert(!fallthroughLabel || fallthroughLabel != target);
  11718. Assert(insertBeforeInstr);
  11719. Func *const func = insertBeforeInstr->m_func;
  11720. IR::BranchInstr *const branchOnEqualOrNotEqual =
  11721. InsertCompareBranch(
  11722. src,
  11723. IR::MemRefOpnd::New((double*)&(Js::JavascriptNumber::k_Zero), TyFloat64, func),
  11724. branchOnZeroOrNan ? Js::OpCode::BrEq_A : Js::OpCode::BrNeq_A,
  11725. target,
  11726. insertBeforeInstr,
  11727. true /* ignoreNaN */);
  11728. // x86/x64
  11729. // When NaN is ignored, on x86 and x64, JE branches when equal or unordered since an unordered result sets the zero
  11730. // flag, and JNE branches when not equal and not unordered. By comparing with zero, JE will branch when src is zero or
  11731. // NaN, and JNE will branch when src is not zero and not NaN.
  11732. //
  11733. // ARM
  11734. // When NaN is ignored, BEQ branches when equal and not unordered, and BNE branches when not equal or unordered. So,
  11735. // when comparing src with zero, an unordered check needs to be added before the BEQ/BNE.
  11736. branchOnEqualOrNotEqual; // satisfy the compiler
  11737. #ifdef _M_ARM
  11738. InsertBranch(
  11739. Js::OpCode::BVS,
  11740. branchOnZeroOrNan
  11741. ? target
  11742. : fallthroughLabel ? fallthroughLabel : insertBeforeInstr->m_prev->GetOrCreateContinueLabel(),
  11743. branchOnEqualOrNotEqual);
  11744. #endif
  11745. }
  11746. IR::IndirOpnd *
  11747. Lowerer::GenerateFastElemICommon(
  11748. IR::Instr * ldElem,
  11749. bool isStore,
  11750. IR::IndirOpnd * indirOpnd,
  11751. IR::LabelInstr * labelHelper,
  11752. IR::LabelInstr * labelCantUseArray,
  11753. IR::LabelInstr *labelFallthrough,
  11754. bool * pIsTypedArrayElement,
  11755. bool * pIsStringIndex,
  11756. bool *emitBailoutRef,
  11757. IR::LabelInstr **pLabelSegmentLengthIncreased /*= nullptr*/,
  11758. bool checkArrayLengthOverflow /*= true*/,
  11759. bool forceGenerateFastPath /* = false */,
  11760. bool returnLength,
  11761. IR::LabelInstr *bailOutLabelInstr /* = nullptr*/)
  11762. {
  11763. *pIsTypedArrayElement = false;
  11764. *pIsStringIndex = false;
  11765. if(pLabelSegmentLengthIncreased)
  11766. {
  11767. *pLabelSegmentLengthIncreased = nullptr;
  11768. }
  11769. IR::RegOpnd *baseOpnd = indirOpnd->GetBaseOpnd();
  11770. AssertMsg(baseOpnd, "This shouldn't be NULL");
  11771. // Caution: If making changes to the conditions under which we don't emit the typical array checks, make sure
  11772. // the code in GlobOpt::ShouldAssumeIndirOpndHasNonNegativeIntIndex is updated accordingly. We don't want the
  11773. // global optimizer to type specialize instructions, for which the lowerer is forced to emit unconditional
  11774. // bailouts.
  11775. if (baseOpnd->IsTaggedInt())
  11776. {
  11777. return NULL;
  11778. }
  11779. IR::RegOpnd *indexOpnd = indirOpnd->GetIndexOpnd();
  11780. if (indexOpnd)
  11781. {
  11782. if (indexOpnd->GetValueType().IsString())
  11783. {
  11784. if (!baseOpnd->GetValueType().IsLikelyOptimizedTypedArray())
  11785. {
  11786. // If profile data says that it's a typed array - do not generate the property string fast path as the src. could be a temp and that would cause a bug.
  11787. *pIsTypedArrayElement = false;
  11788. *pIsStringIndex = true;
  11789. return m_lowererMD.GenerateFastElemIStringIndexCommon(ldElem, isStore, indirOpnd, labelHelper);
  11790. }
  11791. else
  11792. {
  11793. // There's no point in generating the int index fast path if we know the index has a string value.
  11794. return nullptr;
  11795. }
  11796. }
  11797. }
  11798. return
  11799. GenerateFastElemIIntIndexCommon(
  11800. ldElem,
  11801. isStore,
  11802. indirOpnd,
  11803. labelHelper,
  11804. labelCantUseArray,
  11805. labelFallthrough,
  11806. pIsTypedArrayElement,
  11807. emitBailoutRef,
  11808. pLabelSegmentLengthIncreased,
  11809. checkArrayLengthOverflow,
  11810. false,
  11811. returnLength,
  11812. bailOutLabelInstr);
  11813. }
  11814. IR::IndirOpnd *
  11815. Lowerer::GenerateFastElemIIntIndexCommon(
  11816. IR::Instr * ldElem,
  11817. bool isStore,
  11818. IR::IndirOpnd * indirOpnd,
  11819. IR::LabelInstr * labelHelper,
  11820. IR::LabelInstr * labelCantUseArray,
  11821. IR::LabelInstr *labelFallthrough,
  11822. bool * pIsTypedArrayElement,
  11823. bool *emitBailoutRef,
  11824. IR::LabelInstr **pLabelSegmentLengthIncreased,
  11825. bool checkArrayLengthOverflow /*= true*/,
  11826. bool forceGenerateFastPath /* = false */,
  11827. bool returnLength,
  11828. IR::LabelInstr *bailOutLabelInstr /* = nullptr*/)
  11829. {
  11830. IR::RegOpnd *indexOpnd = indirOpnd->GetIndexOpnd();
  11831. IR::RegOpnd *baseOpnd = indirOpnd->GetBaseOpnd();
  11832. Assert(!baseOpnd->IsTaggedInt() || (indexOpnd && indexOpnd->IsNotInt()));
  11833. BYTE indirScale = this->m_lowererMD.GetDefaultIndirScale();
  11834. IRType indirType = TyVar;
  11835. const ValueType baseValueType(baseOpnd->GetValueType());
  11836. // TEST base, AtomTag -- check base not tagged int
  11837. // JNE $helper
  11838. // if (base.GetValueType() != Array) {
  11839. // CMP [base], JavascriptArray::`vtable'
  11840. // JNE $helper
  11841. // }
  11842. // TEST index, 1 -- index tagged int
  11843. // JEQ $helper
  11844. // if (inputIndex is not int const) {
  11845. // MOV index, inputIndex
  11846. // SAR index, Js::VarTag_Shift -- remote atom tag
  11847. // JS $helper -- exclude negative index
  11848. // }
  11849. // MOV headSegment, [base + offset(head)]
  11850. // CMP [headSegment + offset(length)], index -- bounds check
  11851. // if (opcode == StElemI_A) {
  11852. // JA $done (for typedarray, JA $toNumberHelper)
  11853. // CMP [headSegment + offset(size)], index -- chunk has room?
  11854. // JBE $helper
  11855. // if (index is not int const) {
  11856. // LEA newLength, [index + 1]
  11857. // } else {
  11858. // newLength = index + 1
  11859. // }
  11860. // MOV [headSegment + offset(length)], newLength -- update length on chunk
  11861. // CMP [base + offset(length)], newLength
  11862. // JAE $done
  11863. // MOV [base + offset(length)], newLength -- update length on array
  11864. // if(length to be returned){
  11865. // SHL newLength, AtomTag
  11866. // INC newLength
  11867. // MOV dst, newLength
  11868. // }
  11869. // JMP $done
  11870. //
  11871. // $toNumberHelper: Call HelperOp_ConvNumber_Full
  11872. // JMP $done
  11873. // $done
  11874. // } else {la
  11875. // JBE $helper
  11876. // }
  11877. // return [headSegment + offset(elements) + index]
  11878. // Caution: If making changes to the conditions under which we don't emit the typical array checks, make sure
  11879. // the code in GlobOpt::ShouldAssumeIndirOpndHasNonNegativeIntIndex is updated accordingly. We don't want the
  11880. // global optimizer to type specialize instructions, for which the lowerer is forced to emit unconditional
  11881. // bailouts.
  11882. bool isIndexNotInt = false;
  11883. IntConstType value = 0;
  11884. IR::Opnd * indexValueOpnd = nullptr;
  11885. bool invertBoundCheckComparison = false;
  11886. if (indirOpnd->TryGetIntConstIndexValue(true, &value, &isIndexNotInt))
  11887. {
  11888. if (value >= 0)
  11889. {
  11890. indexValueOpnd = IR::IntConstOpnd::New(value, TyUint32, this->m_func);
  11891. invertBoundCheckComparison = true; // facilitate folding the constant index into the compare instruction
  11892. }
  11893. else
  11894. {
  11895. // If the index is a negative int constant we go directly to helper.
  11896. Assert(!forceGenerateFastPath);
  11897. return nullptr;
  11898. }
  11899. }
  11900. else if (isIndexNotInt)
  11901. {
  11902. // If we know the index is not an int we go directly to helper.
  11903. Assert(!forceGenerateFastPath);
  11904. return nullptr;
  11905. }
  11906. //At this point indexValueOpnd is either NULL or contains the valueOpnd
  11907. if(!forceGenerateFastPath && !ShouldGenerateArrayFastPath(baseOpnd, true, true, true))
  11908. {
  11909. return nullptr;
  11910. }
  11911. if(baseValueType.IsLikelyAnyOptimizedArray())
  11912. {
  11913. indirScale = GetArrayIndirScale(baseValueType);
  11914. indirType = GetArrayIndirType(baseValueType);
  11915. }
  11916. IRType elementType = TyIllegal;
  11917. IR::Opnd * element = nullptr;
  11918. if(ldElem->m_opcode == Js::OpCode::InlineArrayPush)
  11919. {
  11920. element = ldElem->GetSrc2();
  11921. elementType = element->GetType();
  11922. }
  11923. else if(isStore && ldElem->GetSrc1())
  11924. {
  11925. element = ldElem->GetSrc1();
  11926. elementType = element->GetType();
  11927. }
  11928. Assert(isStore || (element == nullptr && elementType == TyIllegal));
  11929. if (isStore && baseValueType.IsLikelyNativeArray() && indirType != elementType)
  11930. {
  11931. // We're trying to write a value of the wrong type, which should force a conversion of the array.
  11932. // Go to the helper for that.
  11933. return nullptr;
  11934. }
  11935. IR::RegOpnd *arrayOpnd = baseOpnd;
  11936. IR::RegOpnd *headSegmentOpnd = nullptr;
  11937. IR::Opnd *headSegmentLengthOpnd = nullptr;
  11938. IR::AutoReuseOpnd autoReuseHeadSegmentOpnd, autoReuseHeadSegmentLengthOpnd;
  11939. bool indexIsNonnegative = indexValueOpnd || indexOpnd->GetType() == TyUint32 || !checkArrayLengthOverflow;
  11940. bool indexIsLessThanHeadSegmentLength = false;
  11941. if(!baseValueType.IsAnyOptimizedArray())
  11942. {
  11943. arrayOpnd = GenerateArrayTest(baseOpnd, labelCantUseArray, labelCantUseArray, ldElem, true, isStore);
  11944. }
  11945. else
  11946. {
  11947. if(arrayOpnd->IsArrayRegOpnd())
  11948. {
  11949. IR::ArrayRegOpnd *const arrayRegOpnd = arrayOpnd->AsArrayRegOpnd();
  11950. if(arrayRegOpnd->HeadSegmentSym())
  11951. {
  11952. headSegmentOpnd = IR::RegOpnd::New(arrayRegOpnd->HeadSegmentSym(), TyMachPtr, m_func);
  11953. DebugOnly(headSegmentOpnd->FreezeSymValue());
  11954. autoReuseHeadSegmentOpnd.Initialize(headSegmentOpnd, m_func);
  11955. }
  11956. if(arrayRegOpnd->HeadSegmentLengthSym())
  11957. {
  11958. headSegmentLengthOpnd = IR::RegOpnd::New(arrayRegOpnd->HeadSegmentLengthSym(), TyUint32, m_func);
  11959. DebugOnly(headSegmentLengthOpnd->AsRegOpnd()->FreezeSymValue());
  11960. autoReuseHeadSegmentLengthOpnd.Initialize(headSegmentLengthOpnd, m_func);
  11961. }
  11962. if (arrayRegOpnd->EliminatedLowerBoundCheck())
  11963. {
  11964. indexIsNonnegative = true;
  11965. }
  11966. if(arrayRegOpnd->EliminatedUpperBoundCheck())
  11967. {
  11968. indexIsLessThanHeadSegmentLength = true;
  11969. }
  11970. }
  11971. }
  11972. IR::AutoReuseOpnd autoReuseArrayOpnd;
  11973. if(arrayOpnd->GetValueType().GetObjectType() != ObjectType::ObjectWithArray)
  11974. {
  11975. autoReuseArrayOpnd.Initialize(arrayOpnd, m_func);
  11976. }
  11977. const auto EnsureObjectArrayLoaded = [&]()
  11978. {
  11979. if(arrayOpnd->GetValueType().GetObjectType() != ObjectType::ObjectWithArray)
  11980. {
  11981. return;
  11982. }
  11983. arrayOpnd = LoadObjectArray(arrayOpnd, ldElem);
  11984. autoReuseArrayOpnd.Initialize(arrayOpnd, m_func);
  11985. };
  11986. const bool doUpperBoundCheck = checkArrayLengthOverflow && !indexIsLessThanHeadSegmentLength;
  11987. if(!indexValueOpnd)
  11988. {
  11989. indexValueOpnd =
  11990. m_lowererMD.LoadNonnegativeIndex(
  11991. indexOpnd,
  11992. (
  11993. indexIsNonnegative
  11994. #if !INT32VAR
  11995. ||
  11996. // On 32-bit platforms, skip the negative check since for now, the unsigned upper bound check covers it
  11997. doUpperBoundCheck
  11998. #endif
  11999. ),
  12000. labelCantUseArray,
  12001. labelHelper,
  12002. ldElem);
  12003. }
  12004. const IR::AutoReuseOpnd autoReuseIndexValueOpnd(indexValueOpnd, m_func);
  12005. if (baseValueType.IsLikelyTypedArray())
  12006. {
  12007. *pIsTypedArrayElement = true;
  12008. if(doUpperBoundCheck)
  12009. {
  12010. if(!headSegmentLengthOpnd)
  12011. {
  12012. // (headSegmentLength = [base + offset(length)])
  12013. int lengthOffset;
  12014. lengthOffset = Js::Float64Array::GetOffsetOfLength();
  12015. headSegmentLengthOpnd = IR::IndirOpnd::New(arrayOpnd, lengthOffset, TyUint32, m_func);
  12016. autoReuseHeadSegmentLengthOpnd.Initialize(headSegmentLengthOpnd, m_func);
  12017. }
  12018. // CMP index, headSegmentLength -- upper bound check
  12019. if(!invertBoundCheckComparison)
  12020. {
  12021. InsertCompare(indexValueOpnd, headSegmentLengthOpnd, ldElem);
  12022. }
  12023. else
  12024. {
  12025. InsertCompare(headSegmentLengthOpnd, indexValueOpnd, ldElem);
  12026. }
  12027. }
  12028. }
  12029. else
  12030. {
  12031. *pIsTypedArrayElement = false;
  12032. if (isStore &&
  12033. baseValueType.IsLikelyNativeIntArray() &&
  12034. (!element->IsIntConstOpnd() || Js::SparseArraySegment<int32>::GetMissingItem() == element->AsIntConstOpnd()->AsInt32()))
  12035. {
  12036. Assert(ldElem->m_opcode != Js::OpCode::InlineArrayPush || bailOutLabelInstr);
  12037. // Check for a write of the MissingItem value.
  12038. InsertCompareBranch(
  12039. element,
  12040. GetMissingItemOpnd(elementType, m_func),
  12041. Js::OpCode::BrEq_A,
  12042. ldElem->m_opcode == Js::OpCode::InlineArrayPush ? bailOutLabelInstr : labelCantUseArray,
  12043. ldElem,
  12044. true);
  12045. }
  12046. if(!headSegmentOpnd)
  12047. {
  12048. EnsureObjectArrayLoaded();
  12049. // MOV headSegment, [base + offset(head)]
  12050. indirOpnd = IR::IndirOpnd::New(arrayOpnd, Js::JavascriptArray::GetOffsetOfHead(), TyMachPtr, this->m_func);
  12051. headSegmentOpnd = IR::RegOpnd::New(TyMachPtr, this->m_func);
  12052. autoReuseHeadSegmentOpnd.Initialize(headSegmentOpnd, m_func);
  12053. InsertMove(headSegmentOpnd, indirOpnd, ldElem);
  12054. }
  12055. if(doUpperBoundCheck)
  12056. {
  12057. if(!headSegmentLengthOpnd)
  12058. {
  12059. // (headSegmentLength = [headSegment + offset(length)])
  12060. headSegmentLengthOpnd =
  12061. IR::IndirOpnd::New(headSegmentOpnd, Js::SparseArraySegmentBase::GetOffsetOfLength(), TyUint32, m_func);
  12062. autoReuseHeadSegmentLengthOpnd.Initialize(headSegmentLengthOpnd, m_func);
  12063. }
  12064. // CMP index, headSegmentLength -- upper bound check
  12065. if(!invertBoundCheckComparison)
  12066. {
  12067. InsertCompare(indexValueOpnd, headSegmentLengthOpnd, ldElem);
  12068. }
  12069. else
  12070. {
  12071. InsertCompare(headSegmentLengthOpnd, indexValueOpnd, ldElem);
  12072. }
  12073. }
  12074. }
  12075. const IR::BailOutKind bailOutKind = ldElem->HasBailOutInfo() ? ldElem->GetBailOutKind() : IR::BailOutInvalid;
  12076. if(indexIsLessThanHeadSegmentLength ||
  12077. bailOutKind & (IR::BailOutOnArrayAccessHelperCall | IR::BailOutOnInvalidatedArrayHeadSegment))
  12078. {
  12079. if(bailOutKind & (IR::BailOutOnArrayAccessHelperCall | IR::BailOutOnInvalidatedArrayHeadSegment))
  12080. {
  12081. // The bailout must be pre-op because it will not have completed the operation
  12082. Assert(ldElem->GetBailOutInfo()->bailOutOffset == ldElem->GetByteCodeOffset());
  12083. // Verify other bailouts these can be combined with
  12084. Assert(
  12085. !(
  12086. bailOutKind &
  12087. IR::BailOutKindBits &
  12088. ~(
  12089. IR::BailOutOnArrayAccessHelperCall |
  12090. IR::BailOutOnInvalidatedArrayHeadSegment |
  12091. IR::BailOutOnInvalidatedArrayLength |
  12092. IR::BailOutConventionalNativeArrayAccessOnly |
  12093. (bailOutKind & IR::BailOutOnArrayAccessHelperCall ? IR::BailOutInvalid : IR::BailOutConvertedNativeArray)
  12094. )
  12095. ));
  12096. if(bailOutKind & IR::BailOutOnArrayAccessHelperCall)
  12097. {
  12098. // Omit the helper call and generate a bailout instead
  12099. Assert(emitBailoutRef);
  12100. *emitBailoutRef = true;
  12101. }
  12102. }
  12103. if(indexIsLessThanHeadSegmentLength)
  12104. {
  12105. Assert(!(bailOutKind & IR::BailOutOnInvalidatedArrayHeadSegment));
  12106. }
  12107. else
  12108. {
  12109. IR::LabelInstr *bailOutLabel;
  12110. if(bailOutKind & IR::BailOutOnInvalidatedArrayHeadSegment)
  12111. {
  12112. Assert(isStore);
  12113. // Lower a separate (but shared) bailout for this case, and preserve the bailout kind in the instruction if the
  12114. // helper call is going to be generated, because the bailout kind needs to be lowered again and differently in the
  12115. // helper call path.
  12116. //
  12117. // Generate:
  12118. // (LdElem)
  12119. // jmp $continue
  12120. // $bailOut:
  12121. // Bail out with IR::BailOutOnInvalidatedArrayHeadSegment
  12122. // $continue:
  12123. LowerOneBailOutKind(
  12124. ldElem,
  12125. IR::BailOutOnInvalidatedArrayHeadSegment,
  12126. false,
  12127. !(bailOutKind & IR::BailOutOnArrayAccessHelperCall));
  12128. bailOutLabel = ldElem->GetOrCreateContinueLabel(true);
  12129. InsertBranch(Js::OpCode::Br, labelFallthrough, bailOutLabel);
  12130. }
  12131. else
  12132. {
  12133. Assert(bailOutKind & IR::BailOutOnArrayAccessHelperCall);
  12134. bailOutLabel = labelHelper;
  12135. }
  12136. // Bail out if the index is outside the head segment bounds
  12137. // jae $bailOut
  12138. Assert(checkArrayLengthOverflow);
  12139. InsertBranch(
  12140. !invertBoundCheckComparison ? Js::OpCode::BrGe_A : Js::OpCode::BrLe_A,
  12141. true /* isUnsigned */,
  12142. bailOutLabel,
  12143. ldElem);
  12144. }
  12145. }
  12146. else if (isStore && !baseValueType.IsLikelyTypedArray()) // #if (opcode == StElemI_A)
  12147. {
  12148. IR::LabelInstr *labelDone = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  12149. IR::LabelInstr *labelSegmentLengthIncreased = nullptr;
  12150. const bool isPush = ldElem->m_opcode != Js::OpCode::StElemI_A && ldElem->m_opcode != Js::OpCode::StElemI_A_Strict;
  12151. // Put the head segment size check and length updates in a helper block since they're not the common path for StElem.
  12152. // For push, that is the common path so keep it in a non-helper block.
  12153. const bool isInHelperBlock = !isPush;
  12154. if(checkArrayLengthOverflow)
  12155. {
  12156. if(pLabelSegmentLengthIncreased &&
  12157. !(
  12158. baseValueType.IsArrayOrObjectWithArray() && baseValueType.HasNoMissingValues() ||
  12159. (ldElem->m_opcode == Js::OpCode::StElemI_A || ldElem->m_opcode == Js::OpCode::StElemI_A_Strict) &&
  12160. ldElem->IsProfiledInstr() && !ldElem->AsProfiledInstr()->u.stElemInfo->LikelyFillsMissingValue()
  12161. ))
  12162. {
  12163. // For arrays that are not guaranteed to have no missing values, before storing to an element where
  12164. // (index < length), the element value needs to be checked to see if it's a missing value, and if so, fall back
  12165. // to the helper. This is done to keep the missing value tracking precise in arrays. So, create a separate label
  12166. // for the case where the length was increased (index >= length), and pass it back to GenerateFastStElemI, which
  12167. // will fill in the rest.
  12168. labelSegmentLengthIncreased = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, isInHelperBlock);
  12169. *pLabelSegmentLengthIncreased = labelSegmentLengthIncreased;
  12170. }
  12171. else
  12172. {
  12173. labelSegmentLengthIncreased = labelDone;
  12174. }
  12175. // JB $done
  12176. InsertBranch(
  12177. !invertBoundCheckComparison ? Js::OpCode::BrLt_A : Js::OpCode::BrGt_A,
  12178. true /* isUnsigned */,
  12179. labelDone,
  12180. ldElem);
  12181. }
  12182. if(isInHelperBlock)
  12183. {
  12184. InsertLabel(true /* isHelper */, ldElem);
  12185. }
  12186. EnsureObjectArrayLoaded();
  12187. do // while(false);
  12188. {
  12189. if(checkArrayLengthOverflow)
  12190. {
  12191. if(ldElem->HasBailOutInfo() && ldElem->GetBailOutKind() & IR::BailOutOnMissingValue)
  12192. {
  12193. // Need to bail out if this store would create a missing value. The store would cause a missing value to be
  12194. // created if (index > length && index < size). If (index >= size) we would go to helper anyway, and the bailout
  12195. // handling for this is done after the helper call, so just go to helper if (index > length).
  12196. //
  12197. // jne $helper // branch for (cmp index, headSegmentLength)
  12198. InsertBranch(Js::OpCode::BrNeq_A, labelHelper, ldElem);
  12199. }
  12200. else
  12201. {
  12202. // If (index < size) we will not call the helper, so the array flags must be updated to reflect that it no
  12203. // longer has no missing values.
  12204. //
  12205. // jne indexGreaterThanLength // branch for (cmp index, headSegmentLength)
  12206. // cmp index, [headSegment + offset(size)]
  12207. // jae $helper
  12208. // jmp indexLessThanSize
  12209. // indexGreaterThanLength:
  12210. // cmp index, [headSegment + offset(size)]
  12211. // jae $helper
  12212. // and [array + offsetOf(objectArrayOrFlags)], ~Js::DynamicObjectFlags::HasNoMissingValues
  12213. // indexLessThanSize:
  12214. IR::LabelInstr *const indexGreaterThanLengthLabel = InsertLabel(true /* isHelper */, ldElem);
  12215. IR::LabelInstr *const indexLessThanSizeLabel = InsertLabel(isInHelperBlock, ldElem);
  12216. // jne indexGreaterThanLength // branch for (cmp index, headSegmentLength)
  12217. // cmp index, [headSegment + offset(size)]
  12218. // jae $helper
  12219. // jmp indexLessThanSize
  12220. // indexGreaterThanLength:
  12221. InsertBranch(Js::OpCode::BrNeq_A, indexGreaterThanLengthLabel, indexGreaterThanLengthLabel);
  12222. InsertCompareBranch(
  12223. indexValueOpnd,
  12224. IR::IndirOpnd::New(headSegmentOpnd, offsetof(Js::SparseArraySegmentBase, size), TyUint32, m_func),
  12225. Js::OpCode::BrGe_A,
  12226. true /* isUnsigned */,
  12227. labelHelper,
  12228. indexGreaterThanLengthLabel);
  12229. InsertBranch(Js::OpCode::Br, indexLessThanSizeLabel, indexGreaterThanLengthLabel);
  12230. // indexGreaterThanLength:
  12231. // cmp index, [headSegment + offset(size)]
  12232. // jae $helper
  12233. // and [array + offsetOf(objectArrayOrFlags)], ~Js::DynamicObjectFlags::HasNoMissingValues
  12234. // indexLessThanSize:
  12235. InsertCompareBranch(
  12236. indexValueOpnd,
  12237. IR::IndirOpnd::New(headSegmentOpnd, offsetof(Js::SparseArraySegmentBase, size), TyUint32, m_func),
  12238. Js::OpCode::BrGe_A,
  12239. true /* isUnsigned */,
  12240. labelHelper,
  12241. indexLessThanSizeLabel);
  12242. CompileAssert(
  12243. static_cast<Js::DynamicObjectFlags>(static_cast<uint8>(Js::DynamicObjectFlags::HasNoMissingValues)) ==
  12244. Js::DynamicObjectFlags::HasNoMissingValues);
  12245. InsertAnd(
  12246. IR::IndirOpnd::New(arrayOpnd, Js::JavascriptArray::GetOffsetOfArrayFlags(), TyUint8, m_func),
  12247. IR::IndirOpnd::New(arrayOpnd, Js::JavascriptArray::GetOffsetOfArrayFlags(), TyUint8, m_func),
  12248. IR::IntConstOpnd::New(
  12249. static_cast<uint8>(~Js::DynamicObjectFlags::HasNoMissingValues),
  12250. TyUint8,
  12251. m_func,
  12252. true),
  12253. indexLessThanSizeLabel);
  12254. // indexLessThanSize:
  12255. break;
  12256. }
  12257. }
  12258. // CMP index, [headSegment + offset(size)]
  12259. // JAE $helper
  12260. indirOpnd = IR::IndirOpnd::New(headSegmentOpnd, offsetof(Js::SparseArraySegmentBase, size), TyUint32, this->m_func);
  12261. InsertCompareBranch(indexValueOpnd, indirOpnd, Js::OpCode::BrGe_A, true /* isUnsigned */, labelHelper, ldElem);
  12262. } while(false);
  12263. if(isPush)
  12264. {
  12265. IR::LabelInstr *const updateLengthLabel = InsertLabel(isInHelperBlock, ldElem);
  12266. if(!doUpperBoundCheck && !headSegmentLengthOpnd)
  12267. {
  12268. // (headSegmentLength = [headSegment + offset(length)])
  12269. headSegmentLengthOpnd =
  12270. IR::IndirOpnd::New(headSegmentOpnd, Js::SparseArraySegmentBase::GetOffsetOfLength(), TyUint32, m_func);
  12271. autoReuseHeadSegmentLengthOpnd.Initialize(headSegmentLengthOpnd, m_func);
  12272. }
  12273. // For push, it is guaranteed that (index >= length). We already know that (index < size), but we need to check if
  12274. // (index > length) because in that case a missing value will be created and the missing value tracking in the array
  12275. // needs to be updated.
  12276. //
  12277. // cmp index, headSegmentLength
  12278. // je $updateLength
  12279. // and [array + offsetOf(objectArrayOrFlags)], ~Js::DynamicObjectFlags::HasNoMissingValues
  12280. // updateLength:
  12281. InsertCompareBranch(
  12282. indexValueOpnd,
  12283. headSegmentLengthOpnd,
  12284. Js::OpCode::BrEq_A,
  12285. updateLengthLabel,
  12286. updateLengthLabel);
  12287. CompileAssert(
  12288. static_cast<Js::DynamicObjectFlags>(static_cast<uint8>(Js::DynamicObjectFlags::HasNoMissingValues)) ==
  12289. Js::DynamicObjectFlags::HasNoMissingValues);
  12290. InsertAnd(
  12291. IR::IndirOpnd::New(arrayOpnd, Js::JavascriptArray::GetOffsetOfArrayFlags(), TyUint8, m_func),
  12292. IR::IndirOpnd::New(arrayOpnd, Js::JavascriptArray::GetOffsetOfArrayFlags(), TyUint8, m_func),
  12293. IR::IntConstOpnd::New(
  12294. static_cast<uint8>(~Js::DynamicObjectFlags::HasNoMissingValues),
  12295. TyUint8,
  12296. m_func,
  12297. true),
  12298. updateLengthLabel);
  12299. }
  12300. if (baseValueType.IsArrayOrObjectWithArray())
  12301. {
  12302. // We didn't emit an array check, but if we are going to grow the array
  12303. // We need to go to helper if there is an ES5 array/objectarray used as prototype
  12304. GenerateIsEnabledArraySetElementFastPathCheck(labelHelper, ldElem);
  12305. }
  12306. IR::Opnd *newLengthOpnd;
  12307. IR::AutoReuseOpnd autoReuseNewLengthOpnd;
  12308. if (indexValueOpnd->IsRegOpnd())
  12309. {
  12310. // LEA newLength, [index + 1]
  12311. newLengthOpnd = IR::RegOpnd::New(TyUint32, this->m_func);
  12312. autoReuseNewLengthOpnd.Initialize(newLengthOpnd, m_func);
  12313. InsertAdd(false /* needFlags */, newLengthOpnd, indexValueOpnd, IR::IntConstOpnd::New(1, TyUint32, m_func), ldElem);
  12314. }
  12315. else
  12316. {
  12317. newLengthOpnd = IR::IntConstOpnd::New(value + 1, TyUint32, this->m_func);
  12318. autoReuseNewLengthOpnd.Initialize(newLengthOpnd, m_func);
  12319. }
  12320. // MOV [headSegment + offset(length)], newLength
  12321. indirOpnd = IR::IndirOpnd::New(headSegmentOpnd, offsetof(Js::SparseArraySegmentBase, length), TyUint32, this->m_func);
  12322. InsertMove(indirOpnd, newLengthOpnd, ldElem);
  12323. if (checkArrayLengthOverflow)
  12324. {
  12325. // CMP newLength, [base + offset(length)]
  12326. // JBE $segmentLengthIncreased
  12327. Assert(labelSegmentLengthIncreased);
  12328. indirOpnd = IR::IndirOpnd::New(arrayOpnd, Js::JavascriptArray::GetOffsetOfLength(), TyUint32, this->m_func);
  12329. InsertCompareBranch(
  12330. newLengthOpnd,
  12331. indirOpnd,
  12332. Js::OpCode::BrLe_A,
  12333. true /* isUnsigned */,
  12334. labelSegmentLengthIncreased,
  12335. ldElem);
  12336. if(!isInHelperBlock)
  12337. {
  12338. InsertLabel(true /* isHelper */, ldElem);
  12339. }
  12340. }
  12341. // MOV [base + offset(length)], newLength
  12342. indirOpnd = IR::IndirOpnd::New(arrayOpnd, Js::JavascriptArray::GetOffsetOfLength(), TyUint32, this->m_func);
  12343. InsertMove(indirOpnd, newLengthOpnd, ldElem);
  12344. if(returnLength)
  12345. {
  12346. if(newLengthOpnd->GetSize() != MachPtr)
  12347. {
  12348. newLengthOpnd = newLengthOpnd->UseWithNewType(TyMachPtr, m_func)->AsRegOpnd();
  12349. }
  12350. // SHL newLength, AtomTag
  12351. // INC newLength
  12352. this->m_lowererMD.GenerateInt32ToVarConversion(newLengthOpnd, ldElem);
  12353. // MOV dst, newLength
  12354. InsertMove(ldElem->GetDst(), newLengthOpnd, ldElem);
  12355. }
  12356. if(labelSegmentLengthIncreased && labelSegmentLengthIncreased != labelDone)
  12357. {
  12358. // labelSegmentLengthIncreased:
  12359. ldElem->InsertBefore(labelSegmentLengthIncreased);
  12360. }
  12361. // $done
  12362. ldElem->InsertBefore(labelDone);
  12363. }
  12364. else // #else
  12365. {
  12366. if (checkArrayLengthOverflow)
  12367. {
  12368. if (*pIsTypedArrayElement && isStore)
  12369. {
  12370. IR::LabelInstr *labelInlineSet = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  12371. //For positive index beyond length or negative index its essentially nop for typed array store
  12372. InsertBranch(
  12373. !invertBoundCheckComparison ? Js::OpCode::BrLt_A : Js::OpCode::BrGt_A,
  12374. true /* isUnsigned */,
  12375. labelInlineSet,
  12376. ldElem);
  12377. // For typed array, call ToNumber before we fallThrough.
  12378. if (ldElem->GetSrc1()->GetType() == TyVar && !ldElem->GetSrc1()->GetValueType().IsPrimitive())
  12379. {
  12380. IR::Instr *toNumberInstr = IR::Instr::New(Js::OpCode::Call, this->m_func);
  12381. toNumberInstr->SetSrc1(ldElem->GetSrc1());
  12382. ldElem->InsertBefore(toNumberInstr);
  12383. LowerUnaryHelperMem(toNumberInstr, IR::HelperOp_ConvNumber_Full);
  12384. }
  12385. InsertBranch(Js::OpCode::Br, labelFallthrough, ldElem); //Jump to fallThrough
  12386. ldElem->InsertBefore(labelInlineSet);
  12387. }
  12388. else
  12389. {
  12390. // JAE $helper
  12391. InsertBranch(
  12392. !invertBoundCheckComparison ? Js::OpCode::BrGe_A : Js::OpCode::BrLe_A,
  12393. true /* isUnsigned */,
  12394. labelHelper,
  12395. ldElem);
  12396. }
  12397. }
  12398. EnsureObjectArrayLoaded();
  12399. if (ldElem->m_opcode == Js::OpCode::InlineArrayPop)
  12400. {
  12401. Assert(!baseValueType.IsLikelyTypedArray());
  12402. Assert(bailOutLabelInstr);
  12403. if (indexValueOpnd->IsIntConstOpnd())
  12404. {
  12405. // indirOpnd = [headSegment + index + offset(elements)]
  12406. IntConstType offset = offsetof(Js::SparseArraySegment<Js::Var>, elements) + (value << indirScale);
  12407. // TODO: Assert(Math::FitsInDWord(offset));
  12408. indirOpnd = IR::IndirOpnd::New(headSegmentOpnd, (int32)offset, indirType, this->m_func);
  12409. }
  12410. else
  12411. {
  12412. // indirOpnd = [headSegment + offset(elements) + (index << scale)]
  12413. indirOpnd = IR::IndirOpnd::New(headSegmentOpnd, indexValueOpnd->AsRegOpnd(), indirScale, indirType, this->m_func);
  12414. indirOpnd->SetOffset(offsetof(Js::SparseArraySegment<Js::Var>, elements));
  12415. }
  12416. IR::Opnd * tmpDst = nullptr;
  12417. IR::Opnd * dst = ldElem->GetDst();
  12418. //Pop might not have a dst, if not don't worry about returning the last element. But we still have to
  12419. // worry about gaps, because these force us to access the prototype chain, which may have side-effects.
  12420. if (dst || !baseValueType.HasNoMissingValues())
  12421. {
  12422. if (!dst)
  12423. {
  12424. dst = IR::RegOpnd::New(indirType, this->m_func);
  12425. }
  12426. else if (dst->AsRegOpnd()->m_sym == arrayOpnd->m_sym)
  12427. {
  12428. tmpDst = IR::RegOpnd::New(TyVar, this->m_func);
  12429. dst = tmpDst;
  12430. }
  12431. // MOV dst, [head + offset]
  12432. InsertMove(dst, indirOpnd, ldElem);
  12433. //If the array has missing values, check for one
  12434. if (!baseValueType.HasNoMissingValues())
  12435. {
  12436. InsertCompareBranch(
  12437. dst,
  12438. GetMissingItemOpnd(indirType, m_func),
  12439. Js::OpCode::BrEq_A,
  12440. bailOutLabelInstr,
  12441. ldElem,
  12442. true);
  12443. }
  12444. }
  12445. // MOV [head + offset], missing
  12446. InsertMove(indirOpnd, GetMissingItemOpnd(indirType, m_func), ldElem);
  12447. IR::Opnd *newLengthOpnd;
  12448. IR::AutoReuseOpnd autoReuseNewLengthOpnd;
  12449. if (indexValueOpnd->IsRegOpnd())
  12450. {
  12451. // LEA newLength, [index]
  12452. newLengthOpnd = indexValueOpnd;
  12453. autoReuseNewLengthOpnd.Initialize(newLengthOpnd, m_func);
  12454. }
  12455. else
  12456. {
  12457. newLengthOpnd = IR::IntConstOpnd::New(value, TyUint32, this->m_func);
  12458. autoReuseNewLengthOpnd.Initialize(newLengthOpnd, m_func);
  12459. }
  12460. //update segment length and array length
  12461. // MOV [headSegment + offset(length)], newLength
  12462. IR::IndirOpnd *lengthIndirOpnd = IR::IndirOpnd::New(headSegmentOpnd, offsetof(Js::SparseArraySegmentBase, length), TyUint32, this->m_func);
  12463. InsertMove(lengthIndirOpnd, newLengthOpnd, ldElem);
  12464. // MOV [base + offset(length)], newLength
  12465. lengthIndirOpnd = IR::IndirOpnd::New(arrayOpnd, Js::JavascriptArray::GetOffsetOfLength(), TyUint32, this->m_func);
  12466. InsertMove(lengthIndirOpnd, newLengthOpnd, ldElem);
  12467. if (tmpDst)
  12468. {
  12469. // The array opnd and the destination is the same, need to move the value in the tmp dst
  12470. // to the actual dst
  12471. InsertMove(ldElem->GetDst(), tmpDst, ldElem);
  12472. }
  12473. return indirOpnd;
  12474. }
  12475. } // #endif
  12476. if (baseValueType.IsLikelyTypedArray())
  12477. {
  12478. if(!headSegmentOpnd)
  12479. {
  12480. // MOV headSegment, [base + offset(arrayBuffer)]
  12481. int bufferOffset;
  12482. bufferOffset = Js::Float64Array::GetOffsetOfBuffer();
  12483. indirOpnd = IR::IndirOpnd::New(arrayOpnd, bufferOffset, TyMachPtr, this->m_func);
  12484. headSegmentOpnd = IR::RegOpnd::New(TyMachPtr, this->m_func);
  12485. autoReuseHeadSegmentOpnd.Initialize(headSegmentOpnd, m_func);
  12486. InsertMove(headSegmentOpnd, indirOpnd, ldElem);
  12487. }
  12488. // indirOpnd = [headSegment + index]
  12489. if (indexValueOpnd->IsIntConstOpnd())
  12490. {
  12491. IntConstType offset = (value << indirScale);
  12492. // TODO: Assert(Math::FitsInDWord(offset));
  12493. indirOpnd = IR::IndirOpnd::New(headSegmentOpnd, (int32)offset, indirType, this->m_func);
  12494. }
  12495. else
  12496. {
  12497. indirOpnd = IR::IndirOpnd::New(headSegmentOpnd, indexValueOpnd->AsRegOpnd(), indirScale, indirType, this->m_func);
  12498. }
  12499. }
  12500. else if (indexValueOpnd->IsIntConstOpnd())
  12501. {
  12502. // indirOpnd = [headSegment + index + offset(elements)]
  12503. IntConstType offset = offsetof(Js::SparseArraySegment<Js::Var>, elements) + (value << indirScale);
  12504. // TODO: Assert(Math::FitsInDWord(offset));
  12505. indirOpnd = IR::IndirOpnd::New(headSegmentOpnd, (int32)offset, indirType, this->m_func);
  12506. }
  12507. else
  12508. {
  12509. // indirOpnd = [headSegment + offset(elements) + (index << scale)]
  12510. indirOpnd = IR::IndirOpnd::New(headSegmentOpnd, indexValueOpnd->AsRegOpnd(), indirScale, indirType, this->m_func);
  12511. indirOpnd->SetOffset(offsetof(Js::SparseArraySegment<Js::Var>, elements));
  12512. }
  12513. return indirOpnd;
  12514. }
  12515. void
  12516. Lowerer::GenerateTypeIdCheck(Js::TypeId typeId, IR::RegOpnd * opnd, IR::LabelInstr * labelFail, IR::Instr * insertBeforeInstr, bool generateObjectCheck)
  12517. {
  12518. if (generateObjectCheck && !opnd->IsNotTaggedValue())
  12519. {
  12520. m_lowererMD.GenerateObjectTest(opnd, insertBeforeInstr, labelFail);
  12521. }
  12522. // MOV r1, [opnd + offset(type)]
  12523. IR::RegOpnd *r1 = IR::RegOpnd::New(TyMachReg, this->m_func);
  12524. const IR::AutoReuseOpnd autoReuseR1(r1, m_func);
  12525. IR::IndirOpnd *indirOpnd = IR::IndirOpnd::New(opnd, Js::RecyclableObject::GetOffsetOfType(), TyMachReg, this->m_func);
  12526. InsertMove(r1, indirOpnd, insertBeforeInstr);
  12527. // CMP [r1 + offset(typeId)], typeid -- check src isString
  12528. // JNE $fail
  12529. indirOpnd = IR::IndirOpnd::New(r1, Js::Type::GetOffsetOfTypeId(), TyInt32, this->m_func);
  12530. InsertCompareBranch(
  12531. indirOpnd,
  12532. IR::IntConstOpnd::New(typeId, TyInt32, this->m_func),
  12533. Js::OpCode::BrNeq_A,
  12534. labelFail,
  12535. insertBeforeInstr);
  12536. }
  12537. IR::RegOpnd *
  12538. Lowerer::GenerateUntagVar(IR::RegOpnd * opnd, IR::LabelInstr * labelFail, IR::Instr * insertBeforeInstr, bool generateTagCheck)
  12539. {
  12540. if (!opnd->IsVar())
  12541. {
  12542. AssertMsg(opnd->GetSize() == 4, "This should be 32-bit wide");
  12543. return opnd;
  12544. }
  12545. return m_lowererMD.GenerateUntagVar(opnd, labelFail, insertBeforeInstr, generateTagCheck && !opnd->IsTaggedInt());
  12546. }
  12547. void
  12548. Lowerer::GenerateNotZeroTest( IR::Opnd * opndSrc, IR::LabelInstr * isZeroLabel, IR::Instr * insertBeforeInstr)
  12549. {
  12550. InsertTestBranch(opndSrc, opndSrc, Js::OpCode::BrEq_A, isZeroLabel, insertBeforeInstr);
  12551. }
  12552. bool
  12553. Lowerer::GenerateFastStringLdElem(IR::Instr * ldElem, IR::LabelInstr * labelHelper, IR::LabelInstr * labelFallThru)
  12554. {
  12555. IR::IndirOpnd * indirOpnd = ldElem->GetSrc1()->AsIndirOpnd();
  12556. IR::RegOpnd * baseOpnd = indirOpnd->GetBaseOpnd();
  12557. // don't generate the fast path if the instance is not likely string
  12558. if (!baseOpnd->GetValueType().IsLikelyString())
  12559. {
  12560. return false;
  12561. }
  12562. Assert(!baseOpnd->IsTaggedInt());
  12563. IR::RegOpnd * indexOpnd = indirOpnd->GetIndexOpnd();
  12564. // Don't generate the fast path if the index operand is not likely int
  12565. if (indexOpnd && !indexOpnd->GetValueType().IsLikelyInt())
  12566. {
  12567. return false;
  12568. }
  12569. // Make sure the instance is a string
  12570. Assert(!indexOpnd || !indexOpnd->IsNotInt());
  12571. GenerateStringTest(baseOpnd, ldElem, labelHelper);
  12572. IR::Opnd * index32CmpOpnd;
  12573. IR::RegOpnd * bufferOpnd = IR::RegOpnd::New(TyMachPtr, this->m_func);
  12574. const IR::AutoReuseOpnd autoReuseBufferOpnd(bufferOpnd, m_func);
  12575. IR::IndirOpnd * charIndirOpnd;
  12576. if (indexOpnd)
  12577. {
  12578. // Untag the var and generate the indir into the string buffer
  12579. IR::RegOpnd * index32Opnd = GenerateUntagVar(indexOpnd, labelHelper, ldElem);
  12580. charIndirOpnd = IR::IndirOpnd::New(bufferOpnd, index32Opnd, 1, TyUint16, this->m_func);
  12581. index32CmpOpnd = index32Opnd;
  12582. }
  12583. else
  12584. {
  12585. // Just use the offset to indirect into the string buffer
  12586. charIndirOpnd = IR::IndirOpnd::New(bufferOpnd, indirOpnd->GetOffset() * sizeof(wchar_t), TyUint16, this->m_func);
  12587. index32CmpOpnd = IR::IntConstOpnd::New(indirOpnd->GetOffset(), TyUint32, this->m_func);
  12588. }
  12589. // Check if the index is in range of the string length
  12590. // CMP [baseOpnd + offset(length)], indexOpnd -- string length
  12591. // JBE $helper -- unsigned compare, and string length are at most INT_MAX - 1
  12592. // -- so that even if we have a negative index, this will fail
  12593. InsertCompareBranch(IR::IndirOpnd::New(baseOpnd, offsetof(Js::JavascriptString, m_charLength), TyInt32, this->m_func)
  12594. , index32CmpOpnd, Js::OpCode::BrLe_A, true, labelHelper, ldElem);
  12595. // Load the string buffer and make sure it is not null
  12596. // MOV bufferOpnd, [baseOpnd + offset(m_pszValue)]
  12597. // TEST bufferOpnd, bufferOpnd
  12598. // JEQ $lableHelper
  12599. indirOpnd = IR::IndirOpnd::New(baseOpnd, offsetof(Js::JavascriptString, m_pszValue), TyMachPtr, this->m_func);
  12600. InsertMove(bufferOpnd, indirOpnd, ldElem);
  12601. GenerateNotZeroTest(bufferOpnd, labelHelper, ldElem);
  12602. // Load the character and check if it is 7bit ASCI (which we have the cache for)
  12603. // MOV charOpnd, [bufferOpnd + index32Opnd]
  12604. // CMP charOpnd, 0x80
  12605. // JAE $helper
  12606. IR::RegOpnd * charOpnd = IR::RegOpnd::New(TyInt32, this->m_func);
  12607. const IR::AutoReuseOpnd autoReuseCharOpnd(charOpnd, m_func);
  12608. InsertMove(charOpnd, charIndirOpnd, ldElem);
  12609. InsertCompareBranch(charOpnd, IR::IntConstOpnd::New(Js::CharStringCache::CharStringCacheSize, TyUint16, this->m_func),
  12610. Js::OpCode::BrGe_A, true, labelHelper, ldElem);
  12611. // Load the string from the cache
  12612. // MOV charStringCache, <charStringCache, address>
  12613. // MOV stringOpnd, [charStringCache + charOpnd * 4]
  12614. IR::RegOpnd * cacheOpnd = IR::RegOpnd::New(TyMachPtr, this->m_func);
  12615. const IR::AutoReuseOpnd autoReuseCacheOpnd(cacheOpnd, m_func);
  12616. Assert(Js::JavascriptLibrary::GetCharStringCacheAOffset() == Js::JavascriptLibrary::GetCharStringCacheOffset());
  12617. InsertMove(cacheOpnd, this->LoadLibraryValueOpnd(ldElem, LibraryValue::ValueCharStringCache), ldElem);
  12618. // Check if we have created the string or not
  12619. // TEST stringOpnd, stringOpnd
  12620. // JE $helper
  12621. IR::RegOpnd * stringOpnd = IR::RegOpnd::New(TyMachPtr, this->m_func);
  12622. const IR::AutoReuseOpnd autoReuseStringOpnd(stringOpnd, m_func);
  12623. InsertMove(stringOpnd, IR::IndirOpnd::New(cacheOpnd, charOpnd, this->m_lowererMD.GetDefaultIndirScale(), TyVar, this->m_func), ldElem);
  12624. GenerateNotZeroTest(stringOpnd, labelHelper, ldElem);
  12625. InsertMove(ldElem->GetDst(), stringOpnd, ldElem);
  12626. InsertBranch(Js::OpCode::Br, labelFallThru, ldElem);
  12627. return true;
  12628. }
  12629. bool
  12630. Lowerer::GenerateFastLdElemI(IR::Instr *& ldElem, bool *instrIsInHelperBlockRef)
  12631. {
  12632. Assert(instrIsInHelperBlockRef);
  12633. bool &instrIsInHelperBlock = *instrIsInHelperBlockRef;
  12634. instrIsInHelperBlock = false;
  12635. IR::LabelInstr * labelHelper;
  12636. IR::LabelInstr * labelFallThru;
  12637. IR::LabelInstr * labelBailOut = nullptr;
  12638. IR::LabelInstr * labelMissingNative = nullptr;
  12639. IR::Opnd *src1 = ldElem->GetSrc1();
  12640. AssertMsg(src1->IsIndirOpnd(), "Expected indirOpnd on LdElementI");
  12641. IR::IndirOpnd * indirOpnd = src1->AsIndirOpnd();
  12642. // From FastElemICommon:
  12643. // TEST base, AtomTag -- check base not tagged int
  12644. // JNE $helper
  12645. // MOV r1, [base + offset(type)] -- check base isArray
  12646. // CMP [r1 + offset(typeId)], TypeIds_Array
  12647. // JNE $helper
  12648. // TEST index, 1 -- index tagged int
  12649. // JEQ $helper
  12650. // MOV r2, index
  12651. // SAR r2, Js::VarTag_Shift -- remote atom tag
  12652. // JS $helper -- exclude negative index
  12653. // MOV r4, [base + offset(head)]
  12654. // CMP r2, [r4 + offset(length)] -- bounds check
  12655. // JAE $helper
  12656. // MOV r3, [r4 + offset(elements)]
  12657. // Generated here:
  12658. // MOV dst, [r3 + r2]
  12659. // TEST dst, dst
  12660. // JNE $fallthrough
  12661. if(ldElem->m_opcode == Js::OpCode::LdMethodElem && indirOpnd->GetBaseOpnd()->GetValueType().IsLikelyOptimizedTypedArray())
  12662. {
  12663. // Typed arrays don't return objects, so it's not worth generating a fast path for LdMethodElem. Calling the helper also
  12664. // generates a better error message. Skip the fast path and just generate a helper call.
  12665. return true;
  12666. }
  12667. labelFallThru = ldElem->GetOrCreateContinueLabel();
  12668. labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  12669. // If we know for sure (based on flow graph) we're loading from the arguments object, then ignore the (path-based) profile info.
  12670. bool isNativeArrayLoad = !ldElem->DoStackArgsOpt(this->m_func) && indirOpnd->GetBaseOpnd()->GetValueType().IsLikelyNativeArray();
  12671. bool needMissingValueCheck = true;
  12672. bool emittedFastPath = false;
  12673. bool emitBailout = false;
  12674. if (ldElem->DoStackArgsOpt(this->m_func))
  12675. {
  12676. emittedFastPath = GenerateFastArgumentsLdElemI(ldElem, labelHelper, labelFallThru);
  12677. }
  12678. else if (GenerateFastStringLdElem(ldElem, labelHelper, labelFallThru))
  12679. {
  12680. emittedFastPath = true;
  12681. }
  12682. else
  12683. {
  12684. IR::LabelInstr * labelCantUseArray = labelHelper;
  12685. if (isNativeArrayLoad)
  12686. {
  12687. if (ldElem->GetDst()->GetType() == TyVar)
  12688. {
  12689. // Skip the fast path and just generate a helper call
  12690. return true;
  12691. }
  12692. // Specialized native array lowering for LdElem requires that it is profiled. When not profiled, GlobOpt should not
  12693. // have specialized it.
  12694. Assert(ldElem->IsProfiledInstr());
  12695. labelBailOut = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  12696. labelCantUseArray = labelBailOut;
  12697. }
  12698. bool isTypedArrayElement, isStringIndex;
  12699. indirOpnd =
  12700. GenerateFastElemICommon(
  12701. ldElem,
  12702. false,
  12703. src1->AsIndirOpnd(),
  12704. labelHelper,
  12705. labelCantUseArray,
  12706. labelFallThru,
  12707. &isTypedArrayElement,
  12708. &isStringIndex,
  12709. &emitBailout);
  12710. IR::Opnd *dst = ldElem->GetDst();
  12711. IRType dstType = dst->AsRegOpnd()->GetType();
  12712. // The index is negative or not int.
  12713. if (indirOpnd == nullptr)
  12714. {
  12715. Assert(!(ldElem->HasBailOutInfo() && ldElem->GetBailOutKind() & IR::BailOutOnArrayAccessHelperCall));
  12716. // The global optimizer should never type specialize a LdElem for which the index is not int or an integer constant
  12717. // with a negative value. This would force an unconditional bail out on the main code path.
  12718. if (dst->IsVar())
  12719. {
  12720. if (PHASE_TRACE(Js::TypedArrayTypeSpecPhase, this->m_func) && PHASE_TRACE(Js::LowererPhase, this->m_func))
  12721. {
  12722. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  12723. Output::Print(L"Typed Array Lowering: function: %s (%s): instr %s, not specialized by glob opt due to negative or not likely int index.\n",
  12724. this->m_func->GetJnFunction()->GetDisplayName(),
  12725. this->m_func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  12726. Js::OpCodeUtil::GetOpCodeName(ldElem->m_opcode));
  12727. Output::Flush();
  12728. }
  12729. // We must be dealing with some unconventional index value. Don't emit fast path, but go directly to helper.
  12730. emittedFastPath = false;
  12731. return true;
  12732. }
  12733. else
  12734. {
  12735. AssertMsg(false, "Global optimizer shouldn't have specialized this instruction.");
  12736. Assert(dst->IsRegOpnd());
  12737. // If global optimizer failed to notice the unconventional index and type specialized the dst,
  12738. // there is nothing to do but bail out. This could happen if global optimizer's information based
  12739. // on value tracking fails to recognize a non-integer index or a constant int index that is negative.
  12740. // The bailout below ensures that we behave correctly in retail builds even under
  12741. // these (unlikely) conditions. To satisfy the downstream code we must populate the type specialized operand
  12742. // with some made up values, even though we will unconditionally bail out here and the values will never be
  12743. // used.
  12744. IR::IntConstOpnd *constOpnd = IR::IntConstOpnd::New(0, TyInt32, this->m_func, true);
  12745. InsertMove(dst, constOpnd, ldElem);
  12746. ldElem->UnlinkSrc1();
  12747. ldElem->UnlinkDst();
  12748. GenerateBailOut(ldElem, nullptr, nullptr);
  12749. emittedFastPath = true;
  12750. return false;
  12751. }
  12752. }
  12753. const IR::AutoReuseOpnd autoReuseIndirOpnd(indirOpnd, m_func);
  12754. const ValueType baseValueType(src1->AsIndirOpnd()->GetBaseOpnd()->GetValueType());
  12755. if (ldElem->HasBailOutInfo() &&
  12756. ldElem->GetByteCodeOffset() != Js::Constants::NoByteCodeOffset &&
  12757. ldElem->GetBailOutInfo()->bailOutOffset <= ldElem->GetByteCodeOffset() &&
  12758. dst->IsEqual(src1->AsIndirOpnd()->GetBaseOpnd()) ||
  12759. (src1->AsIndirOpnd()->GetIndexOpnd() && dst->IsEqual(src1->AsIndirOpnd()->GetIndexOpnd())))
  12760. {
  12761. // This is a pre-op bailout where the dst is the same as one of the srcs. The dst may be trashed before bailing out,
  12762. // but since the operation will be processed again in the interpreter, src values need to be kept intact. Use a
  12763. // temporary dst until after the operation is complete.
  12764. IR::Instr *instrSink = ldElem->SinkDst(Js::OpCode::Ld_A);
  12765. // The sink instruction needs to be on the fall-through path
  12766. instrSink->Unlink();
  12767. labelFallThru->InsertAfter(instrSink);
  12768. LowererMD::ChangeToAssign(instrSink);
  12769. dst = ldElem->GetDst();
  12770. }
  12771. if (isTypedArrayElement)
  12772. {
  12773. // For typedArrays, convert the loaded element to the appropriate type
  12774. IR::RegOpnd *reg;
  12775. IR::AutoReuseOpnd autoReuseReg;
  12776. Assert(dst->IsRegOpnd());
  12777. if(indirOpnd->IsFloat())
  12778. {
  12779. AssertMsg((dstType == TyFloat64) || (dstType == TyVar), "For Float32Array LdElemI's dst should be specialized to TyFloat64 or not at all.");
  12780. if(indirOpnd->IsFloat32())
  12781. {
  12782. // MOVSS reg32.f32, indirOpnd.f32
  12783. IR::RegOpnd *reg32 = IR::RegOpnd::New(TyFloat32, this->m_func);
  12784. const IR::AutoReuseOpnd autoReuseReg32(reg32, m_func);
  12785. InsertMove(reg32, indirOpnd, ldElem);
  12786. // CVTPS2PD dst/reg.f64, reg32.f64
  12787. reg = dstType == TyFloat64 ? dst->AsRegOpnd() : IR::RegOpnd::New(TyFloat64, this->m_func);
  12788. autoReuseReg.Initialize(reg, m_func);
  12789. InsertConvertFloat32ToFloat64(reg, reg32, ldElem);
  12790. }
  12791. else
  12792. {
  12793. Assert(indirOpnd->IsFloat64());
  12794. // MOVSD dst/reg.f64, indirOpnd.f64
  12795. reg = dstType == TyFloat64 ? dst->AsRegOpnd() : IR::RegOpnd::New(TyFloat64, this->m_func);
  12796. autoReuseReg.Initialize(reg, m_func);
  12797. InsertMove(reg, indirOpnd, ldElem);
  12798. }
  12799. if (dstType != TyFloat64)
  12800. {
  12801. // Convert reg.f64 to var
  12802. m_lowererMD.SaveDoubleToVar(dst->AsRegOpnd(), reg, ldElem, ldElem);
  12803. }
  12804. #if FLOATVAR
  12805. // For NaNs, go to the helper to guarantee we don't have an illegal NaN
  12806. // UCOMISD reg, reg
  12807. {
  12808. IR::Instr *const instr = IR::Instr::New(Js::OpCode::UCOMISD, this->m_func);
  12809. instr->SetSrc1(reg);
  12810. instr->SetSrc2(reg);
  12811. ldElem->InsertBefore(instr);
  12812. }
  12813. // JP $helper
  12814. {
  12815. IR::Instr *const instr = IR::BranchInstr::New(Js::OpCode::JP, labelHelper, this->m_func);
  12816. ldElem->InsertBefore(instr);
  12817. }
  12818. #endif
  12819. if(dstType == TyFloat64)
  12820. {
  12821. emitBailout = true;
  12822. }
  12823. }
  12824. else
  12825. {
  12826. AssertMsg((dstType == TyInt32) || (dstType == TyVar), "For Int/UintArray LdElemI's dst should be specialized to TyInt32 or not at all.");
  12827. reg = dstType == TyInt32 ? dst->AsRegOpnd() : IR::RegOpnd::New(TyInt32, this->m_func);
  12828. const IR::AutoReuseOpnd autoReuseReg(reg, m_func);
  12829. // Int32 and Uint32 arrays could overflow an int31, but the others can't
  12830. if (indirOpnd->GetType() != TyUint32
  12831. #if !INT32VAR
  12832. && indirOpnd->GetType() != TyInt32
  12833. #endif
  12834. )
  12835. {
  12836. reg->SetValueType(ValueType::GetTaggedInt()); // Fits as a tagged-int
  12837. }
  12838. // MOV/MOVZX/MOVSX dst/reg.int32, IndirOpnd.type
  12839. IR::Instr *const instr = InsertMove(reg, indirOpnd, ldElem);
  12840. if (dstType == TyInt32)
  12841. {
  12842. instr->dstIsTempNumber = ldElem->dstIsTempNumber;
  12843. instr->dstIsTempNumberTransferred = ldElem->dstIsTempNumberTransferred;
  12844. if (indirOpnd->GetType() == TyUint32)
  12845. {
  12846. // TEST dst, dst
  12847. // JSB $helper (bailout)
  12848. InsertCompareBranch(
  12849. reg,
  12850. IR::IntConstOpnd::New(0, TyUint32, this->m_func, /* dontEncode = */ true),
  12851. Js::OpCode::BrLt_A,
  12852. labelHelper,
  12853. ldElem);
  12854. }
  12855. emitBailout = true;
  12856. }
  12857. else
  12858. {
  12859. // MOV dst, reg
  12860. IR::Instr *const instr = IR::Instr::New(Js::OpCode::ToVar, dst, reg, this->m_func);
  12861. instr->dstIsTempNumber = ldElem->dstIsTempNumber;
  12862. instr->dstIsTempNumberTransferred = ldElem->dstIsTempNumberTransferred;
  12863. ldElem->InsertBefore(instr);
  12864. // Convert dst to var
  12865. m_lowererMD.EmitLoadVar(instr, /* isFromUint32 = */ (indirOpnd->GetType() == TyUint32));
  12866. }
  12867. }
  12868. // JMP $fallthrough
  12869. InsertBranch(Js::OpCode::Br, labelFallThru, ldElem);
  12870. emittedFastPath = true;
  12871. if (PHASE_TRACE(Js::TypedArrayTypeSpecPhase, this->m_func) && PHASE_TRACE(Js::LowererPhase, this->m_func))
  12872. {
  12873. char baseValueTypeStr[VALUE_TYPE_MAX_STRING_SIZE];
  12874. baseValueType.ToString(baseValueTypeStr);
  12875. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  12876. Output::Print(L"Typed Array Lowering: function: %s (%s), instr: %s, base value type: %S, %s.",
  12877. this->m_func->GetJnFunction()->GetDisplayName(),
  12878. this->m_func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  12879. Js::OpCodeUtil::GetOpCodeName(ldElem->m_opcode),
  12880. baseValueTypeStr,
  12881. (!dst->IsVar() ? L"specialized" : L"not specialized"));
  12882. Output::Print(L"\n");
  12883. Output::Flush();
  12884. }
  12885. }
  12886. else
  12887. {
  12888. // MOV dst, indirOpnd
  12889. InsertMove(dst, indirOpnd, ldElem);
  12890. // The string index fast path does not operate on index properties (we don't get a PropertyString in that case), so
  12891. // we don't need to do any further checks in that case
  12892. // For LdMethodElem, if the loaded value is a tagged number, the error message generated by the helper call is
  12893. // better than if we were to just try to call the number. Also, the call arguments need to be evaluated before
  12894. // throwing the error, so just test whether it's an object and jump to helper if it's not.
  12895. const bool needObjectTest = !isStringIndex && !isNativeArrayLoad && ldElem->m_opcode == Js::OpCode::LdMethodElem;
  12896. needMissingValueCheck =
  12897. !isStringIndex && !(baseValueType.IsArrayOrObjectWithArray() && baseValueType.HasNoMissingValues());
  12898. if(needMissingValueCheck)
  12899. {
  12900. // TEST dst, dst
  12901. // JEQ $helper | JNE $fallthrough
  12902. InsertCompareBranch(
  12903. dst,
  12904. GetMissingItemOpnd(dst->GetType(), m_func),
  12905. needObjectTest ? Js::OpCode::BrEq_A : Js::OpCode::BrNeq_A,
  12906. needObjectTest ? labelHelper : labelFallThru,
  12907. ldElem,
  12908. true);
  12909. if (isNativeArrayLoad)
  12910. {
  12911. Assert(!needObjectTest);
  12912. Assert(labelHelper != labelBailOut);
  12913. if(ldElem->AsProfiledInstr()->u.ldElemInfo->GetElementType().HasBeenUndefined())
  12914. {
  12915. // We're going to bail out trying to load "missing value" into a type-spec'd opnd.
  12916. // Branch to a point where we'll convert the array so that we don't keep bailing here.
  12917. // (Gappy arrays are not well-suited to nativeness.)
  12918. labelMissingNative = IR::LabelInstr::New(Js::OpCode::Label, m_func, true);
  12919. InsertBranch(Js::OpCode::Br, labelMissingNative, ldElem);
  12920. }
  12921. else
  12922. {
  12923. // If the value has not been profiled to be undefined at some point, jump directly to bail out
  12924. InsertBranch(Js::OpCode::Br, labelBailOut, ldElem);
  12925. }
  12926. }
  12927. }
  12928. if(needObjectTest)
  12929. {
  12930. // GenerateObjectTest(dst)
  12931. // JIsObject $fallthrough
  12932. m_lowererMD.GenerateObjectTest(dst, ldElem, labelFallThru, true);
  12933. }
  12934. else if(!needMissingValueCheck)
  12935. {
  12936. // JMP $fallthrough
  12937. InsertBranch(Js::OpCode::Br, labelFallThru, ldElem);
  12938. }
  12939. emittedFastPath = true;
  12940. }
  12941. }
  12942. // $helper:
  12943. // bailout or caller generated helper call
  12944. // $fallthru:
  12945. if (!emittedFastPath)
  12946. {
  12947. labelHelper->isOpHelper = false;
  12948. }
  12949. ldElem->InsertBefore(labelHelper);
  12950. instrIsInHelperBlock = true;
  12951. if (isNativeArrayLoad)
  12952. {
  12953. Assert(ldElem->HasBailOutInfo());
  12954. Assert(labelHelper != labelBailOut);
  12955. // Transform the original instr:
  12956. //
  12957. // $helper:
  12958. // dst = LdElemI_A src (BailOut)
  12959. // $fallthrough:
  12960. //
  12961. // to:
  12962. //
  12963. // b $fallthru <--- we get here if we loaded a valid element directly
  12964. // $helper:
  12965. // dst = LdElemI_A src
  12966. // cmp dst, MissingItem
  12967. // bne $fallthrough
  12968. // $bailout:
  12969. // BailOut
  12970. // $fallthrough:
  12971. LowerOneBailOutKind(ldElem, IR::BailOutConventionalNativeArrayAccessOnly, instrIsInHelperBlock);
  12972. IR::Instr *const insertBeforeInstr = ldElem->m_next;
  12973. // Do missing value check on value returned from helper so that we don't have to check the index against
  12974. // array length. (We already checked it above against the segment length.)
  12975. bool hasBeenUndefined = ldElem->AsProfiledInstr()->u.ldElemInfo->GetElementType().HasBeenUndefined();
  12976. if (hasBeenUndefined)
  12977. {
  12978. if(!emitBailout)
  12979. {
  12980. if (labelMissingNative == nullptr)
  12981. {
  12982. labelMissingNative = IR::LabelInstr::New(Js::OpCode::Label, m_func, true);
  12983. }
  12984. InsertCompareBranch(GetMissingItemOpnd(ldElem->GetDst()->GetType(), m_func), ldElem->GetDst(), Js::OpCode::BrEq_A, labelMissingNative, insertBeforeInstr, true);
  12985. }
  12986. InsertBranch(Js::OpCode::Br, labelFallThru, insertBeforeInstr);
  12987. if(labelMissingNative)
  12988. {
  12989. // We're going to bail out on a load from a gap, but convert the array to Var first, so we don't just
  12990. // bail here over and over. Gappy arrays are not well suited to nativeness.
  12991. // NOTE: only emit this call if the profile tells us that this has happened before ("hasBeenUndefined").
  12992. // Emitting this in Navier-Stokes brutalizes the score.
  12993. insertBeforeInstr->InsertBefore(labelMissingNative);
  12994. IR::JnHelperMethod helperMethod;
  12995. indirOpnd = ldElem->GetSrc1()->AsIndirOpnd();
  12996. if (indirOpnd->GetBaseOpnd()->GetValueType().HasIntElements())
  12997. {
  12998. helperMethod = IR::HelperIntArr_ToVarArray;
  12999. }
  13000. else
  13001. {
  13002. Assert(indirOpnd->GetBaseOpnd()->GetValueType().HasFloatElements());
  13003. helperMethod = IR::HelperFloatArr_ToVarArray;
  13004. }
  13005. m_lowererMD.LoadHelperArgument(insertBeforeInstr, indirOpnd->GetBaseOpnd());
  13006. IR::Instr *instrHelper = IR::Instr::New(Js::OpCode::Call, m_func);
  13007. instrHelper->SetSrc1(IR::HelperCallOpnd::New(helperMethod, m_func));
  13008. insertBeforeInstr->InsertBefore(instrHelper);
  13009. m_lowererMD.LowerCall(instrHelper, 0);
  13010. }
  13011. }
  13012. else
  13013. {
  13014. if(!emitBailout)
  13015. {
  13016. InsertCompareBranch(GetMissingItemOpnd(ldElem->GetDst()->GetType(), m_func), ldElem->GetDst(), Js::OpCode::BrEq_A, labelBailOut, insertBeforeInstr, true);
  13017. }
  13018. InsertBranch(Js::OpCode::Br, labelFallThru, insertBeforeInstr);
  13019. }
  13020. insertBeforeInstr->InsertBefore(labelBailOut);
  13021. }
  13022. if (emitBailout)
  13023. {
  13024. ldElem->UnlinkSrc1();
  13025. ldElem->UnlinkDst();
  13026. GenerateBailOut(ldElem, nullptr, nullptr);
  13027. }
  13028. return !emitBailout;
  13029. }
  13030. IR::Opnd *
  13031. Lowerer::GetMissingItemOpnd(IRType type, Func *func)
  13032. {
  13033. if (type == TyVar)
  13034. {
  13035. return IR::AddrOpnd::New(Js::JavascriptArray::MissingItem, IR::AddrOpndKindConstant, func, true);
  13036. }
  13037. if (type == TyInt32)
  13038. {
  13039. return IR::IntConstOpnd::New(Js::JavascriptNativeIntArray::MissingItem, TyInt32, func, true);
  13040. }
  13041. Assert(type == TyFloat64);
  13042. return IR::MemRefOpnd::New((BYTE*)&Js::JavascriptNativeFloatArray::MissingItem, TyFloat64, func);
  13043. }
  13044. bool
  13045. Lowerer::GenerateFastStElemI(IR::Instr *& stElem, bool *instrIsInHelperBlockRef)
  13046. {
  13047. Assert(instrIsInHelperBlockRef);
  13048. bool &instrIsInHelperBlock = *instrIsInHelperBlockRef;
  13049. instrIsInHelperBlock = false;
  13050. IR::LabelInstr * labelHelper;
  13051. IR::LabelInstr * labelSegmentLengthIncreased;
  13052. IR::LabelInstr * labelFallThru;
  13053. IR::LabelInstr * labelBailOut = nullptr;
  13054. IR::Opnd *dst = stElem->GetDst();
  13055. IR::IndirOpnd * indirOpnd = dst->AsIndirOpnd();
  13056. AssertMsg(dst->IsIndirOpnd(), "Expected indirOpnd on StElementI");
  13057. // From FastElemICommon:
  13058. // TEST base, AtomTag -- check base not tagged int
  13059. // JNE $helper
  13060. // MOV r1, [base + offset(type)] -- check base isArray
  13061. // CMP [r1 + offset(typeId)], TypeIds_Array
  13062. // JNE $helper
  13063. // TEST index, 1 -- index tagged int
  13064. // JEQ $helper
  13065. // MOV r2, index
  13066. // SAR r2, Js::VarTag_Shift -- remote atom tag
  13067. // JS $helper -- exclude negative index
  13068. // MOV r4, [base + offset(head)]
  13069. // CMP r2, [r4 + offset(length)] -- bounds check
  13070. // JB $done
  13071. // CMP r2, [r4 + offset(size)] -- chunk has room?
  13072. // JAE $helper
  13073. // LEA r5, [r2 + 1]
  13074. // MOV [r4 + offset(length)], r5 -- update length on chunk
  13075. // CMP r5, [base + offset(length)]
  13076. // JBE $done
  13077. // MOV [base + offset(length)], r5 -- update length on array
  13078. // $done
  13079. // LEA r3, [r4 + offset(elements)]
  13080. // Generated here.
  13081. // MOV [r3 + r2], src
  13082. labelFallThru = stElem->GetOrCreateContinueLabel();
  13083. labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  13084. bool emitBailout = false;
  13085. bool isNativeArrayStore = indirOpnd->GetBaseOpnd()->GetValueType().IsLikelyNativeArray();
  13086. IR::LabelInstr * labelCantUseArray = labelHelper;
  13087. if (isNativeArrayStore)
  13088. {
  13089. if (stElem->GetSrc1()->GetType() != GetArrayIndirType(indirOpnd->GetBaseOpnd()->GetValueType()))
  13090. {
  13091. // Skip the fast path and just generate a helper call
  13092. return true;
  13093. }
  13094. if(stElem->HasBailOutInfo())
  13095. {
  13096. const IR::BailOutKind bailOutKind = stElem->GetBailOutKind();
  13097. if (bailOutKind & IR::BailOutConventionalNativeArrayAccessOnly)
  13098. {
  13099. labelBailOut = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  13100. labelCantUseArray = labelBailOut;
  13101. }
  13102. }
  13103. }
  13104. bool isTypedArrayElement, isStringIndex;
  13105. indirOpnd =
  13106. GenerateFastElemICommon(
  13107. stElem,
  13108. true,
  13109. indirOpnd,
  13110. labelHelper,
  13111. labelCantUseArray,
  13112. labelFallThru,
  13113. &isTypedArrayElement,
  13114. &isStringIndex,
  13115. &emitBailout,
  13116. &labelSegmentLengthIncreased);
  13117. IR::Opnd *src = stElem->GetSrc1();
  13118. const IR::AutoReuseOpnd autoReuseSrc(src, m_func);
  13119. // The index is negative or not int.
  13120. if (indirOpnd == nullptr)
  13121. {
  13122. Assert(!(stElem->HasBailOutInfo() && stElem->GetBailOutKind() & IR::BailOutOnArrayAccessHelperCall));
  13123. // The global optimizer should never type specialize a StElem for which we know the index is not int or is a negative
  13124. // int constant. This would result in an unconditional bailout on the main code path.
  13125. if (src->IsVar())
  13126. {
  13127. if (PHASE_TRACE(Js::TypedArrayTypeSpecPhase, this->m_func) && PHASE_TRACE(Js::LowererPhase, this->m_func))
  13128. {
  13129. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  13130. Output::Print(L"Typed Array Lowering: function: %s (%s): instr %s, not specialized by glob opt due to negative or not likely int index.\n",
  13131. this->m_func->GetJnFunction()->GetDisplayName(),
  13132. this->m_func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  13133. Js::OpCodeUtil::GetOpCodeName(stElem->m_opcode));
  13134. Output::Flush();
  13135. }
  13136. // We must be dealing with some atypical index value. Don't emit fast path, but go directly to helper.
  13137. return true;
  13138. }
  13139. else
  13140. {
  13141. // If global optimizer failed to notice the unconventional index and type specialized the src,
  13142. // there is nothing to do but bail out. We should never hit this code path, unless the global optimizer's conditions
  13143. // for not specializing the instruction don't match the lowerer's conditions for not emitting the array checks (see above).
  13144. // This could happen if global optimizer's information based on value tracking fails to recognize a non-integer index or
  13145. // a constant int index that is negative. The bailout below ensures that we behave correctly in retail builds even under
  13146. // these (unlikely) conditions.
  13147. AssertMsg(false, "Global optimizer shouldn't have specialized this instruction.");
  13148. stElem->UnlinkSrc1();
  13149. stElem->UnlinkDst();
  13150. GenerateBailOut(stElem, nullptr, nullptr);
  13151. return false;
  13152. }
  13153. }
  13154. const IR::AutoReuseOpnd autoReuseIndirOpnd(indirOpnd, m_func);
  13155. const ValueType baseValueType(dst->AsIndirOpnd()->GetBaseOpnd()->GetValueType());
  13156. if (isTypedArrayElement)
  13157. {
  13158. if (PHASE_TRACE(Js::TypedArrayTypeSpecPhase, this->m_func) && PHASE_TRACE(Js::LowererPhase, this->m_func))
  13159. {
  13160. char baseValueTypeStr[VALUE_TYPE_MAX_STRING_SIZE];
  13161. baseValueType.ToString(baseValueTypeStr);
  13162. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  13163. Output::Print(L"Typed Array Lowering: function: %s (%s), instr: %s, base value type: %S, %s.",
  13164. this->m_func->GetJnFunction()->GetDisplayName(),
  13165. this->m_func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  13166. Js::OpCodeUtil::GetOpCodeName(stElem->m_opcode),
  13167. baseValueTypeStr,
  13168. (!src->IsVar() ? L"specialized" : L"not specialized"));
  13169. Output::Print(L"\n");
  13170. Output::Flush();
  13171. }
  13172. ObjectType objectType = baseValueType.GetObjectType();
  13173. if(indirOpnd->IsFloat())
  13174. {
  13175. if (src->GetType() == TyFloat64)
  13176. {
  13177. IR::RegOpnd *const regSrc = src->AsRegOpnd();
  13178. if (indirOpnd->IsFloat32())
  13179. {
  13180. // CVTSD2SS reg.f32, regSrc.f64 -- Convert regSrc from f64 to f32
  13181. IR::RegOpnd *const reg = IR::RegOpnd::New(TyFloat32, this->m_func);
  13182. const IR::AutoReuseOpnd autoReuseReg(reg, m_func);
  13183. InsertConvertFloat64ToFloat32(reg, regSrc, stElem);
  13184. // MOVSS indirOpnd, reg
  13185. InsertMove(indirOpnd, reg, stElem);
  13186. }
  13187. else
  13188. {
  13189. // MOVSD indirOpnd, regSrc
  13190. InsertMove(indirOpnd, regSrc, stElem);
  13191. }
  13192. emitBailout = true;
  13193. }
  13194. else
  13195. {
  13196. Assert(src->GetType() == TyVar);
  13197. // MOV reg, src
  13198. IR::RegOpnd *const reg = IR::RegOpnd::New(TyVar, this->m_func);
  13199. const IR::AutoReuseOpnd autoReuseReg(reg, m_func);
  13200. InsertMove(reg, src, stElem);
  13201. // Convert to float, and assign to indirOpnd
  13202. if (baseValueType.IsLikelyOptimizedVirtualTypedArray())
  13203. {
  13204. IR::RegOpnd* dstReg = IR::RegOpnd::New(indirOpnd->GetType(), this->m_func);
  13205. m_lowererMD.EmitLoadFloat(dstReg, reg, stElem);
  13206. InsertMove(indirOpnd, dstReg, stElem);
  13207. }
  13208. else
  13209. {
  13210. m_lowererMD.EmitLoadFloat(indirOpnd, reg, stElem);
  13211. }
  13212. }
  13213. }
  13214. else if (objectType == ObjectType::Uint8ClampedArray || objectType == ObjectType::Uint8ClampedVirtualArray || objectType == ObjectType::Uint8ClampedMixedArray)
  13215. {
  13216. Assert(indirOpnd->GetType() == TyUint8);
  13217. IR::RegOpnd *regSrc;
  13218. IR::AutoReuseOpnd autoReuseRegSrc;
  13219. if(src->IsRegOpnd())
  13220. {
  13221. regSrc = src->AsRegOpnd();
  13222. }
  13223. else
  13224. {
  13225. regSrc = IR::RegOpnd::New(StackSym::New(src->GetType(), m_func), src->GetType(), m_func);
  13226. autoReuseRegSrc.Initialize(regSrc, m_func);
  13227. InsertMove(regSrc, src, stElem);
  13228. }
  13229. IR::Opnd *bitMaskOpnd;
  13230. IRType srcType = regSrc->GetType();
  13231. if ((srcType == TyFloat64) || (srcType == TyInt32))
  13232. {
  13233. // if (srcType == TyInt32) {
  13234. // TEST regSrc, ~255
  13235. // JE $storeValue
  13236. // JSB $handleNegative
  13237. // MOV indirOpnd, 255
  13238. // JMP $fallThru
  13239. // $handleNegative [isHelper = false]
  13240. // MOV indirOpnd, 0
  13241. // JMP $fallThru
  13242. // $storeValue
  13243. // MOV indirOpnd, regSrc
  13244. // }
  13245. // else {
  13246. // MOVSD regTmp, regSrc
  13247. // ADDSD regTmp, 0.5
  13248. // CVTTSD2SI regOpnd, regTmp
  13249. // TEST regOpnd, ~255
  13250. // JE $storeValue
  13251. // $handleOutOfBounds [isHelper = true]
  13252. // COMISD regSrc, [&FloatZero]
  13253. // JB $handleNegative
  13254. // MOV regOpnd, 255
  13255. // JMP $storeValue
  13256. // $handleNegative [isHelper = true]
  13257. // MOV regOpnd, 0
  13258. // $storeValue
  13259. // MOV indirOpnd, regOpnd
  13260. // }
  13261. // $fallThru
  13262. IR::RegOpnd *regOpnd;
  13263. IR::AutoReuseOpnd autoReuseRegOpnd;
  13264. if (srcType == TyInt32)
  13265. {
  13266. // When srcType == TyInt32 we will never call the helper and we will never
  13267. // modify the regOpnd. Therefore, it's okay to use regSrc directly, and it
  13268. // reduces register pressure.
  13269. regOpnd = regSrc;
  13270. }
  13271. else
  13272. {
  13273. #ifdef _M_IX86
  13274. AssertMsg(AutoSystemInfo::Data.SSE2Available(), "GlobOpt shouldn't have specialized Uint8ClampedArray StElem to float64 if SSE2 is unavailable.");
  13275. #endif
  13276. regOpnd = IR::RegOpnd::New(TyInt32, this->m_func);
  13277. autoReuseRegOpnd.Initialize(regOpnd, m_func);
  13278. Assert(objectType == ObjectType::Uint8ClampedArray || objectType == ObjectType::Uint8ClampedVirtualArray || objectType == ObjectType::Uint8ClampedMixedArray);
  13279. // Uint8ClampedArray follows IEEE 754 rounding rules for ties which round up
  13280. // odd integers and round down even integers. Both ties result in the nearest
  13281. // even integer value.
  13282. //
  13283. // CVTSD2SI regOpnd, regSrc
  13284. LowererMD::InsertConvertFloat64ToInt32(RoundModeHalfToEven, regOpnd, regSrc, stElem);
  13285. }
  13286. IR::LabelInstr *labelStoreValue = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, false);
  13287. #ifndef _M_ARM
  13288. // TEST regOpnd, ~255
  13289. // JE $storeValue
  13290. bitMaskOpnd = IR::IntConstOpnd::New(~255, TyInt32, this->m_func, true);
  13291. InsertTestBranch(regOpnd, bitMaskOpnd, Js::OpCode::BrEq_A, labelStoreValue, stElem);
  13292. #else // ARM
  13293. // Special case for ARM, a shift may be better
  13294. //
  13295. // ASRS tempReg, src, 8
  13296. // BEQ $inlineSet
  13297. InsertShiftBranch(
  13298. Js::OpCode::Shr_A,
  13299. IR::RegOpnd::New(TyInt32, this->m_func),
  13300. regOpnd,
  13301. IR::IntConstOpnd::New(8, TyInt8, this->m_func),
  13302. Js::OpCode::BrEq_A,
  13303. labelStoreValue,
  13304. stElem);
  13305. #endif
  13306. IR::LabelInstr *labelHandleNegative = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, srcType == TyFloat64);
  13307. if (srcType == TyInt32)
  13308. {
  13309. // JSB $handleNegativeOrOverflow
  13310. InsertBranch(
  13311. LowererMD::MDCompareWithZeroBranchOpcode(Js::OpCode::BrLt_A),
  13312. labelHandleNegative,
  13313. stElem);
  13314. // MOV IndirOpnd.u8, 255
  13315. InsertMove(indirOpnd, IR::IntConstOpnd::New(255, TyUint8, this->m_func, true), stElem);
  13316. // JMP $fallThru
  13317. InsertBranch(Js::OpCode::Br, labelFallThru, stElem);
  13318. // $handleNegative [isHelper = false]
  13319. stElem->InsertBefore(labelHandleNegative);
  13320. // MOV IndirOpnd.u8, 0
  13321. InsertMove(indirOpnd, IR::IntConstOpnd::New(0, TyUint8, this->m_func, true), stElem);
  13322. // JMP $fallThru
  13323. InsertBranch(Js::OpCode::Br, labelFallThru, stElem);
  13324. }
  13325. else
  13326. {
  13327. Assert(regOpnd != regSrc);
  13328. // This label is just to ensure the following code is moved to the helper block.
  13329. // $handleOutOfBounds [isHelper = true]
  13330. IR::LabelInstr *labelHandleOutOfBounds = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  13331. stElem->InsertBefore(labelHandleOutOfBounds);
  13332. // COMISD regSrc, FloatZero
  13333. // JB labelHandleNegative
  13334. IR::MemRefOpnd * zeroOpnd = IR::MemRefOpnd::New((double*)&(Js::JavascriptNumber::k_Zero), TyMachDouble, this->m_func);
  13335. InsertCompareBranch(regSrc, zeroOpnd, Js::OpCode::BrNotGe_A, labelHandleNegative, stElem);
  13336. // MOV regOpnd, 255
  13337. InsertMove(regOpnd, IR::IntConstOpnd::New(255, TyUint8, this->m_func, true), stElem);
  13338. // JMP $storeValue
  13339. InsertBranch(Js::OpCode::Br, labelStoreValue, stElem);
  13340. // $handleNegative [isHelper = true]
  13341. stElem->InsertBefore(labelHandleNegative);
  13342. // MOV regOpnd, 0
  13343. InsertMove(regOpnd, IR::IntConstOpnd::New(0, TyUint8, this->m_func, true), stElem);
  13344. }
  13345. // $storeValue
  13346. stElem->InsertBefore(labelStoreValue);
  13347. // MOV IndirOpnd.u8, regOpnd.u8
  13348. InsertMove(indirOpnd, regOpnd, stElem);
  13349. emitBailout = true;
  13350. }
  13351. else
  13352. {
  13353. Assert(srcType == TyVar);
  13354. #if INT32VAR
  13355. bitMaskOpnd = IR::AddrOpnd::New((Js::Var)~(INT_PTR)(Js::TaggedInt::ToVarUnchecked(255)), IR::AddrOpndKindConstantVar, this->m_func, true);
  13356. #else
  13357. bitMaskOpnd = IR::IntConstOpnd::New(~(INT_PTR)(Js::TaggedInt::ToVarUnchecked(255)), TyMachReg, this->m_func, true);
  13358. #endif
  13359. // Note: We are assuming that if no bits other than ~(TaggedInt(255)) are 1, that we have a tagged
  13360. // int value between 0 - 255.
  13361. // #if INT32VAR
  13362. // This works for pointers because tagged int bit can't be on, and first 64k are not valid addresses
  13363. // This works for floats because a valid float would have one of the upper 13 bits on.
  13364. // #else
  13365. // Any pointer is larger than 512 because first 64k memory is reserved by the OS
  13366. // #endif
  13367. IR::LabelInstr *labelInlineSet = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  13368. #ifndef _M_ARM
  13369. // TEST src, ~(TaggedInt(255)) -- Check for tagged int >= 255 and <= 0
  13370. // JEQ $inlineSet
  13371. InsertTestBranch(regSrc, bitMaskOpnd, Js::OpCode::BrEq_A, labelInlineSet, stElem);
  13372. #else // ARM
  13373. // Special case for ARM, a shift may be better
  13374. //
  13375. // ASRS tempReg, src, 8
  13376. // BEQ $inlineSet
  13377. InsertShiftBranch(
  13378. Js::OpCode::Shr_A,
  13379. IR::RegOpnd::New(TyInt32, this->m_func),
  13380. regSrc,
  13381. IR::IntConstOpnd::New(8, TyInt8, this->m_func),
  13382. Js::OpCode::BrEq_A,
  13383. labelInlineSet,
  13384. stElem);
  13385. #endif
  13386. // Uint8ClampedArray::DirectSetItem(array, index, value);
  13387. m_lowererMD.LoadHelperArgument(stElem, regSrc);
  13388. IR::Opnd *indexOpnd = indirOpnd->GetIndexOpnd();
  13389. if (indexOpnd == nullptr)
  13390. {
  13391. indexOpnd = IR::IntConstOpnd::New(indirOpnd->GetOffset(), TyInt32, this->m_func);
  13392. }
  13393. else
  13394. {
  13395. Assert(indirOpnd->GetOffset() == 0);
  13396. }
  13397. m_lowererMD.LoadHelperArgument(stElem, indexOpnd);
  13398. m_lowererMD.LoadHelperArgument(stElem, stElem->GetDst()->AsIndirOpnd()->GetBaseOpnd());
  13399. IR::Instr *instr = IR::Instr::New(Js::OpCode::Call, this->m_func);
  13400. Assert(objectType == ObjectType::Uint8ClampedArray || objectType == ObjectType::Uint8ClampedMixedArray || objectType == ObjectType::Uint8ClampedVirtualArray);
  13401. instr->SetSrc1(IR::HelperCallOpnd::New(IR::HelperUint8ClampedArraySetItem, this->m_func));
  13402. stElem->InsertBefore(instr);
  13403. m_lowererMD.LowerCall(instr, 0);
  13404. // JMP $fallThrough
  13405. InsertBranch(Js::OpCode::Br, labelFallThru, stElem);
  13406. //$inlineSet
  13407. stElem->InsertBefore(labelInlineSet);
  13408. IR::RegOpnd *regOpnd;
  13409. IR::AutoReuseOpnd autoReuseRegOpnd;
  13410. #if INT32VAR
  13411. regOpnd = regSrc;
  13412. #else
  13413. // MOV r1, src
  13414. // SAR r1, 1
  13415. regOpnd = IR::RegOpnd::New(TyInt32, this->m_func);
  13416. autoReuseRegOpnd.Initialize(regOpnd, m_func);
  13417. InsertShift(
  13418. Js::OpCode::Shr_A,
  13419. false /* needFlags */,
  13420. regOpnd,
  13421. regSrc,
  13422. IR::IntConstOpnd::New(1, TyInt8, this->m_func),
  13423. stElem);
  13424. #endif
  13425. // MOV IndirOpnd.u8, reg.u8
  13426. InsertMove(indirOpnd, regOpnd, stElem);
  13427. }
  13428. }
  13429. else
  13430. {
  13431. if (src->IsInt32())
  13432. {
  13433. // MOV indirOpnd, src
  13434. InsertMove(indirOpnd, src, stElem);
  13435. emitBailout = true;
  13436. }
  13437. else if (src->IsFloat64())
  13438. {
  13439. AssertMsg(indirOpnd->GetType() == TyUint32, "Only StElemI to Uint32Array could be specialized to float64.");
  13440. #ifdef _M_IX86
  13441. AssertMsg(AutoSystemInfo::Data.SSE2Available(), "GloOpt shouldn't have specialized Uint32Array StElemI to float64 if SSE2 is unavailable.");
  13442. #endif
  13443. IR::RegOpnd *const reg = IR::RegOpnd::New(TyInt32, this->m_func);
  13444. const IR::AutoReuseOpnd autoReuseReg(reg, m_func);
  13445. m_lowererMD.EmitFloatToInt(reg, src, stElem);
  13446. // MOV indirOpnd, reg
  13447. InsertMove(indirOpnd, reg, stElem);
  13448. emitBailout = true;
  13449. }
  13450. else
  13451. {
  13452. Assert(src->IsVar());
  13453. if(src->IsAddrOpnd())
  13454. {
  13455. IR::AddrOpnd *const addrSrc = src->AsAddrOpnd();
  13456. Assert(addrSrc->IsVar());
  13457. Assert(Js::TaggedInt::Is(addrSrc->m_address));
  13458. // MOV indirOpnd, intValue
  13459. InsertMove(
  13460. indirOpnd,
  13461. IR::IntConstOpnd::New(Js::TaggedInt::ToInt32(addrSrc->m_address), TyInt32, m_func),
  13462. stElem);
  13463. }
  13464. else
  13465. {
  13466. IR::RegOpnd *const regSrc = src->AsRegOpnd();
  13467. // FromVar reg, Src
  13468. IR::RegOpnd *const reg = IR::RegOpnd::New(TyInt32, this->m_func);
  13469. const IR::AutoReuseOpnd autoReuseReg(reg, m_func);
  13470. IR::Instr *const instr = IR::Instr::New(Js::OpCode::FromVar, reg, regSrc, stElem->m_func);
  13471. stElem->InsertBefore(instr);
  13472. // Convert reg to int32
  13473. // Note: ToUint32 is implemented as (uint32)ToInt32()
  13474. m_lowererMD.EmitLoadInt32(instr);
  13475. // MOV indirOpnd, reg
  13476. InsertMove(indirOpnd, reg, stElem);
  13477. }
  13478. }
  13479. }
  13480. }
  13481. else
  13482. {
  13483. if(labelSegmentLengthIncreased)
  13484. {
  13485. IR::Instr *const insertBeforeInstr = labelSegmentLengthIncreased->m_next;
  13486. // labelSegmentLengthIncreased:
  13487. // mov [segment + index], src
  13488. // jmp $fallThru
  13489. InsertMove(indirOpnd, src, insertBeforeInstr);
  13490. InsertBranch(Js::OpCode::Br, labelFallThru, insertBeforeInstr);
  13491. }
  13492. if (!(isStringIndex || baseValueType.IsArrayOrObjectWithArray() && baseValueType.HasNoMissingValues()))
  13493. {
  13494. if(!stElem->IsProfiledInstr() || stElem->AsProfiledInstr()->u.stElemInfo->LikelyFillsMissingValue())
  13495. {
  13496. // Check whether the store is filling a missing value. If so, fall back to the helper so that it can check whether
  13497. // this store is filling the last missing value in the array. This is necessary to keep the missing value tracking
  13498. // in arrays precise. The check is omitted when profile data says that the store is likely to create missing values.
  13499. //
  13500. // cmp [segment + index], Js::SparseArraySegment::MissingValue
  13501. // je $helper
  13502. InsertCompareBranch(
  13503. indirOpnd,
  13504. GetMissingItemOpnd(src->GetType(), m_func),
  13505. Js::OpCode::BrEq_A,
  13506. labelHelper,
  13507. stElem,
  13508. true);
  13509. }
  13510. else
  13511. {
  13512. GenerateIsEnabledArraySetElementFastPathCheck(labelHelper, stElem);
  13513. }
  13514. }
  13515. // MOV [r3 + r2], src
  13516. InsertMoveWithBarrier(indirOpnd, src, stElem);
  13517. }
  13518. // JMP $fallThru
  13519. InsertBranch(Js::OpCode::Br, labelFallThru, stElem);
  13520. // $helper:
  13521. // bailout or caller generated helper call
  13522. // $fallThru:
  13523. stElem->InsertBefore(labelHelper);
  13524. instrIsInHelperBlock = true;
  13525. if (isNativeArrayStore && !isStringIndex)
  13526. {
  13527. Assert(stElem->HasBailOutInfo());
  13528. Assert(labelHelper != labelBailOut);
  13529. // Transform the original instr:
  13530. //
  13531. // $helper:
  13532. // dst = LdElemI_A src (BailOut)
  13533. // $fallthrough:
  13534. //
  13535. // to:
  13536. //
  13537. // $helper:
  13538. // dst = LdElemI_A src
  13539. // b $fallthrough
  13540. // $bailout:
  13541. // BailOut
  13542. // $fallthrough:
  13543. LowerOneBailOutKind(stElem, IR::BailOutConventionalNativeArrayAccessOnly, instrIsInHelperBlock);
  13544. IR::Instr *const insertBeforeInstr = stElem->m_next;
  13545. InsertBranch(Js::OpCode::Br, labelFallThru, insertBeforeInstr);
  13546. insertBeforeInstr->InsertBefore(labelBailOut);
  13547. }
  13548. if (emitBailout)
  13549. {
  13550. stElem->UnlinkSrc1();
  13551. stElem->UnlinkDst();
  13552. GenerateBailOut(stElem, nullptr, nullptr);
  13553. }
  13554. return !emitBailout;
  13555. }
  13556. bool
  13557. Lowerer::GenerateFastLdLen(IR::Instr *ldLen, bool *instrIsInHelperBlockRef)
  13558. {
  13559. Assert(instrIsInHelperBlockRef);
  13560. bool &instrIsInHelperBlock = *instrIsInHelperBlockRef;
  13561. instrIsInHelperBlock = false;
  13562. // TEST src, AtomTag -- check src not tagged int
  13563. // JNE $helper
  13564. // CMP [src], JavascriptArray::`vtable' -- check base isArray
  13565. // JNE $string
  13566. // MOV length, [src + offset(length)] -- Load array length
  13567. // JMP $tovar
  13568. // $string:
  13569. // CMP [src + offset(type)], static_string_type -- check src isString
  13570. // JNE $helper
  13571. // MOV length, [src + offset(length)] -- Load string length
  13572. // $toVar:
  13573. // TEST length, 0xC0000000 -- test for overflow of SHL, or negative
  13574. // JNE $helper
  13575. // SHL length, Js::VarTag_Shift -- restore the var tag on the result
  13576. // INC length
  13577. // MOV dst, length
  13578. // JMP $fallthru
  13579. // $helper:
  13580. // CALL GetProperty(src, length_property_id, scriptContext)
  13581. // $fallthru:
  13582. IR::RegOpnd * opnd = ldLen->GetSrc1()->AsRegOpnd();
  13583. IR::RegOpnd * dst = ldLen->GetDst()->AsRegOpnd();
  13584. IR::RegOpnd * src = opnd->AsRegOpnd();
  13585. const ValueType srcValueType(src->GetValueType());
  13586. AssertMsg(src->IsRegOpnd(), "Expected regOpnd on LdLen");
  13587. IR::LabelInstr *const labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  13588. if (ldLen->DoStackArgsOpt(this->m_func))
  13589. {
  13590. GenerateFastArgumentsLdLen(ldLen, labelHelper, ldLen->GetOrCreateContinueLabel());
  13591. }
  13592. else
  13593. {
  13594. const bool arrayFastPath = ShouldGenerateArrayFastPath(src, false, true, false);
  13595. // HasBeenString instead of IsLikelyString because it could be a merge between StringObject and String, and this
  13596. // information about whether it's a StringObject or some other object is not available in the profile data
  13597. const bool stringFastPath = srcValueType.IsUninitialized() || srcValueType.HasBeenString();
  13598. if(!(arrayFastPath || stringFastPath))
  13599. {
  13600. return true;
  13601. }
  13602. const int32 arrayOffsetOfLength =
  13603. srcValueType.IsLikelyAnyOptimizedArray()
  13604. ? GetArrayOffsetOfLength(srcValueType)
  13605. : Js::JavascriptArray::GetOffsetOfLength();
  13606. IR::LabelInstr *labelString = nullptr;
  13607. IR::RegOpnd *arrayOpnd = src;
  13608. IR::RegOpnd *arrayLengthOpnd = nullptr;
  13609. IR::AutoReuseOpnd autoReuseArrayLengthOpnd;
  13610. if(arrayFastPath)
  13611. {
  13612. if(!srcValueType.IsAnyOptimizedArray())
  13613. {
  13614. if(stringFastPath)
  13615. {
  13616. // If we don't have info about the src value type or its object type, the array and string fast paths are
  13617. // generated
  13618. labelString = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  13619. }
  13620. arrayOpnd = GenerateArrayTest(src, labelHelper, stringFastPath ? labelString : labelHelper, ldLen, false);
  13621. }
  13622. else if(src->IsArrayRegOpnd())
  13623. {
  13624. IR::ArrayRegOpnd *const arrayRegOpnd = src->AsArrayRegOpnd();
  13625. if(arrayRegOpnd->LengthSym())
  13626. {
  13627. arrayLengthOpnd = IR::RegOpnd::New(arrayRegOpnd->LengthSym(), TyUint32, m_func);
  13628. DebugOnly(arrayLengthOpnd->FreezeSymValue());
  13629. autoReuseArrayLengthOpnd.Initialize(arrayLengthOpnd, m_func);
  13630. }
  13631. }
  13632. }
  13633. const IR::AutoReuseOpnd autoReuseArrayOpnd(arrayOpnd, m_func);
  13634. IR::RegOpnd *lengthOpnd = nullptr;
  13635. IR::AutoReuseOpnd autoReuseLengthOpnd;
  13636. const auto EnsureLengthOpnd = [&]()
  13637. {
  13638. if(lengthOpnd)
  13639. {
  13640. return;
  13641. }
  13642. lengthOpnd = IR::RegOpnd::New(TyUint32, m_func);
  13643. autoReuseLengthOpnd.Initialize(lengthOpnd, m_func);
  13644. };
  13645. if(arrayFastPath)
  13646. {
  13647. if(arrayLengthOpnd)
  13648. {
  13649. lengthOpnd = arrayLengthOpnd;
  13650. autoReuseLengthOpnd.Initialize(lengthOpnd, m_func);
  13651. Assert(!stringFastPath);
  13652. }
  13653. else
  13654. {
  13655. // MOV length, [array + offset(length)] -- Load array length
  13656. EnsureLengthOpnd();
  13657. IR::IndirOpnd *const indirOpnd = IR::IndirOpnd::New(arrayOpnd, arrayOffsetOfLength, TyUint32, this->m_func);
  13658. InsertMove(lengthOpnd, indirOpnd, ldLen);
  13659. }
  13660. }
  13661. if(stringFastPath)
  13662. {
  13663. IR::LabelInstr *labelToVar = nullptr;
  13664. if(arrayFastPath)
  13665. {
  13666. // JMP $tovar
  13667. labelToVar = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  13668. InsertBranch(Js::OpCode::Br, labelToVar, ldLen);
  13669. // $string:
  13670. ldLen->InsertBefore(labelString);
  13671. }
  13672. // CMP [src + offset(type)], static_stringtype -- check src isString
  13673. // JNE $helper
  13674. GenerateStringTest(src, ldLen, labelHelper, nullptr, !arrayFastPath);
  13675. // MOV length, [src + offset(length)] -- Load string length
  13676. EnsureLengthOpnd();
  13677. IR::IndirOpnd * indirOpnd = IR::IndirOpnd::New(src, offsetof(Js::JavascriptString, m_charLength), TyUint32, this->m_func);
  13678. InsertMove(lengthOpnd, indirOpnd, ldLen);
  13679. if(arrayFastPath)
  13680. {
  13681. // $toVar:
  13682. ldLen->InsertBefore(labelToVar);
  13683. }
  13684. }
  13685. Assert(lengthOpnd);
  13686. if(ldLen->HasBailOutInfo() && (ldLen->GetBailOutKind() & ~IR::BailOutKindBits) == IR::BailOutOnIrregularLength)
  13687. {
  13688. Assert(ldLen->GetBailOutKind() == IR::BailOutOnIrregularLength);
  13689. Assert(dst->IsInt32());
  13690. // Since the length is an unsigned int32, verify that when interpreted as a signed int32, it is not negative
  13691. // test length, length
  13692. // js $helper
  13693. // mov dst, length
  13694. // jmp $fallthrough
  13695. InsertCompareBranch(
  13696. lengthOpnd,
  13697. IR::IntConstOpnd::New(0, lengthOpnd->GetType(), m_func, true),
  13698. Js::OpCode::BrLt_A,
  13699. labelHelper,
  13700. ldLen);
  13701. InsertMove(dst, lengthOpnd, ldLen);
  13702. InsertBranch(Js::OpCode::Br, ldLen->GetOrCreateContinueLabel(), ldLen);
  13703. // $helper:
  13704. // (Bail out with IR::BailOutOnIrregularLength)
  13705. ldLen->InsertBefore(labelHelper);
  13706. instrIsInHelperBlock = true;
  13707. ldLen->FreeDst();
  13708. ldLen->FreeSrc1();
  13709. GenerateBailOut(ldLen);
  13710. return false;
  13711. }
  13712. #if INT32VAR
  13713. // Since the length is an unsigned int32, verify that when interpreted as a signed int32, it is not negative
  13714. // test length, length
  13715. // js $helper
  13716. InsertCompareBranch(
  13717. lengthOpnd,
  13718. IR::IntConstOpnd::New(0, lengthOpnd->GetType(), m_func, true),
  13719. Js::OpCode::BrLt_A,
  13720. labelHelper,
  13721. ldLen);
  13722. #else
  13723. // Since the length is an unsigned int32, verify that when interpreted as a signed int32, it is not negative.
  13724. // Additionally, verify that the signed value's width is not greater than 31 bits, since it needs to be tagged.
  13725. // test length, 0xC0000000
  13726. // jne $helper
  13727. InsertTestBranch(
  13728. lengthOpnd,
  13729. IR::IntConstOpnd::New(0xC0000000, TyUint32, this->m_func, true),
  13730. Js::OpCode::BrNeq_A,
  13731. labelHelper,
  13732. ldLen);
  13733. #endif
  13734. #if INT32VAR
  13735. //
  13736. // dst_32 = MOV length
  13737. // dst_64 = OR dst_64, Js::AtomTag_IntPtr
  13738. //
  13739. Assert(dst->GetType() == TyVar);
  13740. IR::Opnd *dst32 = dst->Copy(this->m_func);
  13741. dst32->SetType(TyInt32);
  13742. // This will clear the top bits.
  13743. InsertMove(dst32, lengthOpnd, ldLen);
  13744. m_lowererMD.GenerateInt32ToVarConversion(dst, ldLen);
  13745. #else
  13746. // dst = SHL length, Js::VarTag_Shift -- restore the var tag on the result
  13747. InsertShift(
  13748. Js::OpCode::Shl_A,
  13749. false /* needFlags */,
  13750. dst,
  13751. lengthOpnd,
  13752. IR::IntConstOpnd::New(Js::VarTag_Shift, TyInt8, this->m_func),
  13753. ldLen);
  13754. // dst = ADD dst, AtomTag
  13755. InsertAdd(
  13756. false /* needFlags */,
  13757. dst,
  13758. dst,
  13759. IR::IntConstOpnd::New(Js::AtomTag_Int32, TyUint32, m_func, true),
  13760. ldLen);
  13761. #endif
  13762. // JMP $fallthrough
  13763. InsertBranch(Js::OpCode::Br, ldLen->GetOrCreateContinueLabel(), ldLen);
  13764. }
  13765. // $helper:
  13766. // (caller generates helper call)
  13767. ldLen->InsertBefore(labelHelper);
  13768. instrIsInHelperBlock = true;
  13769. return true; // fast path was generated, helper call will be in a helper block
  13770. }
  13771. void
  13772. Lowerer::GenerateFastInlineStringCodePointAt(IR::Instr* lastInstr, Func* func, IR::Opnd *strLength, IR::Opnd *srcIndex, IR::RegOpnd *lowerChar, IR::RegOpnd *strPtr)
  13773. {
  13774. //// Required State:
  13775. // strLength - UInt32
  13776. // srcIndex - TyVar if not Address
  13777. // lowerChar - TyMachReg
  13778. // strPtr - Addr
  13779. //// Instructions
  13780. // CMP [strLength], srcIndex + 1
  13781. // JBE charCodeAt
  13782. // CMP lowerChar 0xDC00
  13783. // JGE charCodeAt
  13784. // CMP lowerChar 0xD7FF
  13785. // JLE charCodeAt
  13786. // upperChar = MOVZX [strPtr + srcIndex + 1]
  13787. // CMP upperChar 0xE000
  13788. // JGE charCodeAt
  13789. // CMP lowerChar 0xDBFF
  13790. // JLE charCodeAt
  13791. // lowerChar = SUB lowerChar - 0xD800
  13792. // lowerChar = SHL lowerChar, 10
  13793. // lowerChar = ADD lowerChar + upperChar
  13794. // lowerChar = ADD lowerChar + 0x2400
  13795. // :charCodeAt
  13796. // :done
  13797. // Asserts
  13798. // Arm should change to Uint32 for the strLength
  13799. Assert(strLength->GetType() == TyUint32 || strLength->GetType() == TyMachReg);
  13800. Assert(srcIndex->GetType() == TyVar || srcIndex->IsAddrOpnd());
  13801. Assert(lowerChar->GetType() == TyMachReg || lowerChar->GetType() == TyUint32);
  13802. Assert(strPtr->IsRegOpnd());
  13803. IR::RegOpnd *tempReg = IR::RegOpnd::New(TyMachReg, func);
  13804. IR::LabelInstr *labelCharCodeAt = IR::LabelInstr::New(Js::OpCode::Label, func);
  13805. IR::IndirOpnd *tempIndirOpnd;
  13806. if (srcIndex->IsAddrOpnd())
  13807. {
  13808. uint32 length = Js::TaggedInt::ToUInt32(srcIndex->AsAddrOpnd()->m_address) + 1U;
  13809. InsertCompareBranch(strLength, IR::IntConstOpnd::New(length, TyUint32, func), Js::OpCode::BrLe_A, true, labelCharCodeAt, lastInstr);
  13810. tempIndirOpnd = IR::IndirOpnd::New(strPtr, (length) * sizeof(wchar_t), TyUint16, func);
  13811. }
  13812. else
  13813. {
  13814. InsertMove(tempReg, srcIndex, lastInstr);
  13815. #if INT32VAR
  13816. IR::Opnd * reg32Bit = tempReg->UseWithNewType(TyInt32, func);
  13817. InsertMove(tempReg, reg32Bit, lastInstr);
  13818. tempReg = reg32Bit->AsRegOpnd();
  13819. #else
  13820. InsertShift(Js::OpCode::Shr_A, false, tempReg, tempReg, IR::IntConstOpnd::New(Js::VarTag_Shift, TyInt8, func), lastInstr);
  13821. #endif
  13822. InsertAdd(false, tempReg, tempReg, IR::IntConstOpnd::New(1, TyInt32, func), lastInstr);
  13823. InsertCompareBranch(strLength, tempReg, Js::OpCode::BrLe_A, true, labelCharCodeAt, lastInstr);
  13824. if(tempReg->GetSize() != MachPtr)
  13825. {
  13826. tempReg = tempReg->UseWithNewType(TyMachPtr, func)->AsRegOpnd();
  13827. }
  13828. tempIndirOpnd = IR::IndirOpnd::New(strPtr, tempReg, 1, TyUint16, func);
  13829. }
  13830. // By this point, we have added instructions before labelCharCodeAt to check for extra length required for the surrogate pair
  13831. // The branching for that is already handled, all we have to do now is to check for correct values.
  13832. // Validate char is in range [D800, DBFF]; otherwise just get a charCodeAt
  13833. InsertCompareBranch(lowerChar, IR::IntConstOpnd::New(0xDC00, TyUint32, func), Js::OpCode::BrGe_A, labelCharCodeAt, lastInstr);
  13834. InsertCompareBranch(lowerChar, IR::IntConstOpnd::New(0xD7FF, TyUint32, func), Js::OpCode::BrLe_A, labelCharCodeAt, lastInstr);
  13835. // upperChar = MOVZX r3, [r1 + r3 * 2] -- this is the value of the upper surrogate pair char
  13836. IR::RegOpnd *upperChar = IR::RegOpnd::New(TyInt32, func);
  13837. InsertMove(upperChar, tempIndirOpnd, lastInstr);
  13838. // Validate upper is in range [DC00, DFFF]; otherwise just get a charCodeAt
  13839. InsertCompareBranch(upperChar, IR::IntConstOpnd::New(0xE000, TyUint32, func), Js::OpCode::BrGe_A, labelCharCodeAt, lastInstr);
  13840. InsertCompareBranch(upperChar, IR::IntConstOpnd::New(0xDBFF, TyUint32, func), Js::OpCode::BrLe_A, labelCharCodeAt, lastInstr);
  13841. // (lower - 0xD800) << 10 + second - 0xDC00 + 0x10000 -- 0x10000 - 0xDC00 = 0x2400
  13842. // lowerChar = SUB lowerChar - 0xD800
  13843. // lowerChar = SHL lowerChar, 10
  13844. // lowerChar = ADD lowerChar + upperChar
  13845. // lowerChar = ADD lowerChar + 0x2400
  13846. InsertSub(false, lowerChar, lowerChar, IR::IntConstOpnd::New(0xD800, TyUint32, func), lastInstr);
  13847. InsertShift(Js::OpCode::Shl_A, false, lowerChar, lowerChar, IR::IntConstOpnd::New(10, TyUint32, func), lastInstr);
  13848. InsertAdd(false, lowerChar, lowerChar, upperChar, lastInstr);
  13849. InsertAdd(false, lowerChar, lowerChar, IR::IntConstOpnd::New(0x2400, TyUint32, func), lastInstr);
  13850. lastInstr->InsertBefore(labelCharCodeAt);
  13851. }
  13852. bool
  13853. Lowerer::GenerateFastInlineStringFromCodePoint(IR::Instr* instr)
  13854. {
  13855. Assert(instr->m_opcode == Js::OpCode::CallDirect);
  13856. // ArgOut sequence
  13857. // s8.var = StartCall 2 (0x2).i32 #000c
  13858. // arg1(s9)<0>.var = ArgOut_A s2.var, s8.var #0014 //Implicit this, String object
  13859. // arg2(s10)<4>.var = ArgOut_A s3.var, arg1(s9)<0>.var #0018 //First argument to FromCharCode
  13860. // arg1(s11)<0>.u32 = ArgOut_A_InlineSpecialized 0x012C26C0 (DynamicObject).var, arg2(s10)<4>.var #
  13861. // s0[LikelyTaggedInt].var = CallDirect String_FromCodePoint.u32, arg1(s11)<0>.u32 #001c
  13862. IR::Opnd * linkOpnd = instr->GetSrc2();
  13863. IR::Instr * tmpInstr = Inline::GetDefInstr(linkOpnd);// linkOpnd->AsSymOpnd()->m_sym->AsStackSym()->m_instrDef;
  13864. linkOpnd = tmpInstr->GetSrc2();
  13865. #if DBG
  13866. IntConstType argCount = linkOpnd->AsSymOpnd()->m_sym->AsStackSym()->GetArgSlotNum();
  13867. Assert(argCount == 2);
  13868. #endif
  13869. IR::Instr *argInstr = Inline::GetDefInstr(linkOpnd);
  13870. Assert(argInstr->m_opcode == Js::OpCode::ArgOut_A);
  13871. IR::Opnd *src1 = argInstr->GetSrc1();
  13872. if (src1->GetValueType().IsLikelyNumber())
  13873. {
  13874. //Trying to generate this code
  13875. // MOV resultOpnd, dst
  13876. // MOV fromCharCodeIntArgOpnd, src1
  13877. // SAR fromCharCodeIntArgOpnd, Js::VarTag_Shift
  13878. // JAE $Helper
  13879. // CMP fromCharCodeIntArgOpnd, Js::ScriptContext::CharStringCacheSize
  13880. //
  13881. // JAE $labelWCharStringCheck <
  13882. // MOV resultOpnd, GetCharStringCache[fromCharCodeIntArgOpnd]
  13883. // TST resultOpnd, resultOpnd //Check for null
  13884. // JEQ $helper
  13885. // JMP $Done
  13886. //
  13887. //$labelWCharStringCheck:
  13888. // resultOpnd = Call HelperGetStringForCharW
  13889. // JMP $Done
  13890. //$helper:
  13891. IR::RegOpnd * resultOpnd = nullptr;
  13892. if (!instr->GetDst()->IsRegOpnd() || instr->GetDst()->IsEqual(src1))
  13893. {
  13894. resultOpnd = IR::RegOpnd::New(TyVar, this->m_func);
  13895. }
  13896. else
  13897. {
  13898. resultOpnd = instr->GetDst()->AsRegOpnd();
  13899. }
  13900. IR::LabelInstr *doneLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  13901. IR::LabelInstr *labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  13902. IR::RegOpnd * fromCodePointIntArgOpnd = IR::RegOpnd::New(TyVar, instr->m_func);
  13903. IR::AutoReuseOpnd autoReuseFromCodePointIntArgOpnd(fromCodePointIntArgOpnd, instr->m_func);
  13904. InsertMove(fromCodePointIntArgOpnd, src1, instr);
  13905. //Check for tagged int and get the untagged version.
  13906. fromCodePointIntArgOpnd = GenerateUntagVar(fromCodePointIntArgOpnd, labelHelper, instr);
  13907. GenerateGetSingleCharString(fromCodePointIntArgOpnd, resultOpnd, labelHelper, doneLabel, instr, true);
  13908. instr->InsertBefore(labelHelper);
  13909. instr->InsertAfter(doneLabel);
  13910. RelocateCallDirectToHelperPath(tmpInstr, labelHelper);
  13911. }
  13912. return true;
  13913. }
  13914. bool
  13915. Lowerer::GenerateFastInlineStringFromCharCode(IR::Instr* instr)
  13916. {
  13917. Assert(instr->m_opcode == Js::OpCode::CallDirect);
  13918. // ArgOut sequence
  13919. // s8.var = StartCall 2 (0x2).i32 #000c
  13920. // arg1(s9)<0>.var = ArgOut_A s2.var, s8.var #0014 //Implicit this, String object
  13921. // arg2(s10)<4>.var = ArgOut_A s3.var, arg1(s9)<0>.var #0018 //First argument to FromCharCode
  13922. // arg1(s11)<0>.u32 = ArgOut_A_InlineSpecialized 0x012C26C0 (DynamicObject).var, arg2(s10)<4>.var #
  13923. // s0[LikelyTaggedInt].var = CallDirect String_FromCharCode.u32, arg1(s11)<0>.u32 #001c
  13924. IR::Opnd * linkOpnd = instr->GetSrc2();
  13925. IR::Instr * tmpInstr = Inline::GetDefInstr(linkOpnd);// linkOpnd->AsSymOpnd()->m_sym->AsStackSym()->m_instrDef;
  13926. linkOpnd = tmpInstr->GetSrc2();
  13927. #if DBG
  13928. IntConstType argCount = linkOpnd->AsSymOpnd()->m_sym->AsStackSym()->GetArgSlotNum();
  13929. Assert(argCount == 2);
  13930. #endif
  13931. IR::Instr *argInstr = Inline::GetDefInstr(linkOpnd);
  13932. Assert(argInstr->m_opcode == Js::OpCode::ArgOut_A);
  13933. IR::Opnd *src1 = argInstr->GetSrc1();
  13934. if (src1->GetValueType().IsLikelyNumber())
  13935. {
  13936. //Trying to generate this code
  13937. // MOV resultOpnd, dst
  13938. // MOV fromCharCodeIntArgOpnd, src1
  13939. // SAR fromCharCodeIntArgOpnd, Js::VarTag_Shift
  13940. // JAE $Helper
  13941. // CMP fromCharCodeIntArgOpnd, Js::ScriptContext::CharStringCacheSize
  13942. //
  13943. // JAE $labelWCharStringCheck <
  13944. // MOV resultOpnd, GetCharStringCache[fromCharCodeIntArgOpnd]
  13945. // TST resultOpnd, resultOpnd //Check for null
  13946. // JEQ $helper
  13947. // JMP $Done
  13948. //
  13949. //$labelWCharStringCheck:
  13950. // resultOpnd = Call HelperGetStringForCharW
  13951. // JMP $Done
  13952. //$helper:
  13953. IR::RegOpnd * resultOpnd = nullptr;
  13954. if (!instr->GetDst()->IsRegOpnd() || instr->GetDst()->IsEqual(src1))
  13955. {
  13956. resultOpnd = IR::RegOpnd::New(TyVar, this->m_func);
  13957. }
  13958. else
  13959. {
  13960. resultOpnd = instr->GetDst()->AsRegOpnd();
  13961. }
  13962. IR::LabelInstr *labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  13963. IR::RegOpnd * fromCharCodeIntArgOpnd = IR::RegOpnd::New(TyVar, instr->m_func);
  13964. IR::AutoReuseOpnd autoReuseFromCharCodeIntArgOpnd(fromCharCodeIntArgOpnd, instr->m_func);
  13965. InsertMove(fromCharCodeIntArgOpnd, src1, instr);
  13966. //Check for tagged int and get the untagged version.
  13967. fromCharCodeIntArgOpnd = GenerateUntagVar(fromCharCodeIntArgOpnd, labelHelper, instr);
  13968. IR::LabelInstr *doneLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  13969. GenerateGetSingleCharString(fromCharCodeIntArgOpnd, resultOpnd, labelHelper, doneLabel, instr, false);
  13970. instr->InsertBefore(labelHelper);
  13971. instr->InsertAfter(doneLabel);
  13972. RelocateCallDirectToHelperPath(tmpInstr, labelHelper);
  13973. }
  13974. return true;
  13975. }
  13976. void
  13977. Lowerer::GenerateGetSingleCharString(IR::RegOpnd * charCodeOpnd, IR::Opnd * resultOpnd, IR::LabelInstr * labelHelper, IR::LabelInstr * doneLabel, IR::Instr * instr, bool isCodePoint)
  13978. {
  13979. // MOV cacheReg, CharStringCache
  13980. // CMP charCodeOpnd, Js::ScriptContext::CharStringCacheSize
  13981. // JAE $labelWCharStringCheck <
  13982. // MOV resultOpnd, cacheReg[charCodeOpnd]
  13983. // TST resultOpnd, resultOpnd //Check for null
  13984. // JEQ $helper
  13985. // JMP $Done
  13986. //
  13987. //$labelWCharStringCheck:
  13988. // Arg1 = charCodeOpnd
  13989. // Arg0 = cacheReg
  13990. // resultOpnd = Call HelperGetStringForCharW/CodePoint
  13991. // JMP $Done
  13992. //$helper:
  13993. IR::LabelInstr *labelWCharStringCheck = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  13994. //Try to load from in CharStringCacheA
  13995. IR::RegOpnd *cacheRegOpnd = IR::RegOpnd::New(TyVar, instr->m_func);
  13996. IR::AutoReuseOpnd autoReuseCacheRegOpnd(cacheRegOpnd, instr->m_func);
  13997. Assert(Js::JavascriptLibrary::GetCharStringCacheAOffset() == Js::JavascriptLibrary::GetCharStringCacheOffset());
  13998. InsertMove(cacheRegOpnd, this->LoadLibraryValueOpnd(instr, LibraryValue::ValueCharStringCache), instr);
  13999. InsertCompareBranch(charCodeOpnd, IR::IntConstOpnd::New(Js::CharStringCache::CharStringCacheSize, TyUint32, this->m_func), Js::OpCode::BrGe_A, true, labelWCharStringCheck, instr);
  14000. InsertMove(resultOpnd, IR::IndirOpnd::New(cacheRegOpnd, charCodeOpnd, this->m_lowererMD.GetDefaultIndirScale(), TyVar, instr->m_func), instr);
  14001. InsertTestBranch(resultOpnd, resultOpnd, Js::OpCode::BrEq_A, labelHelper, instr);
  14002. InsertMove(instr->GetDst(), resultOpnd, instr);
  14003. InsertBranch(Js::OpCode::Br, doneLabel, instr);
  14004. instr->InsertBefore(labelWCharStringCheck);
  14005. IR::JnHelperMethod helperMethod;
  14006. if (isCodePoint)
  14007. {
  14008. helperMethod = IR::HelperGetStringForCharCodePoint;
  14009. }
  14010. else
  14011. {
  14012. InsertMove(charCodeOpnd, charCodeOpnd->UseWithNewType(TyUint16, instr->m_func), instr);
  14013. helperMethod = IR::HelperGetStringForChar;
  14014. }
  14015. //Try to load from in CharStringCacheW or CharStringCacheCodePoint, this is a helper call.
  14016. this->m_lowererMD.LoadHelperArgument(instr, charCodeOpnd);
  14017. this->m_lowererMD.LoadHelperArgument(instr, cacheRegOpnd);
  14018. IR::Instr* helperCallInstr = IR::Instr::New(Js::OpCode::Call, resultOpnd, IR::HelperCallOpnd::New(helperMethod, this->m_func), this->m_func);
  14019. instr->InsertBefore(helperCallInstr);
  14020. this->m_lowererMD.LowerCall(helperCallInstr, 0);
  14021. InsertMove(instr->GetDst(), resultOpnd, instr);
  14022. InsertBranch(Js::OpCode::Br, doneLabel, instr);
  14023. }
  14024. bool
  14025. Lowerer::GenerateFastInlineGlobalObjectParseInt(IR::Instr *instr)
  14026. {
  14027. Assert(instr->m_opcode == Js::OpCode::CallDirect);
  14028. // ArgOut sequence
  14029. // s8.var = StartCall 2 (0x2).i32 #000c
  14030. // arg1(s9)<0>.var = ArgOut_A s2.var, s8.var #0014 //Implicit this, global object
  14031. // arg2(s10)<4>.var = ArgOut_A s3.var, arg1(s9)<0>.var #0018 //First argument to parseInt
  14032. // arg1(s11)<0>.u32 = ArgOut_A_InlineSpecialized 0x012C26C0 (DynamicObject).var, arg2(s10)<4>.var #
  14033. // s0[LikelyTaggedInt].var = CallDirect GlobalObject_ParseInt.u32, arg1(s11)<0>.u32 #001c
  14034. IR::Opnd * linkOpnd = instr->GetSrc2();
  14035. IR::Instr * tmpInstr = Inline::GetDefInstr(linkOpnd);// linkOpnd->AsSymOpnd()->m_sym->AsStackSym()->m_instrDef;
  14036. linkOpnd = tmpInstr->GetSrc2();
  14037. #if DBG
  14038. IntConstType argCount = linkOpnd->AsSymOpnd()->m_sym->AsStackSym()->GetArgSlotNum();
  14039. Assert(argCount == 2);
  14040. #endif
  14041. IR::Instr *argInstr = Inline::GetDefInstr(linkOpnd);
  14042. Assert(argInstr->m_opcode == Js::OpCode::ArgOut_A);
  14043. IR::Opnd *parseIntArgOpnd = argInstr->GetSrc1();
  14044. if (parseIntArgOpnd->GetValueType().IsLikelyNumber())
  14045. {
  14046. //If likely int check for tagged int and set the dst
  14047. IR::LabelInstr *doneLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  14048. IR::LabelInstr *labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  14049. if (!parseIntArgOpnd->IsTaggedInt())
  14050. {
  14051. this->m_lowererMD.GenerateSmIntTest(parseIntArgOpnd, instr, labelHelper);
  14052. }
  14053. if (instr->GetDst())
  14054. {
  14055. this->m_lowererMD.CreateAssign(instr->GetDst(), parseIntArgOpnd, instr);
  14056. }
  14057. InsertBranch(Js::OpCode::Br, doneLabel, instr);
  14058. instr->InsertBefore(labelHelper);
  14059. instr->InsertAfter(doneLabel);
  14060. RelocateCallDirectToHelperPath(tmpInstr, labelHelper);
  14061. }
  14062. return true;
  14063. }
  14064. void
  14065. Lowerer::GenerateFastInlineArrayPop(IR::Instr * instr)
  14066. {
  14067. Assert(instr->m_opcode == Js::OpCode::InlineArrayPop);
  14068. IR::Opnd *arrayOpnd = instr->GetSrc1();
  14069. IR::LabelInstr *bailOutLabelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  14070. IR::LabelInstr *doneLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  14071. bool isLikelyNativeArray = arrayOpnd->GetValueType().IsLikelyNativeArray();
  14072. if (ShouldGenerateArrayFastPath(arrayOpnd, false, false, false))
  14073. {
  14074. IR::LabelInstr *labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  14075. if(isLikelyNativeArray)
  14076. {
  14077. //We bailOut on cases like length == 0, Array Test failing cases (Runtime helper cannot handle these cases)
  14078. GenerateFastPop(arrayOpnd, instr, labelHelper, doneLabel, bailOutLabelHelper);
  14079. }
  14080. else
  14081. {
  14082. //We jump to helper on cases like length == 0, Array Test failing cases
  14083. GenerateFastPop(arrayOpnd, instr, labelHelper, doneLabel, labelHelper);
  14084. }
  14085. instr->InsertBefore(labelHelper);
  14086. ///JMP to $doneLabel
  14087. InsertBranch(Js::OpCode::Br, true, doneLabel, labelHelper);
  14088. }
  14089. else
  14090. {
  14091. //We assume here that the array will be a Var array. - Runtime Helper calls assume this.
  14092. Assert(!isLikelyNativeArray);
  14093. }
  14094. instr->InsertAfter(doneLabel);
  14095. if(isLikelyNativeArray)
  14096. {
  14097. //Lower IR::BailOutConventionalNativeArrayAccessOnly here.
  14098. LowerOneBailOutKind(instr, IR::BailOutConventionalNativeArrayAccessOnly, false, false);
  14099. instr->InsertAfter(bailOutLabelHelper);
  14100. }
  14101. GenerateHelperToArrayPopFastPath(instr, doneLabel, bailOutLabelHelper);
  14102. }
  14103. bool
  14104. Lowerer::ShouldGenerateStringReplaceFastPath(IR::Instr * callInstr, IntConstType argCount)
  14105. {
  14106. // a.replace(b,c)
  14107. // We want to emit the fast path if 'a' and 'c' are strings and 'b' is a regex
  14108. //
  14109. // argout sequence:
  14110. // arg1(s12)<0>.var = ArgOut_A s2.var, s11.var #0014 <---- a
  14111. // arg2(s13)<4>.var = ArgOut_A s3.var, arg1(s12)<0>.var #0018 <---- b
  14112. // arg3(s14)<8>.var = ArgOut_A s4.var, arg2(s13)<4>.var #001c <---- c
  14113. // s0[LikelyString].var = CallI s5[ffunc].var, arg3(s14)<8>.var #0020
  14114. IR::Opnd *linkOpnd = callInstr->GetSrc2();
  14115. Assert(argCount == 2);
  14116. while(linkOpnd->IsSymOpnd())
  14117. {
  14118. IR::SymOpnd *src2 = linkOpnd->AsSymOpnd();
  14119. StackSym *sym = src2->m_sym->AsStackSym();
  14120. Assert(sym->m_isSingleDef);
  14121. IR::Instr *argInstr = sym->m_instrDef;
  14122. Assert(argCount >= 0);
  14123. // check to see if 'a' and 'c' are likely strings
  14124. if((argCount == 2 || argCount == 0) && (!argInstr->GetSrc1()->GetValueType().IsLikelyString()))
  14125. {
  14126. return false;
  14127. }
  14128. // we want 'b' to be regex. Don't generate fastpath if it is a tagged int
  14129. if((argCount == 1) && (argInstr->GetSrc1()->IsTaggedInt()))
  14130. {
  14131. return false;
  14132. }
  14133. argCount--;
  14134. linkOpnd = argInstr->GetSrc2();
  14135. }
  14136. return true;
  14137. }
  14138. bool
  14139. Lowerer::GenerateFastReplace(IR::Opnd* strOpnd, IR::Opnd* src1, IR::Opnd* src2, IR::Instr *callInstr, IR::Instr *insertInstr, IR::LabelInstr *labelHelper, IR::LabelInstr *doneLabel)
  14140. {
  14141. // a.replace(b,c)
  14142. // We want to emit the fast path if 'a' and 'c' are strings and 'b' is a regex
  14143. //
  14144. // strOpnd --> a
  14145. // src1 --> b
  14146. // src2 --> c
  14147. IR::Opnd * callDst = callInstr->GetDst();
  14148. Assert(strOpnd->GetValueType().IsLikelyString() && src2->GetValueType().IsLikelyString());
  14149. if(!strOpnd->GetValueType().IsString())
  14150. {
  14151. if(!strOpnd->IsRegOpnd())
  14152. {
  14153. IR::RegOpnd *strOpndReg = IR::RegOpnd::New(TyVar, m_func);
  14154. LowererMD::CreateAssign(strOpndReg, strOpnd, insertInstr);
  14155. strOpnd = strOpndReg;
  14156. }
  14157. this->GenerateStringTest(strOpnd->AsRegOpnd(), insertInstr, labelHelper);
  14158. }
  14159. if(!src1->IsNotTaggedValue())
  14160. {
  14161. m_lowererMD.GenerateObjectTest(src1, insertInstr, labelHelper);
  14162. }
  14163. IR::Opnd * vtableOpnd = LoadVTableValueOpnd(insertInstr, VTableValue::VtableJavascriptRegExp);
  14164. // cmp [regex], vtableAddress
  14165. // jne $labelHelper
  14166. if(!src1->IsRegOpnd())
  14167. {
  14168. IR::RegOpnd *src1Reg = IR::RegOpnd::New(TyVar, m_func);
  14169. LowererMD::CreateAssign(src1Reg, src1, insertInstr);
  14170. src1 = src1Reg;
  14171. }
  14172. InsertCompareBranch(
  14173. IR::IndirOpnd::New(src1->AsRegOpnd(), 0, TyMachPtr, insertInstr->m_func),
  14174. vtableOpnd,
  14175. Js::OpCode::BrNeq_A,
  14176. labelHelper,
  14177. insertInstr);
  14178. if(!src2->GetValueType().IsString())
  14179. {
  14180. if(!src2->IsRegOpnd())
  14181. {
  14182. IR::RegOpnd *src2Reg = IR::RegOpnd::New(TyVar, m_func);
  14183. LowererMD::CreateAssign(src2Reg, src2, insertInstr);
  14184. src2 = src2Reg;
  14185. }
  14186. this->GenerateStringTest(src2->AsRegOpnd(), insertInstr, labelHelper);
  14187. }
  14188. //scriptContext, pRegEx, pThis, pReplace (to be pushed in reverse order)
  14189. // pReplace, pThis, pRegEx
  14190. this->m_lowererMD.LoadHelperArgument(insertInstr, src2);
  14191. this->m_lowererMD.LoadHelperArgument(insertInstr, strOpnd);
  14192. this->m_lowererMD.LoadHelperArgument(insertInstr, src1);
  14193. // script context
  14194. LoadScriptContext(insertInstr);
  14195. IR::Instr * helperCallInstr = IR::Instr::New(LowererMD::MDCallOpcode, insertInstr->m_func);
  14196. if(callDst)
  14197. {
  14198. helperCallInstr->SetDst(callDst);
  14199. }
  14200. insertInstr->InsertBefore(helperCallInstr);
  14201. if(callDst)
  14202. {
  14203. m_lowererMD.ChangeToHelperCall(helperCallInstr, IR::JnHelperMethod::HelperRegExp_ReplaceStringResultUsed);
  14204. }
  14205. else
  14206. {
  14207. m_lowererMD.ChangeToHelperCall(helperCallInstr, IR::JnHelperMethod::HelperRegExp_ReplaceStringResultNotUsed);
  14208. }
  14209. return true;
  14210. }
  14211. ///----
  14212. void
  14213. Lowerer::GenerateFastInlineStringSplitMatch(IR::Instr * instr)
  14214. {
  14215. // a.split(b,c (optional) )
  14216. // We want to emit the fast path when
  14217. // 1. c is not present, and
  14218. // 2. 'a' is a string and 'b' is a regex.
  14219. //
  14220. // a.match(b)
  14221. // We want to emit the fast path when 'a' is a string and 'b' is a regex.
  14222. Assert(instr->m_opcode == Js::OpCode::CallDirect);
  14223. IR::Opnd * callDst = instr->GetDst();
  14224. //helperCallOpnd
  14225. IR::Opnd * src1 = instr->GetSrc1();
  14226. //ArgOut_A_InlineSpecialized
  14227. IR::Instr * tmpInstr = instr->GetSrc2()->AsSymOpnd()->m_sym->AsStackSym()->m_instrDef;
  14228. IR::Opnd * argsOpnd[2];
  14229. if(!instr->FetchOperands(argsOpnd, 2))
  14230. {
  14231. return;
  14232. }
  14233. if(!argsOpnd[0]->GetValueType().IsLikelyString() || argsOpnd[1]->IsTaggedInt())
  14234. {
  14235. return;
  14236. }
  14237. IR::LabelInstr *labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  14238. if(!argsOpnd[0]->GetValueType().IsString())
  14239. {
  14240. if(!argsOpnd[0]->IsRegOpnd())
  14241. {
  14242. IR::RegOpnd *opndReg = IR::RegOpnd::New(TyVar, m_func);
  14243. LowererMD::CreateAssign(opndReg, argsOpnd[0], instr);
  14244. argsOpnd[0] = opndReg;
  14245. }
  14246. this->GenerateStringTest(argsOpnd[0]->AsRegOpnd(), instr, labelHelper);
  14247. }
  14248. if(!argsOpnd[1]->IsNotTaggedValue())
  14249. {
  14250. m_lowererMD.GenerateObjectTest(argsOpnd[1], instr, labelHelper);
  14251. }
  14252. IR::Opnd * vtableOpnd = LoadVTableValueOpnd(instr, VTableValue::VtableJavascriptRegExp);
  14253. // cmp [regex], vtableAddress
  14254. // jne $labelHelper
  14255. if(!argsOpnd[1]->IsRegOpnd())
  14256. {
  14257. IR::RegOpnd *opndReg = IR::RegOpnd::New(TyVar, m_func);
  14258. LowererMD::CreateAssign(opndReg, argsOpnd[1], instr);
  14259. argsOpnd[1] = opndReg;
  14260. }
  14261. InsertCompareBranch(
  14262. IR::IndirOpnd::New(argsOpnd[1]->AsRegOpnd(), 0, TyMachPtr, instr->m_func),
  14263. vtableOpnd,
  14264. Js::OpCode::BrNeq_A,
  14265. labelHelper,
  14266. instr);
  14267. // [stackAllocationPointer, ]scriptcontext, regexp, input[, limit] (to be pushed in reverse order)
  14268. if(src1->AsHelperCallOpnd()->m_fnHelper == IR::JnHelperMethod::HelperString_Split)
  14269. {
  14270. //limit
  14271. //As we are optimizing only for two operands, make limit UINT_MAX
  14272. IR::Opnd* limit = IR::IntConstOpnd::New(UINT_MAX, TyUint32, instr->m_func);
  14273. this->m_lowererMD.LoadHelperArgument(instr, limit);
  14274. }
  14275. //input, regexp
  14276. this->m_lowererMD.LoadHelperArgument(instr, argsOpnd[0]);
  14277. this->m_lowererMD.LoadHelperArgument(instr, argsOpnd[1]);
  14278. // script context
  14279. LoadScriptContext(instr);
  14280. IR::JnHelperMethod helperMethod;
  14281. IR::AutoReuseOpnd autoReuseStackAllocationOpnd;
  14282. if(callDst && instr->dstIsTempObject)
  14283. {
  14284. switch(src1->AsHelperCallOpnd()->m_fnHelper)
  14285. {
  14286. case IR::JnHelperMethod::HelperString_Split:
  14287. helperMethod = IR::JnHelperMethod::HelperRegExp_SplitResultUsedAndMayBeTemp;
  14288. break;
  14289. case IR::JnHelperMethod::HelperString_Match:
  14290. helperMethod = IR::JnHelperMethod::HelperRegExp_MatchResultUsedAndMayBeTemp;
  14291. break;
  14292. default:
  14293. Assert(false);
  14294. __assume(false);
  14295. }
  14296. // Allocate some space on the stack for the result array
  14297. IR::RegOpnd *const stackAllocationOpnd = IR::RegOpnd::New(TyVar, m_func);
  14298. autoReuseStackAllocationOpnd.Initialize(stackAllocationOpnd, m_func);
  14299. stackAllocationOpnd->SetValueType(callDst->GetValueType());
  14300. GenerateMarkTempAlloc(stackAllocationOpnd, Js::JavascriptArray::StackAllocationSize, instr);
  14301. m_lowererMD.LoadHelperArgument(instr, stackAllocationOpnd);
  14302. }
  14303. else
  14304. {
  14305. switch(src1->AsHelperCallOpnd()->m_fnHelper)
  14306. {
  14307. case IR::JnHelperMethod::HelperString_Split:
  14308. helperMethod =
  14309. callDst
  14310. ? IR::JnHelperMethod::HelperRegExp_SplitResultUsed
  14311. : IR::JnHelperMethod::HelperRegExp_SplitResultNotUsed;
  14312. break;
  14313. case IR::JnHelperMethod::HelperString_Match:
  14314. helperMethod =
  14315. callDst
  14316. ? IR::JnHelperMethod::HelperRegExp_MatchResultUsed
  14317. : IR::JnHelperMethod::HelperRegExp_MatchResultNotUsed;
  14318. break;
  14319. default:
  14320. Assert(false);
  14321. __assume(false);
  14322. }
  14323. }
  14324. IR::Instr * helperCallInstr = IR::Instr::New(LowererMD::MDCallOpcode, instr->m_func);
  14325. if(callDst)
  14326. {
  14327. helperCallInstr->SetDst(callDst);
  14328. }
  14329. instr->InsertBefore(helperCallInstr);
  14330. m_lowererMD.ChangeToHelperCall(helperCallInstr, helperMethod);
  14331. IR::LabelInstr *doneLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  14332. instr->InsertAfter(doneLabel);
  14333. instr->InsertBefore(labelHelper);
  14334. InsertBranch(Js::OpCode::Br, true, doneLabel, labelHelper);
  14335. RelocateCallDirectToHelperPath(tmpInstr, labelHelper);
  14336. }
  14337. void
  14338. Lowerer::GenerateFastInlineRegExpExec(IR::Instr * instr)
  14339. {
  14340. // a.exec(b)
  14341. // We want to emit the fast path when 'a' is a regex and 'b' is a string
  14342. Assert(instr->m_opcode == Js::OpCode::CallDirect);
  14343. IR::Opnd * callDst = instr->GetDst();
  14344. //ArgOut_A_InlineSpecialized
  14345. IR::Instr * tmpInstr = instr->GetSrc2()->AsSymOpnd()->m_sym->AsStackSym()->m_instrDef;
  14346. IR::Opnd * argsOpnd[2];
  14347. if (!instr->FetchOperands(argsOpnd, 2))
  14348. {
  14349. return;
  14350. }
  14351. IR::Opnd *opndString = argsOpnd[1];
  14352. if(!opndString->GetValueType().IsLikelyString() || argsOpnd[0]->IsTaggedInt())
  14353. {
  14354. return;
  14355. }
  14356. IR::LabelInstr *labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  14357. if(!opndString->GetValueType().IsString())
  14358. {
  14359. if(!opndString->IsRegOpnd())
  14360. {
  14361. IR::RegOpnd *opndReg = IR::RegOpnd::New(TyVar, m_func);
  14362. LowererMD::CreateAssign(opndReg, opndString, instr);
  14363. opndString = opndReg;
  14364. }
  14365. this->GenerateStringTest(opndString->AsRegOpnd(), instr, labelHelper);
  14366. }
  14367. IR::Opnd *opndRegex = argsOpnd[0];
  14368. if(!opndRegex->IsNotTaggedValue())
  14369. {
  14370. m_lowererMD.GenerateObjectTest(opndRegex, instr, labelHelper);
  14371. }
  14372. IR::Opnd * vtableOpnd = LoadVTableValueOpnd(instr, VTableValue::VtableJavascriptRegExp);
  14373. // cmp [regex], vtableAddress
  14374. // jne $labelHelper
  14375. if(!opndRegex->IsRegOpnd())
  14376. {
  14377. IR::RegOpnd *opndReg = IR::RegOpnd::New(TyVar, m_func);
  14378. LowererMD::CreateAssign(opndReg, opndRegex, instr);
  14379. opndRegex = opndReg;
  14380. }
  14381. InsertCompareBranch(
  14382. IR::IndirOpnd::New(opndRegex->AsRegOpnd(), 0, TyMachPtr, instr->m_func),
  14383. vtableOpnd,
  14384. Js::OpCode::BrNeq_A,
  14385. labelHelper,
  14386. instr);
  14387. IR::LabelInstr *doneLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  14388. if (!PHASE_OFF(Js::ExecBOIFastPathPhase, m_func))
  14389. {
  14390. // Load pattern from regex operand
  14391. IR::RegOpnd *opndPattern = IR::RegOpnd::New(TyMachPtr, m_func);
  14392. LowererMD::CreateAssign(
  14393. opndPattern,
  14394. IR::IndirOpnd::New(opndRegex->AsRegOpnd(), Js::JavascriptRegExp::GetOffsetOfPattern(), TyMachPtr, m_func),
  14395. instr);
  14396. // Load program from pattern
  14397. IR::RegOpnd *opndProgram = IR::RegOpnd::New(TyMachPtr, m_func);
  14398. LowererMD::CreateAssign(
  14399. opndProgram,
  14400. IR::IndirOpnd::New(opndPattern, offsetof(UnifiedRegex::RegexPattern, rep) + offsetof(UnifiedRegex::RegexPattern::UnifiedRep, program), TyMachPtr, m_func),
  14401. instr);
  14402. IR::LabelInstr *labelFastHelper = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  14403. // We want the program's tag to be BOILiteral2Tag
  14404. InsertCompareBranch(
  14405. IR::IndirOpnd::New(opndProgram, (int32)UnifiedRegex::Program::GetOffsetOfTag(), TyUint8, m_func),
  14406. IR::IntConstOpnd::New(UnifiedRegex::Program::GetBOILiteral2Tag(), TyUint8, m_func),
  14407. Js::OpCode::BrNeq_A,
  14408. labelFastHelper,
  14409. instr);
  14410. // Test the program's flags for "global"
  14411. InsertTestBranch(
  14412. IR::IndirOpnd::New(opndProgram, offsetof(UnifiedRegex::Program, flags), TyUint8, m_func),
  14413. IR::IntConstOpnd::New(UnifiedRegex::GlobalRegexFlag, TyUint8, m_func),
  14414. Js::OpCode::BrNeq_A,
  14415. labelFastHelper,
  14416. instr);
  14417. IR::LabelInstr *labelNoMatch = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  14418. // If string length < 2...
  14419. InsertCompareBranch(
  14420. IR::IndirOpnd::New(opndString->AsRegOpnd(), offsetof(Js::JavascriptString, m_charLength), TyUint32, m_func),
  14421. IR::IntConstOpnd::New(2, TyUint32, m_func),
  14422. Js::OpCode::BrLt_A,
  14423. labelNoMatch,
  14424. instr);
  14425. // ...or the DWORD doesn't match the pattern...
  14426. IR::RegOpnd *opndBuffer = IR::RegOpnd::New(TyMachReg, m_func);
  14427. LowererMD::CreateAssign(
  14428. opndBuffer,
  14429. IR::IndirOpnd::New(opndString->AsRegOpnd(), offsetof(Js::JavascriptString, m_pszValue), TyMachPtr, m_func),
  14430. instr);
  14431. IR::LabelInstr *labelGotString = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  14432. InsertTestBranch(opndBuffer, opndBuffer, Js::OpCode::BrNeq_A, labelGotString, instr);
  14433. m_lowererMD.LoadHelperArgument(instr, opndString);
  14434. IR::Instr *instrCall = IR::Instr::New(Js::OpCode::Call, opndBuffer, IR::HelperCallOpnd::New(IR::HelperString_GetSz, m_func), m_func);
  14435. instr->InsertBefore(instrCall);
  14436. m_lowererMD.LowerCall(instrCall, 0);
  14437. instr->InsertBefore(labelGotString);
  14438. IR::RegOpnd *opndBufferDWORD = IR::RegOpnd::New(TyUint32, m_func);
  14439. LowererMD::CreateAssign(
  14440. opndBufferDWORD,
  14441. IR::IndirOpnd::New(opndBuffer, 0, TyUint32, m_func),
  14442. instr);
  14443. InsertCompareBranch(
  14444. IR::IndirOpnd::New(opndProgram, (int32)(UnifiedRegex::Program::GetOffsetOfRep() + UnifiedRegex::Program::GetOffsetOfBOILiteral2Literal()), TyUint32, m_func),
  14445. opndBufferDWORD,
  14446. Js::OpCode::BrEq_A,
  14447. labelFastHelper,
  14448. instr);
  14449. // ...then set the last index to 0...
  14450. instr->InsertBefore(labelNoMatch);
  14451. LowererMD::CreateAssign(
  14452. IR::IndirOpnd::New(opndRegex->AsRegOpnd(), Js::JavascriptRegExp::GetOffsetOfLastIndexVar(), TyVar, m_func),
  14453. IR::AddrOpnd::NewNull(m_func),
  14454. instr);
  14455. LowererMD::CreateAssign(
  14456. IR::IndirOpnd::New(opndRegex->AsRegOpnd(), Js::JavascriptRegExp::GetOffsetOfLastIndexOrFlag(), TyUint32, m_func),
  14457. IR::IntConstOpnd::New(0, TyUint32, m_func),
  14458. instr);
  14459. // ...and set the dst to null...
  14460. if (callDst)
  14461. {
  14462. LowererMD::CreateAssign(
  14463. callDst,
  14464. LoadLibraryValueOpnd(instr, LibraryValue::ValueNull),
  14465. instr);
  14466. }
  14467. // ...and we're done.
  14468. this->InsertBranch(Js::OpCode::Br, doneLabel, instr);
  14469. instr->InsertBefore(labelFastHelper);
  14470. }
  14471. // [stackAllocationPointer, ]scriptcontext, regexp, string (to be pushed in reverse order)
  14472. //string, regexp
  14473. this->m_lowererMD.LoadHelperArgument(instr, opndString);
  14474. this->m_lowererMD.LoadHelperArgument(instr, opndRegex);
  14475. // script context
  14476. LoadScriptContext(instr);
  14477. IR::JnHelperMethod helperMethod;
  14478. IR::AutoReuseOpnd autoReuseStackAllocationOpnd;
  14479. if(callDst)
  14480. {
  14481. if(instr->dstIsTempObject)
  14482. {
  14483. helperMethod = IR::JnHelperMethod::HelperRegExp_ExecResultUsedAndMayBeTemp;
  14484. // Allocate some space on the stack for the result array
  14485. IR::RegOpnd *const stackAllocationOpnd = IR::RegOpnd::New(TyVar, m_func);
  14486. autoReuseStackAllocationOpnd.Initialize(stackAllocationOpnd, m_func);
  14487. stackAllocationOpnd->SetValueType(callDst->GetValueType());
  14488. GenerateMarkTempAlloc(stackAllocationOpnd, Js::JavascriptArray::StackAllocationSize, instr);
  14489. m_lowererMD.LoadHelperArgument(instr, stackAllocationOpnd);
  14490. }
  14491. else
  14492. {
  14493. helperMethod = IR::JnHelperMethod::HelperRegExp_ExecResultUsed;
  14494. }
  14495. }
  14496. else
  14497. {
  14498. helperMethod = IR::JnHelperMethod::HelperRegExp_ExecResultNotUsed;
  14499. }
  14500. IR::Instr * helperCallInstr = IR::Instr::New(LowererMD::MDCallOpcode, instr->m_func);
  14501. if(callDst)
  14502. {
  14503. helperCallInstr->SetDst(callDst);
  14504. }
  14505. instr->InsertBefore(helperCallInstr);
  14506. m_lowererMD.ChangeToHelperCall(helperCallInstr, helperMethod);
  14507. instr->InsertAfter(doneLabel);
  14508. instr->InsertBefore(labelHelper);
  14509. InsertBranch(Js::OpCode::Br, true, doneLabel, labelHelper);
  14510. RelocateCallDirectToHelperPath(tmpInstr, labelHelper);
  14511. }
  14512. void
  14513. Lowerer::RelocateCallDirectToHelperPath(IR::Instr* argoutInlineSpecialized, IR::LabelInstr* labelHelper)
  14514. {
  14515. IR::Opnd *linkOpnd = argoutInlineSpecialized->GetSrc2(); //ArgOut_A_InlineSpecialized src2; link to actual argouts.
  14516. argoutInlineSpecialized->Unlink();
  14517. labelHelper->InsertAfter(argoutInlineSpecialized);
  14518. while(linkOpnd->IsSymOpnd())
  14519. {
  14520. IR::SymOpnd *src2 = linkOpnd->AsSymOpnd();
  14521. StackSym *sym = src2->m_sym->AsStackSym();
  14522. Assert(sym->m_isSingleDef);
  14523. IR::Instr *argInstr = sym->m_instrDef;
  14524. Assert(argInstr->m_opcode == Js::OpCode::ArgOut_A);
  14525. argInstr->Unlink();
  14526. labelHelper->InsertAfter(argInstr);
  14527. linkOpnd = argInstr->GetSrc2();
  14528. }
  14529. // Move startcall
  14530. Assert(linkOpnd->IsRegOpnd());
  14531. StackSym *sym = linkOpnd->AsRegOpnd()->m_sym;
  14532. Assert(sym->m_isSingleDef);
  14533. IR::Instr *startCall = sym->m_instrDef;
  14534. Assert(startCall->m_opcode == Js::OpCode::StartCall);
  14535. startCall->Unlink();
  14536. labelHelper->InsertAfter(startCall);
  14537. }
  14538. bool
  14539. Lowerer::GenerateFastInlineStringCharCodeAt(IR::Instr * instr, Js::BuiltinFunction index)
  14540. {
  14541. Assert(instr->m_opcode == Js::OpCode::CallDirect);
  14542. //CallDirect src2
  14543. IR::Opnd * linkOpnd = instr->GetSrc2();
  14544. //ArgOut_A_InlineSpecialized
  14545. IR::Instr * tmpInstr = linkOpnd->AsSymOpnd()->m_sym->AsStackSym()->m_instrDef;
  14546. IR::Opnd * argsOpnd[2] = {0};
  14547. bool result = instr->FetchOperands(argsOpnd, 2);
  14548. Assert(result);
  14549. IR::LabelInstr *doneLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  14550. instr->InsertAfter(doneLabel);
  14551. IR::LabelInstr *labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  14552. bool success = this->m_lowererMD.GenerateFastCharAt(index, instr->GetDst(), argsOpnd[0], argsOpnd[1],
  14553. instr, instr, labelHelper, doneLabel);
  14554. instr->InsertBefore(labelHelper);
  14555. if (!success)
  14556. {
  14557. return false;
  14558. }
  14559. InsertBranch(Js::OpCode::Br, true, doneLabel, labelHelper);
  14560. RelocateCallDirectToHelperPath(tmpInstr, labelHelper);
  14561. return true;
  14562. }
  14563. void
  14564. Lowerer::GenerateFastInlineMathClz32(IR::Instr* instr)
  14565. {
  14566. Assert(instr->GetDst()->IsInt32());
  14567. Assert(instr->GetSrc1()->IsInt32());
  14568. m_lowererMD.GenerateClz(instr);
  14569. }
  14570. void
  14571. Lowerer::GenerateFastInlineMathImul(IR::Instr* instr)
  14572. {
  14573. IR::Opnd* src1 = instr->GetSrc1();
  14574. IR::Opnd* src2 = instr->GetSrc2();
  14575. IR::Opnd* dst = instr->GetDst();
  14576. Assert(dst->IsInt32());
  14577. Assert(src1->IsInt32());
  14578. Assert(src2->IsInt32());
  14579. IR::Instr* imul = IR::Instr::New(LowererMD::MDImulOpcode, dst, src1, src2, instr->m_func);
  14580. instr->InsertBefore(imul);
  14581. LowererMD::Legalize(imul);
  14582. instr->Remove();
  14583. }
  14584. void
  14585. Lowerer::GenerateFastInlineMathFround(IR::Instr* instr)
  14586. {
  14587. IR::Opnd* src1 = instr->GetSrc1();
  14588. IR::Opnd* dst = instr->GetDst();
  14589. Assert(dst->IsFloat());
  14590. Assert(src1->IsFloat());
  14591. IR::Instr* fcvt64to32 = IR::Instr::New(LowererMD::MDConvertFloat64ToFloat32Opcode, dst, src1, instr->m_func);
  14592. instr->InsertBefore(fcvt64to32);
  14593. LowererMD::Legalize(fcvt64to32);
  14594. if (dst->IsFloat64())
  14595. {
  14596. IR::Instr* fcvt32to64 = IR::Instr::New(LowererMD::MDConvertFloat32ToFloat64Opcode, dst, dst, instr->m_func);
  14597. instr->InsertBefore(fcvt32to64);
  14598. LowererMD::Legalize(fcvt32to64);
  14599. }
  14600. instr->Remove();
  14601. return;
  14602. }
  14603. bool
  14604. Lowerer::GenerateFastInlineStringReplace(IR::Instr * instr)
  14605. {
  14606. Assert(instr->m_opcode == Js::OpCode::CallDirect);
  14607. //CallDirect src2
  14608. IR::Opnd * linkOpnd = instr->GetSrc2();
  14609. //ArgOut_A_InlineSpecialized
  14610. IR::Instr * tmpInstr = linkOpnd->AsSymOpnd()->m_sym->AsStackSym()->m_instrDef;
  14611. IR::Opnd * argsOpnd[3] = {0};
  14612. bool result = instr->FetchOperands(argsOpnd, 3);
  14613. Assert(result);
  14614. AnalysisAssert(argsOpnd[0] && argsOpnd[1] && argsOpnd[2]);
  14615. if (!argsOpnd[0]->GetValueType().IsLikelyString()
  14616. || argsOpnd[1]->GetValueType().IsNotObject()
  14617. || !argsOpnd[2]->GetValueType().IsLikelyString())
  14618. {
  14619. return false;
  14620. }
  14621. IR::LabelInstr *doneLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  14622. instr->InsertAfter(doneLabel);
  14623. IR::LabelInstr *labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  14624. bool success = this->GenerateFastReplace(argsOpnd[0], argsOpnd[1], argsOpnd[2],
  14625. instr, instr, labelHelper, doneLabel);
  14626. instr->InsertBefore(labelHelper);
  14627. if (!success)
  14628. {
  14629. return false;
  14630. }
  14631. InsertBranch(Js::OpCode::Br, true, doneLabel, labelHelper);
  14632. RelocateCallDirectToHelperPath(tmpInstr, labelHelper);
  14633. return true;
  14634. }
  14635. #ifdef ENABLE_DOM_FAST_PATH
  14636. /*
  14637. Lower the DOMFastPathGetter opcode
  14638. We have inliner generated bytecode:
  14639. (dst)helpArg1: ExtendArg_A (src1)thisObject (src2)null
  14640. (dst)helpArg2: ExtendArg_A (src1)funcObject (src2)helpArg1
  14641. method: DOMFastPathGetter (src1)HelperCall (src2)helpArg2
  14642. We'll convert it to a JavascriptFunction entry method call:
  14643. CALL Helper funcObject CallInfo(CallFlags_Value, 3) thisObj
  14644. */
  14645. void
  14646. Lowerer::LowerFastInlineDOMFastPathGetter(IR::Instr* instr)
  14647. {
  14648. IR::Opnd* helperOpnd = instr->UnlinkSrc1();
  14649. Assert(helperOpnd->IsHelperCallOpnd());
  14650. IR::Opnd *linkOpnd = instr->UnlinkSrc2();
  14651. Assert(linkOpnd->IsRegOpnd());
  14652. IR::Instr* prevInstr = linkOpnd->AsRegOpnd()->m_sym->m_instrDef;
  14653. Assert(prevInstr->m_opcode == Js::OpCode::ExtendArg_A);
  14654. IR::Opnd* funcObj = prevInstr->GetSrc1();
  14655. Assert(funcObj->IsRegOpnd());
  14656. // If the Extended_arg was CSE's across a loop or hoisted out of a loop,
  14657. // adding a new reference down here might cause funcObj to now be liveOnBackEdge.
  14658. // Use the addToLiveOnBackEdgeSyms bit vector to add it to a loop if we encounter one.
  14659. // We'll clear it once we reach the Extended arg.
  14660. this->addToLiveOnBackEdgeSyms->Set(funcObj->AsRegOpnd()->m_sym->m_id);
  14661. Assert(prevInstr->GetSrc2() != nullptr);
  14662. prevInstr = prevInstr->GetSrc2()->AsRegOpnd()->m_sym->m_instrDef;
  14663. Assert(prevInstr->m_opcode == Js::OpCode::ExtendArg_A);
  14664. IR::Opnd* thisObj = prevInstr->GetSrc1();
  14665. Assert(prevInstr->GetSrc2() == nullptr);
  14666. Assert(thisObj->IsRegOpnd());
  14667. this->addToLiveOnBackEdgeSyms->Set(thisObj->AsRegOpnd()->m_sym->m_id);
  14668. const auto info = Lowerer::MakeCallInfoConst(Js::CallFlags_Value, 1, m_func);
  14669. m_lowererMD.LoadHelperArgument(instr, thisObj);
  14670. m_lowererMD.LoadHelperArgument(instr, info);
  14671. m_lowererMD.LoadHelperArgument(instr, funcObj);
  14672. instr->m_opcode = Js::OpCode::Call;
  14673. IR::HelperCallOpnd *helperCallOpnd = Lowerer::CreateHelperCallOpnd(helperOpnd->AsHelperCallOpnd()->m_fnHelper, 3, m_func);
  14674. instr->SetSrc1(helperCallOpnd);
  14675. m_lowererMD.LowerCall(instr, 3); // we have funcobj, callInfo, and this.
  14676. }
  14677. #endif
  14678. void
  14679. Lowerer::GenerateFastInlineArrayPush(IR::Instr * instr)
  14680. {
  14681. Assert(instr->m_opcode == Js::OpCode::InlineArrayPush);
  14682. IR::Opnd * baseOpnd = instr->GetSrc1();
  14683. IR::Opnd * srcOpnd = instr->GetSrc2();
  14684. bool returnLength = false;
  14685. if(instr->GetDst())
  14686. {
  14687. returnLength = true;
  14688. }
  14689. IR::LabelInstr * bailOutLabelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  14690. IR::LabelInstr *doneLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  14691. instr->InsertAfter(doneLabel);
  14692. IR::LabelInstr *labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  14693. //Don't Generate fast path according to ShouldGenerateArrayFastPath()
  14694. //AND, Don't Generate fast path if the array is LikelyNative and the element is not specialized
  14695. if(ShouldGenerateArrayFastPath(baseOpnd, false, false, false) &&
  14696. !(baseOpnd->GetValueType().IsLikelyNativeArray() && srcOpnd->IsVar()))
  14697. {
  14698. GenerateFastPush(baseOpnd, srcOpnd, instr, instr, labelHelper, doneLabel, bailOutLabelHelper, returnLength);
  14699. instr->InsertBefore(labelHelper);
  14700. InsertBranch(Js::OpCode::Br, true, doneLabel, labelHelper);
  14701. }
  14702. if(baseOpnd->GetValueType().IsLikelyNativeArray())
  14703. {
  14704. //Lower IR::BailOutConventionalNativeArrayAccessOnly here.
  14705. LowerOneBailOutKind(instr, IR::BailOutConventionalNativeArrayAccessOnly, false, false);
  14706. instr->InsertAfter(bailOutLabelHelper);
  14707. InsertBranch(Js::OpCode::Br, doneLabel, bailOutLabelHelper);
  14708. }
  14709. GenerateHelperToArrayPushFastPath(instr, bailOutLabelHelper);
  14710. }
  14711. bool Lowerer::GenerateFastPop(IR::Opnd *baseOpndParam, IR::Instr *callInstr, IR::LabelInstr *labelHelper, IR::LabelInstr *doneLabel, IR::LabelInstr * bailOutLabelHelper)
  14712. {
  14713. Assert(ShouldGenerateArrayFastPath(baseOpndParam, false, false, false));
  14714. // TEST baseOpnd, AtomTag -- check baseOpnd not tagged int
  14715. // JNE $helper
  14716. // CMP [baseOpnd], JavascriptArray::`vtable' -- check baseOpnd isArray
  14717. // JNE $helper
  14718. // MOV r2, [baseOpnd + offset(length)] -- Load array length
  14719. IR::RegOpnd * baseOpnd = baseOpndParam->AsRegOpnd();
  14720. const IR::AutoReuseOpnd autoReuseBaseOpnd(baseOpnd, m_func);
  14721. ValueType arrValueType(baseOpndParam->GetValueType());
  14722. IR::RegOpnd *arrayOpnd = baseOpnd;
  14723. IR::RegOpnd *arrayLengthOpnd = nullptr;
  14724. IR::AutoReuseOpnd autoReuseArrayLengthOpnd;
  14725. if(!arrValueType.IsAnyOptimizedArray())
  14726. {
  14727. arrayOpnd = GenerateArrayTest(baseOpnd, bailOutLabelHelper, bailOutLabelHelper, callInstr, false, true);
  14728. arrValueType = arrayOpnd->GetValueType().ToDefiniteObject().SetHasNoMissingValues(false);
  14729. }
  14730. else if(arrayOpnd->IsArrayRegOpnd())
  14731. {
  14732. IR::ArrayRegOpnd *const arrayRegOpnd = arrayOpnd->AsArrayRegOpnd();
  14733. if(arrayRegOpnd->LengthSym())
  14734. {
  14735. arrayLengthOpnd = IR::RegOpnd::New(arrayRegOpnd->LengthSym(), arrayRegOpnd->LengthSym()->GetType(), m_func);
  14736. DebugOnly(arrayLengthOpnd->FreezeSymValue());
  14737. autoReuseArrayLengthOpnd.Initialize(arrayLengthOpnd, m_func);
  14738. }
  14739. }
  14740. const IR::AutoReuseOpnd autoReuseArrayOpnd(arrayOpnd, m_func);
  14741. IR::AutoReuseOpnd autoReuseMutableArrayLengthOpnd;
  14742. {
  14743. IR::RegOpnd *const mutableArrayLengthOpnd = IR::RegOpnd::New(TyUint32, m_func);
  14744. autoReuseMutableArrayLengthOpnd.Initialize(mutableArrayLengthOpnd, m_func);
  14745. if(arrayLengthOpnd)
  14746. {
  14747. // mov mutableArrayLength, arrayLength
  14748. InsertMove(mutableArrayLengthOpnd, arrayLengthOpnd, callInstr);
  14749. }
  14750. else
  14751. {
  14752. // MOV mutableArrayLength, [array + offset(length)] -- Load array length
  14753. // We know this index is safe since, so mark it as UInt32 to avoid unnecessary conversion/checks
  14754. InsertMove(
  14755. mutableArrayLengthOpnd,
  14756. IR::IndirOpnd::New(
  14757. arrayOpnd,
  14758. Js::JavascriptArray::GetOffsetOfLength(),
  14759. mutableArrayLengthOpnd->GetType(),
  14760. this->m_func),
  14761. callInstr);
  14762. }
  14763. arrayLengthOpnd = mutableArrayLengthOpnd;
  14764. }
  14765. InsertCompareBranch(arrayLengthOpnd, IR::IntConstOpnd::New(0, TyUint32, this->m_func), Js::OpCode::BrEq_A, true, bailOutLabelHelper, callInstr);
  14766. InsertSub(false, arrayLengthOpnd, arrayLengthOpnd, IR::IntConstOpnd::New(1, TyUint32, this->m_func),callInstr);
  14767. IR::IndirOpnd *arrayRef = IR::IndirOpnd::New(arrayOpnd, arrayLengthOpnd, TyVar, this->m_func);
  14768. arrayRef->GetBaseOpnd()->SetValueType(arrValueType);
  14769. //Array length is going to overflow, hence don't check for Array.length and Segment.length overflow.
  14770. bool isTypedArrayElement, isStringIndex;
  14771. IR::IndirOpnd *const indirOpnd =
  14772. GenerateFastElemICommon(
  14773. callInstr,
  14774. false,
  14775. arrayRef,
  14776. labelHelper,
  14777. labelHelper,
  14778. nullptr,
  14779. &isTypedArrayElement,
  14780. &isStringIndex,
  14781. nullptr,
  14782. nullptr /*pLabelSegmentLengthIncreased*/,
  14783. true /*checkArrayLengthOverflow*/,
  14784. true /* forceGenerateFastPath */,
  14785. false/* = returnLength */,
  14786. bailOutLabelHelper /* = bailOutLabelInstr*/);
  14787. Assert(!isTypedArrayElement);
  14788. Assert(indirOpnd);
  14789. return true;
  14790. }
  14791. bool Lowerer::GenerateFastPush(IR::Opnd *baseOpndParam, IR::Opnd *src, IR::Instr *callInstr,
  14792. IR::Instr *insertInstr, IR::LabelInstr *labelHelper, IR::LabelInstr *doneLabel, IR::LabelInstr * bailOutLabelHelper, bool returnLength)
  14793. {
  14794. Assert(ShouldGenerateArrayFastPath(baseOpndParam, false, false, false));
  14795. // TEST baseOpnd, AtomTag -- check baseOpnd not tagged int
  14796. // JNE $helper
  14797. // CMP [baseOpnd], JavascriptArray::`vtable' -- check baseOpnd isArray
  14798. // JNE $helper
  14799. // MOV r2, [baseOpnd + offset(length)] -- Load array length
  14800. IR::RegOpnd * baseOpnd = baseOpndParam->AsRegOpnd();
  14801. const IR::AutoReuseOpnd autoReuseBaseOpnd(baseOpnd, m_func);
  14802. ValueType arrValueType(baseOpndParam->GetValueType());
  14803. IR::RegOpnd *arrayOpnd = baseOpnd;
  14804. IR::RegOpnd *arrayLengthOpnd = nullptr;
  14805. IR::AutoReuseOpnd autoReuseArrayLengthOpnd;
  14806. if(!arrValueType.IsAnyOptimizedArray())
  14807. {
  14808. arrayOpnd = GenerateArrayTest(baseOpnd, labelHelper, labelHelper, insertInstr, false, true);
  14809. arrValueType = arrayOpnd->GetValueType().ToDefiniteObject().SetHasNoMissingValues(false);
  14810. }
  14811. else if(arrayOpnd->IsArrayRegOpnd())
  14812. {
  14813. IR::ArrayRegOpnd *const arrayRegOpnd = arrayOpnd->AsArrayRegOpnd();
  14814. if(arrayRegOpnd->LengthSym())
  14815. {
  14816. arrayLengthOpnd = IR::RegOpnd::New(arrayRegOpnd->LengthSym(), arrayRegOpnd->LengthSym()->GetType(), m_func);
  14817. DebugOnly(arrayLengthOpnd->FreezeSymValue());
  14818. autoReuseArrayLengthOpnd.Initialize(arrayLengthOpnd, m_func);
  14819. }
  14820. }
  14821. const IR::AutoReuseOpnd autoReuseArrayOpnd(arrayOpnd, m_func);
  14822. if(!arrayLengthOpnd)
  14823. {
  14824. // MOV arrayLength, [array + offset(length)] -- Load array length
  14825. // We know this index is safe since, so mark it as UInt32 to avoid unnecessary conversion/checks
  14826. arrayLengthOpnd = IR::RegOpnd::New(TyUint32, m_func);
  14827. autoReuseArrayLengthOpnd.Initialize(arrayLengthOpnd, m_func);
  14828. InsertMove(
  14829. arrayLengthOpnd,
  14830. IR::IndirOpnd::New(arrayOpnd, Js::JavascriptArray::GetOffsetOfLength(), arrayLengthOpnd->GetType(), this->m_func),
  14831. insertInstr);
  14832. }
  14833. IR::IndirOpnd *arrayRef = IR::IndirOpnd::New(arrayOpnd, arrayLengthOpnd, TyVar, this->m_func);
  14834. arrayRef->GetBaseOpnd()->SetValueType(arrValueType);
  14835. if (returnLength && src->IsEqual(insertInstr->GetDst()))
  14836. {
  14837. //If the dst is same as the src, then dst is going to be overridden by GenerateFastElemICommon in process of updating the length.
  14838. //Save it in a temp register.
  14839. IR::RegOpnd *opnd = IR::RegOpnd::New(src->GetType(), this->m_func);
  14840. InsertMove(opnd, src, insertInstr);
  14841. src = opnd;
  14842. }
  14843. //Array length is going to overflow, hence don't check for Array.length and Segment.length overflow.
  14844. bool isTypedArrayElement, isStringIndex;
  14845. IR::IndirOpnd *const indirOpnd =
  14846. GenerateFastElemICommon(
  14847. insertInstr,
  14848. true,
  14849. arrayRef,
  14850. labelHelper,
  14851. labelHelper,
  14852. nullptr,
  14853. &isTypedArrayElement,
  14854. &isStringIndex,
  14855. nullptr,
  14856. nullptr /*pLabelSegmentLengthIncreased*/,
  14857. false /*checkArrayLengthOverflow*/,
  14858. true /* forceGenerateFastPath */,
  14859. returnLength,
  14860. bailOutLabelHelper);
  14861. Assert(!isTypedArrayElement);
  14862. Assert(indirOpnd);
  14863. // MOV [r3 + r2], src
  14864. InsertMoveWithBarrier(indirOpnd, src, insertInstr);
  14865. return true;
  14866. }
  14867. IR::Opnd*
  14868. Lowerer::GenerateArgOutForInlineeStackArgs(IR::Instr* callInstr, IR::Instr* stackArgsInstr)
  14869. {
  14870. Assert(callInstr->m_func->IsInlinee());
  14871. Func *func = callInstr->m_func;
  14872. uint32 actualCount = func->actualCount - 1; // don't count this pointer
  14873. Assert(actualCount < Js::InlineeCallInfo::MaxInlineeArgoutCount);
  14874. const auto firstRealArgStackSym = func->GetInlineeArgvSlotOpnd()->m_sym->AsStackSym();
  14875. this->m_func->SetArgOffset(firstRealArgStackSym, firstRealArgStackSym->m_offset + MachPtr); //Start after this pointer
  14876. IR::SymOpnd *firstArg = IR::SymOpnd::New(firstRealArgStackSym, TyMachPtr, func);
  14877. const IR::AutoReuseOpnd autoReuseFirstArg(firstArg, func);
  14878. IR::RegOpnd* argInOpnd = IR::RegOpnd::New(TyMachReg, func);
  14879. const IR::AutoReuseOpnd autoReuseArgInOpnd(argInOpnd, func);
  14880. InsertLea(argInOpnd, firstArg, callInstr);
  14881. IR::IndirOpnd *argIndirOpnd = nullptr;
  14882. IR::Instr* argout = nullptr;
  14883. #if defined(_M_IX86)
  14884. // Maintain alignment
  14885. if ((actualCount & 1) == 0)
  14886. {
  14887. IR::Instr *alignPush = IR::Instr::New(Js::OpCode::PUSH, this->m_func);
  14888. alignPush->SetSrc1(IR::IntConstOpnd::New(1, TyInt32, this->m_func));
  14889. callInstr->InsertBefore(alignPush);
  14890. }
  14891. #endif
  14892. for(uint i = actualCount; i > 0; i--)
  14893. {
  14894. argIndirOpnd = IR::IndirOpnd::New(argInOpnd, (i - 1) * MachPtr, TyMachReg, func);
  14895. argout = IR::Instr::New(Js::OpCode::ArgOut_A_Dynamic, func);
  14896. argout->SetSrc1(argIndirOpnd);
  14897. callInstr->InsertBefore(argout);
  14898. // i represents ith arguments from actuals, with is i + 3 counting this, callInfo and function object
  14899. this->m_lowererMD.LoadDynamicArgument(argout, i + 3);
  14900. }
  14901. return IR::IntConstOpnd::New(func->actualCount, TyInt32, func);
  14902. }
  14903. // For AMD64 and ARM only.
  14904. void
  14905. Lowerer::LowerInlineSpreadArgOutLoopUsingRegisters(IR::Instr *callInstr, IR::RegOpnd *indexOpnd, IR::RegOpnd *arrayElementsStartOpnd)
  14906. {
  14907. Func *const func = callInstr->m_func;
  14908. IR::LabelInstr *oneArgLabel = IR::LabelInstr::New(Js::OpCode::Label, func);
  14909. InsertCompareBranch(indexOpnd, IR::IntConstOpnd::New(1, TyUint8, func), Js::OpCode::BrEq_A, true, oneArgLabel, callInstr);
  14910. IR::LabelInstr *startLoopLabel = IR::LabelInstr::New(Js::OpCode::Label, func);
  14911. startLoopLabel->m_isLoopTop = true;
  14912. Loop *loop = JitAnew(func->m_alloc, Loop, func->m_alloc, this->m_func);
  14913. startLoopLabel->SetLoop(loop);
  14914. loop->SetLoopTopInstr(startLoopLabel);
  14915. loop->regAlloc.liveOnBackEdgeSyms = AllocatorNew(JitArenaAllocator, func->m_alloc, BVSparse<JitArenaAllocator>, func->m_alloc);
  14916. loop->regAlloc.liveOnBackEdgeSyms->Set(indexOpnd->m_sym->m_id);
  14917. loop->regAlloc.liveOnBackEdgeSyms->Set(arrayElementsStartOpnd->m_sym->m_id);
  14918. callInstr->InsertBefore(startLoopLabel);
  14919. InsertSub(false, indexOpnd, indexOpnd, IR::IntConstOpnd::New(1, TyInt8, func), callInstr);
  14920. IR::IndirOpnd *elemPtrOpnd = IR::IndirOpnd::New(arrayElementsStartOpnd, indexOpnd, this->m_lowererMD.GetDefaultIndirScale(), TyMachPtr, func);
  14921. // Generate argout for n+2 arg (skipping function object + this)
  14922. IR::Instr *argout = IR::Instr::New(Js::OpCode::ArgOut_A_Dynamic, func);
  14923. // X64 requires a reg opnd
  14924. IR::RegOpnd *elemRegOpnd = IR::RegOpnd::New(TyMachPtr, func);
  14925. LowererMD::CreateAssign(elemRegOpnd, elemPtrOpnd, callInstr);
  14926. argout->SetSrc1(elemRegOpnd);
  14927. argout->SetSrc2(indexOpnd);
  14928. callInstr->InsertBefore(argout);
  14929. this->m_lowererMD.LoadDynamicArgumentUsingLength(argout);
  14930. InsertCompareBranch(indexOpnd, IR::IntConstOpnd::New(1, TyUint8, func), Js::OpCode::BrNeq_A, true, startLoopLabel, callInstr);
  14931. // Emit final argument into register 4 on AMD64 and ARM
  14932. callInstr->InsertBefore(oneArgLabel);
  14933. argout = IR::Instr::New(Js::OpCode::ArgOut_A_Dynamic, func);
  14934. argout->SetSrc1(elemPtrOpnd);
  14935. callInstr->InsertBefore(argout);
  14936. this->m_lowererMD.LoadDynamicArgument(argout, 4); //4 to denote this is 4th register after this, callinfo & function object
  14937. }
  14938. IR::Instr *
  14939. Lowerer::LowerCallIDynamicSpread(IR::Instr *callInstr, ushort callFlags)
  14940. {
  14941. Assert(callInstr->m_opcode == Js::OpCode::CallIDynamicSpread);
  14942. IR::Instr * insertBeforeInstrForCFG = nullptr;
  14943. Func *const func = callInstr->m_func;
  14944. if (func->IsInlinee())
  14945. {
  14946. throw Js::RejitException(RejitReason::InlineSpreadDisabled);
  14947. }
  14948. IR::Instr *spreadArrayInstr = callInstr;
  14949. IR::SymOpnd *argLinkOpnd = spreadArrayInstr->UnlinkSrc2()->AsSymOpnd();
  14950. StackSym *argLinkSym = argLinkOpnd->m_sym->AsStackSym();
  14951. AssertMsg(argLinkSym->IsArgSlotSym() && argLinkSym->m_isSingleDef, "Arg tree not single def...");
  14952. argLinkOpnd->Free(this->m_func);
  14953. spreadArrayInstr = argLinkSym->m_instrDef;
  14954. Assert(spreadArrayInstr->m_opcode == Js::OpCode::ArgOut_A_SpreadArg);
  14955. IR::RegOpnd *arrayOpnd = nullptr;
  14956. IR::Opnd *arraySrcOpnd = spreadArrayInstr->UnlinkSrc1();
  14957. if (!arraySrcOpnd->IsRegOpnd())
  14958. {
  14959. arrayOpnd = IR::RegOpnd::New(TyMachPtr, func);
  14960. LowererMD::CreateAssign(arrayOpnd, arraySrcOpnd, spreadArrayInstr);
  14961. }
  14962. else
  14963. {
  14964. arrayOpnd = arraySrcOpnd->AsRegOpnd();
  14965. }
  14966. argLinkOpnd = spreadArrayInstr->UnlinkSrc2()->AsSymOpnd();
  14967. // Walk the arg chain and find the start call
  14968. argLinkSym = argLinkOpnd->m_sym->AsStackSym();
  14969. AssertMsg(argLinkSym->IsArgSlotSym() && argLinkSym->m_isSingleDef, "Arg tree not single def...");
  14970. argLinkOpnd->Free(this->m_func);
  14971. // Nothing to be done for the function object, emit as normal
  14972. IR::Instr *thisInstr = argLinkSym->m_instrDef;
  14973. IR::RegOpnd *thisOpnd = thisInstr->UnlinkSrc2()->AsRegOpnd();
  14974. argLinkSym = thisOpnd->m_sym->AsStackSym();
  14975. thisInstr->Unlink();
  14976. thisInstr->FreeDst();
  14977. // Remove the array ArgOut instr and StartCall, they are no longer needed
  14978. spreadArrayInstr->Unlink();
  14979. spreadArrayInstr->FreeDst();
  14980. IR::Instr *startCallInstr = argLinkSym->m_instrDef;
  14981. Assert(startCallInstr->m_opcode == Js::OpCode::StartCall);
  14982. insertBeforeInstrForCFG = startCallInstr->GetNextRealInstr();
  14983. startCallInstr->Remove();
  14984. IR::RegOpnd *argsLengthOpnd = IR::RegOpnd::New(TyUint32, func);
  14985. IR::IndirOpnd *arrayLengthPtrOpnd = IR::IndirOpnd::New(arrayOpnd, Js::JavascriptArray::GetOffsetOfLength(), TyUint32, func);
  14986. LowererMD::CreateAssign(argsLengthOpnd, arrayLengthPtrOpnd, callInstr);
  14987. // Don't bother expanding args if there are zero
  14988. IR::LabelInstr *zeroArgsLabel = IR::LabelInstr::New(Js::OpCode::Label, func);
  14989. InsertCompareBranch(argsLengthOpnd, IR::IntConstOpnd::New(0, TyInt8, func), Js::OpCode::BrEq_A, true, zeroArgsLabel, callInstr);
  14990. IR::RegOpnd *indexOpnd = IR::RegOpnd::New(TyUint32, func);
  14991. LowererMD::CreateAssign(indexOpnd, argsLengthOpnd, callInstr);
  14992. // Get the array head offset and length
  14993. IR::IndirOpnd *arrayHeadPtrOpnd = IR::IndirOpnd::New(arrayOpnd, Js::JavascriptArray::GetOffsetOfHead(), TyMachPtr, func);
  14994. IR::RegOpnd *arrayElementsStartOpnd = IR::RegOpnd::New(TyMachPtr, func);
  14995. InsertAdd(false, arrayElementsStartOpnd, arrayHeadPtrOpnd, IR::IntConstOpnd::New(offsetof(Js::SparseArraySegment<Js::Var>, elements), TyUint8, func), callInstr);
  14996. this->m_lowererMD.LowerInlineSpreadArgOutLoop(callInstr, indexOpnd, arrayElementsStartOpnd);
  14997. // Resume if we have zero args
  14998. callInstr->InsertBefore(zeroArgsLabel);
  14999. // Lower call
  15000. callInstr->m_opcode = Js::OpCode::CallIDynamic;
  15001. callInstr = m_lowererMD.LowerCallIDynamic(callInstr, thisInstr, argsLengthOpnd, callFlags, insertBeforeInstrForCFG);
  15002. return callInstr;
  15003. }
  15004. IR::Instr *
  15005. Lowerer::LowerCallIDynamic(IR::Instr * callInstr, ushort callFlags)
  15006. {
  15007. if (!this->m_func->GetHasStackArgs())
  15008. {
  15009. throw Js::RejitException(RejitReason::InlineApplyDisabled);
  15010. }
  15011. IR::Instr * insertBeforeInstrForCFG = nullptr;
  15012. // Lower args and look for StartCall
  15013. IR::Instr * argInstr = callInstr;
  15014. IR::SymOpnd * argLinkOpnd = argInstr->UnlinkSrc2()->AsSymOpnd();
  15015. StackSym * argLinkSym = argLinkOpnd->m_sym->AsStackSym();
  15016. AssertMsg(argLinkSym->IsArgSlotSym() && argLinkSym->m_isSingleDef, "Arg tree not single def...");
  15017. argLinkOpnd->Free(this->m_func);
  15018. argInstr = argLinkSym->m_instrDef;
  15019. Assert(argInstr->m_opcode == Js::OpCode::ArgOut_A_Dynamic);
  15020. IR::Instr* saveThisArgOutInstr = argInstr;
  15021. saveThisArgOutInstr->Unlink();
  15022. saveThisArgOutInstr->FreeDst();
  15023. argLinkOpnd = argInstr->UnlinkSrc2()->AsSymOpnd();
  15024. argLinkSym = argLinkOpnd->m_sym->AsStackSym();
  15025. AssertMsg(argLinkSym->IsArgSlotSym() && argLinkSym->m_isSingleDef, "Arg tree not single def...");
  15026. argLinkOpnd->Free(this->m_func);
  15027. argInstr = argLinkSym->m_instrDef;
  15028. Assert(argInstr->m_opcode == Js::OpCode::ArgOut_A_FromStackArgs);
  15029. IR::Opnd* argsLength = m_lowererMD.GenerateArgOutForStackArgs(callInstr, argInstr);
  15030. IR::RegOpnd* startCallDstOpnd = argInstr->UnlinkSrc2()->AsRegOpnd();
  15031. argLinkSym = startCallDstOpnd->m_sym->AsStackSym();
  15032. startCallDstOpnd->Free(this->m_func);
  15033. argInstr->Remove();// Remove ArgOut_A_FromStackArgs
  15034. argInstr = argLinkSym->m_instrDef;
  15035. Assert(argInstr->m_opcode == Js::OpCode::StartCall);
  15036. insertBeforeInstrForCFG = argInstr->GetNextRealInstr();
  15037. argInstr->Remove(); //Remove start call
  15038. return m_lowererMD.LowerCallIDynamic(callInstr, saveThisArgOutInstr, argsLength, callFlags, insertBeforeInstrForCFG);
  15039. }
  15040. //This is only for x64 & ARM.
  15041. IR::Opnd*
  15042. Lowerer::GenerateArgOutForStackArgs(IR::Instr* callInstr, IR::Instr* stackArgsInstr)
  15043. {
  15044. // s25.var = LdLen_A s4.var
  15045. // s26.var = Ld_A s25.var
  15046. // BrNeq_I4 $L3, s25.var,0
  15047. // $L2:
  15048. // BrNeq_I4 $L4, s25.var,1
  15049. // s25.var = SUB_I4 s25.var, 0x1
  15050. // s10.var = LdElemI_A [s4.var+s25.var].var
  15051. // ArgOut_A_Dynamic s10.var, s25.var
  15052. // Br $L2
  15053. // $L4:
  15054. // s10.var = LdElemI_A [s4.var].var
  15055. // ArgOut_A_Dynamic s10.var, 4
  15056. // $L3
  15057. #if defined(_M_IX86)
  15058. Assert(false);
  15059. #endif
  15060. Assert(stackArgsInstr->m_opcode == Js::OpCode::ArgOut_A_FromStackArgs);
  15061. Assert(callInstr->m_opcode == Js::OpCode::CallIDynamic);
  15062. this->m_lowererMD.GenerateFunctionObjectTest(callInstr, callInstr->GetSrc1()->AsRegOpnd(), false);
  15063. if (callInstr->m_func->IsInlinee())
  15064. {
  15065. return this->GenerateArgOutForInlineeStackArgs(callInstr, stackArgsInstr);
  15066. }
  15067. Func *func = callInstr->m_func;
  15068. IR::RegOpnd* stackArgs = stackArgsInstr->GetSrc1()->AsRegOpnd();
  15069. IR::RegOpnd* ldLenDstOpnd = IR::RegOpnd::New(TyUint32, func);
  15070. IR::Instr* ldLen = IR::Instr::New(Js::OpCode::LdLen_A, ldLenDstOpnd ,stackArgs, func);
  15071. ldLenDstOpnd->SetValueType(ValueType::GetTaggedInt()); /*LdLen_A works only on stack arguments*/
  15072. callInstr->InsertBefore(ldLen);
  15073. GenerateFastRealStackArgumentsLdLen(ldLen);
  15074. IR::Instr* saveLenInstr = IR::Instr::New(Js::OpCode::MOV, IR::RegOpnd::New(TyUint32, func), ldLenDstOpnd, func);
  15075. saveLenInstr->GetDst()->SetValueType(ValueType::GetTaggedInt());
  15076. callInstr->InsertBefore(saveLenInstr);
  15077. IR::LabelInstr* doneArgs = IR::LabelInstr::New(Js::OpCode::Label, func);
  15078. IR::Instr* branchDoneArgs = IR::BranchInstr::New(Js::OpCode::BrEq_I4, doneArgs, ldLenDstOpnd, IR::IntConstOpnd::New(0, TyInt8, func),func);
  15079. callInstr->InsertBefore(branchDoneArgs);
  15080. this->m_lowererMD.EmitInt4Instr(branchDoneArgs);
  15081. IR::LabelInstr* startLoop = IR::LabelInstr::New(Js::OpCode::Label, func);
  15082. IR::LabelInstr* endLoop = IR::LabelInstr::New(Js::OpCode::Label, func);
  15083. startLoop->m_isLoopTop = true;
  15084. Loop *loop = JitAnew(func->m_alloc, Loop, func->m_alloc, this->m_func);
  15085. startLoop->SetLoop(loop);
  15086. loop->SetLoopTopInstr(startLoop);
  15087. loop->regAlloc.liveOnBackEdgeSyms = AllocatorNew(JitArenaAllocator, func->m_alloc, BVSparse<JitArenaAllocator>, func->m_alloc);
  15088. callInstr->InsertBefore(startLoop);
  15089. IR::Instr* branchOutOfLoop = IR::BranchInstr::New(Js::OpCode::BrEq_I4, endLoop, ldLenDstOpnd, IR::IntConstOpnd::New(1, TyInt8, func),func);
  15090. callInstr->InsertBefore(branchOutOfLoop);
  15091. this->m_lowererMD.EmitInt4Instr(branchOutOfLoop);
  15092. IR::Instr* subInstr = IR::Instr::New(Js::OpCode::Sub_I4, ldLenDstOpnd, ldLenDstOpnd, IR::IntConstOpnd::New(1, TyInt8, func),func);
  15093. callInstr->InsertBefore(subInstr);
  15094. this->m_lowererMD.EmitInt4Instr(subInstr);
  15095. IR::IndirOpnd *nthArgument = IR::IndirOpnd::New(stackArgs, ldLenDstOpnd, TyMachReg, func);
  15096. IR::RegOpnd* ldElemDstOpnd = IR::RegOpnd::New(TyMachReg,func);
  15097. IR::Instr* ldElem = IR::Instr::New(Js::OpCode::LdElemI_A, ldElemDstOpnd, nthArgument, func);
  15098. callInstr->InsertBefore(ldElem);
  15099. GenerateFastStackArgumentsLdElemI(ldElem);
  15100. IR::Instr* argout = IR::Instr::New(Js::OpCode::ArgOut_A_Dynamic, func);
  15101. argout->SetSrc1(ldElemDstOpnd);
  15102. argout->SetSrc2(ldLenDstOpnd);
  15103. callInstr->InsertBefore(argout);
  15104. this->m_lowererMD.LoadDynamicArgumentUsingLength(argout);
  15105. IR::BranchInstr *tailBranch = IR::BranchInstr::New(Js::OpCode::Br, startLoop, func);
  15106. callInstr->InsertBefore(tailBranch);
  15107. callInstr->InsertBefore(endLoop);
  15108. this->m_lowererMD.LowerUncondBranch(tailBranch);
  15109. loop->regAlloc.liveOnBackEdgeSyms->Set(ldLenDstOpnd->m_sym->m_id);
  15110. subInstr = IR::Instr::New(Js::OpCode::Sub_I4, ldLenDstOpnd, ldLenDstOpnd, IR::IntConstOpnd::New(1, TyInt8, func),func);
  15111. callInstr->InsertBefore(subInstr);
  15112. this->m_lowererMD.EmitInt4Instr(subInstr);
  15113. nthArgument = IR::IndirOpnd::New(stackArgs, ldLenDstOpnd, TyMachReg, func);
  15114. ldElemDstOpnd = IR::RegOpnd::New(TyMachReg,func);
  15115. ldElem = IR::Instr::New(Js::OpCode::LdElemI_A, ldElemDstOpnd, nthArgument, func);
  15116. callInstr->InsertBefore(ldElem);
  15117. GenerateFastStackArgumentsLdElemI(ldElem);
  15118. argout = IR::Instr::New(Js::OpCode::ArgOut_A_Dynamic, func);
  15119. argout->SetSrc1(ldElemDstOpnd);
  15120. callInstr->InsertBefore(argout);
  15121. this->m_lowererMD.LoadDynamicArgument(argout, 4); //4 to denote this is 4th register after this, callinfo & function object
  15122. callInstr->InsertBefore(doneArgs);
  15123. /*return the length which will be used for callInfo generations & stack allocation*/
  15124. return saveLenInstr->GetDst()->AsRegOpnd();
  15125. }
  15126. //This function assumes there is stackargs bailout and index is always on the range.
  15127. bool
  15128. Lowerer::GenerateFastStackArgumentsLdElemI(IR::Instr* ldElem)
  15129. {
  15130. // MOV dst, ebp [(valueOpnd + 5) *4] // 5 for the stack layout
  15131. //
  15132. IR::IndirOpnd *indirOpnd = ldElem->GetSrc1()->AsIndirOpnd();
  15133. // Now load the index and check if it is an integer.
  15134. IR::RegOpnd *indexOpnd = indirOpnd->GetIndexOpnd();
  15135. Assert (indexOpnd && indexOpnd->IsTaggedInt());
  15136. if(ldElem->m_func->IsInlinee())
  15137. {
  15138. IR::IndirOpnd *argIndirOpnd = GetArgsIndirOpndForInlinee(ldElem, indexOpnd);
  15139. LowererMD::CreateAssign(ldElem->GetDst(), argIndirOpnd, ldElem);
  15140. }
  15141. else
  15142. {
  15143. // Load argument set dst = [ebp + index].
  15144. IR::RegOpnd *ebpOpnd = IR::Opnd::CreateFramePointerOpnd(m_func);
  15145. IR::IndirOpnd *argIndirOpnd = nullptr;
  15146. // The stack looks like this:
  15147. // ...
  15148. // arguments[1]
  15149. // arguments[0]
  15150. // this
  15151. // callinfo
  15152. // function object
  15153. // return addr
  15154. // EBP-> EBP chain
  15155. //actual arguments offset is LowererMD::GetFormalParamOffset() + 1 (this)
  15156. int32 actualOffset = GetFormalParamOffset() + 1 + indirOpnd->GetOffset();
  15157. Assert(GetFormalParamOffset() + 1 == 5);
  15158. const BYTE indirScale = this->m_lowererMD.GetDefaultIndirScale();
  15159. argIndirOpnd = IR::IndirOpnd::New(ebpOpnd->AsRegOpnd(), indexOpnd->AsRegOpnd(), indirScale, TyMachReg, this->m_func);
  15160. // Need to offset valueOpnd by 5. Instead of changing valueOpnd, we can just add an offset to the indir. Changing
  15161. // valueOpnd requires creation of a temp sym (if it's not already a temp) so that the value of the sym that
  15162. // valueOpnd represents is not changed.
  15163. argIndirOpnd->SetOffset(actualOffset << indirScale);
  15164. LowererMD::CreateAssign(ldElem->GetDst(), argIndirOpnd, ldElem);
  15165. }
  15166. ldElem->Remove();
  15167. return false;
  15168. }
  15169. IR::IndirOpnd*
  15170. Lowerer::GetArgsIndirOpndForInlinee(IR::Instr* ldElem, IR::Opnd* valueOpnd)
  15171. {
  15172. Assert(ldElem->m_func->IsInlinee());
  15173. IR::IndirOpnd* argIndirOpnd = nullptr;
  15174. // Address of argument after 'this'
  15175. const auto firstRealArgStackSym = ldElem->m_func->GetInlineeArgvSlotOpnd()->m_sym->AsStackSym();
  15176. this->m_func->SetArgOffset(firstRealArgStackSym, firstRealArgStackSym->m_offset + MachPtr); //Start after this pointer
  15177. IR::SymOpnd *firstArg = IR::SymOpnd::New(firstRealArgStackSym, TyMachPtr, ldElem->m_func);
  15178. const IR::AutoReuseOpnd autoReuseFirstArg(firstArg, m_func);
  15179. IR::RegOpnd *const baseOpnd = IR::RegOpnd::New(TyMachReg, ldElem->m_func);
  15180. const IR::AutoReuseOpnd autoReuseBaseOpnd(baseOpnd, m_func);
  15181. InsertLea(baseOpnd, firstArg, ldElem);
  15182. if (valueOpnd->IsIntConstOpnd())
  15183. {
  15184. IntConstType offset = valueOpnd->AsIntConstOpnd()->GetValue() * MachPtr;
  15185. // TODO: Assert(Math::FitsInDWord(offset));
  15186. argIndirOpnd = IR::IndirOpnd::New(baseOpnd, (int32)offset, TyMachReg, ldElem->m_func);
  15187. }
  15188. else
  15189. {
  15190. Assert(valueOpnd->IsRegOpnd());
  15191. const BYTE indirScale = this->m_lowererMD.GetDefaultIndirScale();
  15192. argIndirOpnd = IR::IndirOpnd::New(baseOpnd, valueOpnd->AsRegOpnd(), indirScale, TyMachReg, ldElem->m_func);
  15193. }
  15194. return argIndirOpnd;
  15195. }
  15196. IR::IndirOpnd*
  15197. Lowerer::GetArgsIndirOpndForTopFunction(IR::Instr* ldElem, IR::Opnd* valueOpnd)
  15198. {
  15199. // Load argument set dst = [ebp + index] (or grab from the generator object if m_func is a generator function).
  15200. IR::RegOpnd *baseOpnd = m_func->GetJnFunction()->IsGenerator() ? LoadGeneratorArgsPtr(ldElem) : IR::Opnd::CreateFramePointerOpnd(m_func);
  15201. IR::IndirOpnd* argIndirOpnd = nullptr;
  15202. // The stack looks like this:
  15203. // ...
  15204. // arguments[1]
  15205. // arguments[0]
  15206. // this
  15207. // callinfo
  15208. // function object
  15209. // return addr
  15210. // EBP-> EBP chain
  15211. //actual arguments offset is LowererMD::GetFormalParamOffset() + 1 (this)
  15212. uint16 actualOffset = m_func->GetJnFunction()->IsGenerator() ? 1 : GetFormalParamOffset() + 1; //5
  15213. Assert(actualOffset == 5 || m_func->GetJnFunction()->IsGenerator());
  15214. if (valueOpnd->IsIntConstOpnd())
  15215. {
  15216. IntConstType offset = (valueOpnd->AsIntConstOpnd()->GetValue() + actualOffset) * MachPtr;
  15217. // TODO: Assert(Math::FitsInDWord(offset));
  15218. argIndirOpnd = IR::IndirOpnd::New(baseOpnd, (int32)offset, TyMachReg, this->m_func);
  15219. }
  15220. else
  15221. {
  15222. const BYTE indirScale = this->m_lowererMD.GetDefaultIndirScale();
  15223. argIndirOpnd = IR::IndirOpnd::New(baseOpnd->AsRegOpnd(), valueOpnd->AsRegOpnd(), indirScale, TyMachReg, this->m_func);
  15224. // Need to offset valueOpnd by 5. Instead of changing valueOpnd, we can just add an offset to the indir. Changing
  15225. // valueOpnd requires creation of a temp sym (if it's not already a temp) so that the value of the sym that
  15226. // valueOpnd represents is not changed.
  15227. argIndirOpnd->SetOffset(actualOffset << indirScale);
  15228. }
  15229. return argIndirOpnd;
  15230. }
  15231. void
  15232. Lowerer::GenerateCheckForArgumentsLength(IR::Instr* ldElem, IR::LabelInstr* labelCreateHeapArgs, IR::Opnd* actualParamOpnd, IR::Opnd* valueOpnd, Js::OpCode opcode)
  15233. {
  15234. // Check if index < nr_actuals.
  15235. InsertCompare(actualParamOpnd, valueOpnd, ldElem);
  15236. // Jump to helper if index >= nr_actuals.
  15237. // Do an unsigned check here so that a negative index will also fail.
  15238. // (GenerateLdValueFromCheckedIndexOpnd does not guarantee positive index on x86.)
  15239. InsertBranch(opcode, true, labelCreateHeapArgs, ldElem);
  15240. }
  15241. bool
  15242. Lowerer::GenerateFastArgumentsLdElemI(IR::Instr* ldElem, IR::LabelInstr * labelHelper, IR::LabelInstr *labelFallThru)
  15243. {
  15244. // TEST argsSlot, argsSlot
  15245. // JNE $helper // There is an arguments object created jump to helper.
  15246. // ---GenerateSmIntTest
  15247. // ---GenerateLdValueFromCheckedIndexOpnd
  15248. // ---LoadInputParamCount
  15249. // CMP actualParamOpnd, valueOpnd //Compare between the actual count & the index count (say i in arguments[i])
  15250. // JLE $labelCreateHeapArgs
  15251. // MOV dst, ebp [(valueOpnd + 5) *4] // 5 for the stack layout
  15252. // JMP $fallthrough
  15253. //
  15254. //labelCreateHeapArgs:
  15255. // ---LoadHeapArguments
  15256. Assert(ldElem->DoStackArgsOpt(this->m_func));
  15257. IR::IndirOpnd *indirOpnd = ldElem->GetSrc1()->AsIndirOpnd();
  15258. bool isInlinee = ldElem->m_func->IsInlinee();
  15259. Func *func = ldElem->m_func;
  15260. // First check the slot on the frame to see if there is a heap arguments object.
  15261. IR::Opnd *cachedArgsObjectSlotOpnd = isInlinee? ldElem->m_func->GetInlineeArgumentsObjectSlotOpnd() : this->m_lowererMD.CreateStackArgumentsSlotOpnd() ;
  15262. // Re-use the base pointer here so that we're loading the current heap args into the reg we will pass
  15263. // to the helper if necessary.
  15264. IR::RegOpnd *argsObjRegOpnd = indirOpnd->GetBaseOpnd();
  15265. LowererMD::CreateAssign(argsObjRegOpnd, cachedArgsObjectSlotOpnd, ldElem);
  15266. InsertTest(argsObjRegOpnd, argsObjRegOpnd, ldElem);
  15267. IR::LabelInstr *labelCreateHeapArgs = IR::LabelInstr::New(Js::OpCode::Label, func, true);
  15268. InsertBranch(Js::OpCode::BrNeq_A, labelHelper, ldElem);
  15269. // Now load the index and check if it is an integer.
  15270. bool emittedFastPath = false;
  15271. bool isNotInt = false;
  15272. IntConstType value = 0;
  15273. IR::RegOpnd *indexOpnd = indirOpnd->GetIndexOpnd();
  15274. IR::Opnd *valueOpnd = nullptr;
  15275. IR::Opnd *actualParamOpnd = nullptr;
  15276. bool hasIntConstIndex = indirOpnd->TryGetIntConstIndexValue(true, &value, &isNotInt);
  15277. if (isInlinee && hasIntConstIndex && value >= (ldElem->m_func->actualCount - 1))
  15278. {
  15279. //Outside the range of actuals, skip
  15280. }
  15281. else if (labelFallThru != nullptr && !(hasIntConstIndex && value < 0)) //if index is not a negative int constant
  15282. {
  15283. if (isInlinee)
  15284. {
  15285. actualParamOpnd = IR::IntConstOpnd::New(ldElem->m_func->actualCount - 1, TyInt32, func);
  15286. }
  15287. else
  15288. {
  15289. // Load actuals count, LoadHeapArguments will reuse the generated instructions here
  15290. IR::Instr *loadInputParamCountInstr = this->m_lowererMD.LoadInputParamCount(ldElem, -1 /* don't include 'this' while counting actuals. */);
  15291. actualParamOpnd = loadInputParamCountInstr->GetDst()->AsRegOpnd();
  15292. }
  15293. if (hasIntConstIndex)
  15294. {
  15295. //Constant index
  15296. valueOpnd = IR::IntConstOpnd::New(value, TyInt32, func);
  15297. }
  15298. else
  15299. {
  15300. //Load valueOpnd from the index
  15301. valueOpnd =
  15302. m_lowererMD.LoadNonnegativeIndex(
  15303. indexOpnd,
  15304. (
  15305. #if INT32VAR
  15306. indexOpnd->GetType() == TyUint32
  15307. #else
  15308. // On 32-bit platforms, skip the negative check since for now, the unsigned upper bound check covers it
  15309. true
  15310. #endif
  15311. ),
  15312. labelCreateHeapArgs,
  15313. labelCreateHeapArgs,
  15314. ldElem);
  15315. }
  15316. if (isInlinee)
  15317. {
  15318. if (!hasIntConstIndex)
  15319. {
  15320. //Runtime check if to make sure length is within the arguments.length range.
  15321. GenerateCheckForArgumentsLength(ldElem, labelCreateHeapArgs, valueOpnd, actualParamOpnd, Js::OpCode::BrGe_A);
  15322. }
  15323. }
  15324. else
  15325. {
  15326. GenerateCheckForArgumentsLength(ldElem, labelCreateHeapArgs, actualParamOpnd, valueOpnd, Js::OpCode::BrLe_A);
  15327. }
  15328. IR::Opnd *argIndirOpnd = nullptr;
  15329. if (isInlinee)
  15330. {
  15331. argIndirOpnd = GetArgsIndirOpndForInlinee(ldElem, valueOpnd);
  15332. }
  15333. else
  15334. {
  15335. argIndirOpnd = GetArgsIndirOpndForTopFunction(ldElem, valueOpnd);
  15336. }
  15337. LowererMD::CreateAssign(ldElem->GetDst(), argIndirOpnd, ldElem);
  15338. // JMP $done
  15339. InsertBranch(Js::OpCode::Br, labelFallThru, ldElem);
  15340. // $labelCreateHeapArgs:
  15341. ldElem->InsertBefore(labelCreateHeapArgs);
  15342. emittedFastPath = true;
  15343. }
  15344. IR::Opnd *nullOpnd = this->LoadLibraryValueOpnd(ldElem, LibraryValue::ValueNull);
  15345. IR::Instr *instrArgs = IR::Instr::New(Js::OpCode::LdHeapArguments,
  15346. indirOpnd->GetBaseOpnd(),
  15347. nullOpnd,
  15348. nullOpnd,
  15349. func);
  15350. ldElem->InsertBefore(instrArgs);
  15351. this->m_lowererMD.LoadHeapArguments(instrArgs, true, actualParamOpnd);
  15352. return emittedFastPath;
  15353. }
  15354. bool
  15355. Lowerer::GenerateFastRealStackArgumentsLdLen(IR::Instr *ldLen)
  15356. {
  15357. if(ldLen->m_func->IsInlinee())
  15358. {
  15359. //Get the length of the arguments
  15360. LowererMD::CreateAssign(ldLen->GetDst(),
  15361. IR::IntConstOpnd::New(ldLen->m_func->actualCount - 1, TyUint32, ldLen->m_func),
  15362. ldLen);
  15363. }
  15364. else
  15365. {
  15366. IR::Instr *loadInputParamCountInstr = this->m_lowererMD.LoadInputParamCount(ldLen, -1);
  15367. IR::RegOpnd *actualCountOpnd = loadInputParamCountInstr->GetDst()->AsRegOpnd();
  15368. LowererMD::CreateAssign(ldLen->GetDst(), actualCountOpnd, ldLen);
  15369. }
  15370. ldLen->Remove();
  15371. return false;
  15372. }
  15373. bool
  15374. Lowerer::GenerateFastArgumentsLdLen(IR::Instr *ldLen, IR::LabelInstr* labelHelper, IR::LabelInstr* labelFallThru)
  15375. {
  15376. // TEST argslot, argslot //Test if the arguments slot is zero
  15377. // JNE $helper
  15378. // actualCountOpnd <-LoadInputParamCount fastpath
  15379. // SHL actualCountOpnd, actualCountOpnd, 1 // Left shift for tagging
  15380. // INC actualCountOpnd // Tagging
  15381. // MOV dst, actualCountOpnd
  15382. // JMP $fallthrough
  15383. //$helper:
  15384. Assert(ldLen->DoStackArgsOpt(this->m_func));
  15385. if(ldLen->m_func->IsInlinee())
  15386. {
  15387. IR::Opnd *cachedArgsObjectSlotOpnd = ldLen->m_func->GetInlineeArgumentsObjectSlotOpnd();
  15388. // Re-use the LdLen_A source here so that we're loading the current heap args into the reg we will pass
  15389. // to the helper if necessary.
  15390. IR::RegOpnd *argsObjectRegOpnd = ldLen->GetSrc1()->AsRegOpnd();
  15391. LowererMD::CreateAssign(argsObjectRegOpnd, cachedArgsObjectSlotOpnd, ldLen);
  15392. InsertTest(argsObjectRegOpnd, argsObjectRegOpnd, ldLen);
  15393. InsertBranch(Js::OpCode::BrNeq_A, labelHelper, ldLen);
  15394. //Get the length of the arguments
  15395. LowererMD::CreateAssign(ldLen->GetDst(),
  15396. IR::AddrOpnd::New(Js::TaggedInt::ToVarUnchecked(ldLen->m_func->actualCount - 1), IR::AddrOpndKindConstantVar, ldLen->m_func), // -1 to exclude this pointer
  15397. ldLen);
  15398. }
  15399. else
  15400. {
  15401. IR::Opnd *cachedArgsObjectSlotOpnd = this->m_lowererMD.CreateStackArgumentsSlotOpnd();
  15402. // Re-use the LdLen_A source here so that we're loading the current heap args into the reg we will pass
  15403. // to the helper if necessary.
  15404. IR::RegOpnd *argsObjectRegOpnd = ldLen->GetSrc1()->AsRegOpnd();
  15405. LowererMD::CreateAssign(argsObjectRegOpnd, cachedArgsObjectSlotOpnd, ldLen);
  15406. InsertTest(argsObjectRegOpnd, argsObjectRegOpnd, ldLen);
  15407. InsertBranch(Js::OpCode::BrNeq_A, labelHelper, ldLen);
  15408. IR::Instr *loadInputParamCountInstr = this->m_lowererMD.LoadInputParamCount(ldLen, -1);
  15409. IR::RegOpnd *actualCountOpnd = loadInputParamCountInstr->GetDst()->AsRegOpnd();
  15410. this->m_lowererMD.GenerateInt32ToVarConversion(actualCountOpnd, ldLen);
  15411. LowererMD::CreateAssign(ldLen->GetDst(), actualCountOpnd, ldLen);
  15412. }
  15413. InsertBranch(Js::OpCode::Br, labelFallThru, ldLen);
  15414. return true;
  15415. }
  15416. IR::RegOpnd*
  15417. Lowerer::GenerateFunctionTypeFromFixedFunctionObject(IR::Instr *insertInstrPt, IR::Opnd* functionObjOpnd)
  15418. {
  15419. IR::RegOpnd * functionTypeRegOpnd = IR::RegOpnd::New(TyMachReg, this->m_func);
  15420. IR::Opnd *functionTypeOpnd = nullptr;
  15421. if(functionObjOpnd->IsAddrOpnd())
  15422. {
  15423. IR::AddrOpnd* functionObjAddrOpnd = functionObjOpnd->AsAddrOpnd();
  15424. // functionTypeRegOpnd = MOV [fixed function address + type offset]
  15425. functionObjAddrOpnd->m_address;
  15426. functionTypeOpnd = IR::MemRefOpnd::New((void *)((intptr)functionObjAddrOpnd->m_address + Js::RecyclableObject::GetOffsetOfType()), TyMachPtr, this->m_func,
  15427. IR::AddrOpndKindDynamicObjectTypeRef);
  15428. }
  15429. else
  15430. {
  15431. functionTypeOpnd = IR::IndirOpnd::New(functionObjOpnd->AsRegOpnd(), Js::RecyclableObject::GetOffsetOfType(), TyMachPtr, this->m_func);
  15432. }
  15433. LowererMD::CreateAssign(functionTypeRegOpnd, functionTypeOpnd, insertInstrPt);
  15434. return functionTypeRegOpnd;
  15435. }
  15436. void
  15437. Lowerer::FinalLower()
  15438. {
  15439. this->m_lowererMD.FinalLower();
  15440. // ensure that the StartLabel and EndLabel are inserted
  15441. // before the prolog and after the epilog respectively
  15442. IR::LabelInstr * startLabel = m_func->GetFuncStartLabel();
  15443. if (startLabel != nullptr)
  15444. {
  15445. m_func->m_headInstr->InsertAfter(startLabel);
  15446. }
  15447. IR::LabelInstr * endLabel = m_func->GetFuncEndLabel();
  15448. if (endLabel != nullptr)
  15449. {
  15450. m_func->m_tailInstr->GetPrevRealInstr()->InsertBefore(endLabel);
  15451. }
  15452. }
  15453. void
  15454. Lowerer::EHBailoutPatchUp()
  15455. {
  15456. Assert(this->m_func->isPostLayout);
  15457. // 1. Insert return thunks for all the regions.
  15458. // 2. Set the hasBailedOut bit to true on all bailout paths in EH regions.
  15459. // 3. Insert code after every bailout in a try or catch region to save the return value on the stack, and jump to the return thunk (See Region.h) of that region.
  15460. // 4. Insert code right before the epilog, to restore the return value (saved in 2.) from a bailout into eax.
  15461. IR::LabelInstr * restoreReturnValueFromBailoutLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  15462. IR::LabelInstr * epilogLabel;
  15463. IR::Instr * exitPrevInstr = this->m_func->m_exitInstr->GetPrevRealInstrOrLabel();
  15464. if (exitPrevInstr->IsLabelInstr())
  15465. {
  15466. epilogLabel = exitPrevInstr->AsLabelInstr();
  15467. }
  15468. else
  15469. {
  15470. epilogLabel = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  15471. this->m_func->m_exitInstr->InsertBefore(epilogLabel);
  15472. }
  15473. IR::Instr * tmpInstr = nullptr;
  15474. bool restoreReturnFromBailoutEmitted = false;
  15475. FOREACH_INSTR_IN_FUNC_EDITING(instr, instrNext, this->m_func)
  15476. {
  15477. if (instr->IsLabelInstr())
  15478. {
  15479. this->currentRegion = instr->AsLabelInstr()->GetRegion();
  15480. }
  15481. // Consider (radua): Assert(this->currentRegion) here?
  15482. if (this->currentRegion)
  15483. {
  15484. RegionType currentRegionType = this->currentRegion->GetType();
  15485. if (currentRegionType == RegionTypeTry || currentRegionType == RegionTypeCatch)
  15486. {
  15487. this->InsertReturnThunkForRegion(this->currentRegion, restoreReturnValueFromBailoutLabel);
  15488. if (instr->HasBailOutInfo())
  15489. {
  15490. this->SetHasBailedOut(instr);
  15491. tmpInstr = this->EmitEHBailoutStackRestore(instr);
  15492. this->EmitSaveEHBailoutReturnValueAndJumpToRetThunk(tmpInstr);
  15493. if (!restoreReturnFromBailoutEmitted)
  15494. {
  15495. this->EmitRestoreReturnValueFromEHBailout(restoreReturnValueFromBailoutLabel, epilogLabel);
  15496. restoreReturnFromBailoutEmitted = true;
  15497. }
  15498. }
  15499. }
  15500. }
  15501. }
  15502. NEXT_INSTR_IN_FUNC_EDITING
  15503. }
  15504. bool
  15505. Lowerer::GenerateFastLdFld(IR::Instr * const instrLdFld, IR::JnHelperMethod helperMethod, IR::JnHelperMethod polymorphicHelperMethod,
  15506. IR::LabelInstr ** labelBailOut, IR::RegOpnd* typeOpnd, bool* pIsHelper, IR::LabelInstr** pLabelHelper)
  15507. {
  15508. // Generates:
  15509. //
  15510. // r1 = object->type
  15511. // if (r1 is taggedInt) goto helper
  15512. // Load inline cache
  15513. // if monomorphic
  15514. // r2 = address of the monomorphic inline cache
  15515. // if polymorphic
  15516. // r2 = address of the polymorphic inline cache array
  15517. // r3 = (type >> PIC shift amount) & (PIC size - 1)
  15518. // r2 = r2 + r3
  15519. // Try load property using proto cache (if protoFirst)
  15520. // Try load property using local cache
  15521. // Try loading property using proto cache (if !protoFirst)
  15522. // Try loading property using flags cache
  15523. //
  15524. // Loading property using local cache:
  15525. // if (r1 == r2->u.local.type)
  15526. // result = load inline slot r2->u.local.slotIndex from r1
  15527. // goto fallthru
  15528. // if ((r1 | InlineCacheAuxSlotTypeTag) == r2->u.local.type)
  15529. // result = load aux slot r2->u.local.slotIndex from r1
  15530. // goto fallthru
  15531. //
  15532. // Loading property using proto cache:
  15533. // if (r1 == r2->u.proto.type)
  15534. // r3 = r2->u.proto.prototypeObject
  15535. // result = load inline slot r2->u.proto.slotIndex from r3
  15536. // goto fallthru
  15537. // if (r1 | InlineCacheAuxSlotTypeTag) == r2.u.proto.type)
  15538. // r3 = r2->u.proto.prototypeObject
  15539. // result = load aux slot r2->u.proto.slotIndex from r3
  15540. // goto fallthru
  15541. //
  15542. // Loading property using flags cache:
  15543. // if (r2->u.accessor.flags & (Js::InlineCacheGetterFlag | Js::InlineCacheSetterFlag) == 0)
  15544. // if (r1 == r2->u.accessor.type)
  15545. // result = load inline slot r2->u.accessor.slotIndex from r1
  15546. // goto fallthru
  15547. // if ((r1 | InlineCacheAuxSlotTypeTag) == r2->u.accessor.type)
  15548. // result = load aux slot r2->u.accessor.slotIndex from r1
  15549. // goto fallthru
  15550. //
  15551. // Loading an inline slot:
  15552. // result = [r1 + slotIndex * sizeof(Var)]
  15553. //
  15554. // Loading an aux slot:
  15555. // slotArray = r1->auxSlots
  15556. // result = [slotArray + slotIndex * sizeof(Var)]
  15557. //
  15558. // We only emit the code block for a type of cache (local/proto/flags) if the profile data
  15559. // indicates that type of cache was used to load the property in the past.
  15560. // We don't emit the type check with aux slot tag if the profile data indicates that we didn't
  15561. // load the property from an aux slot before.
  15562. // We don't emit the type check without an aux slot tag if the profile data indicates that we didn't
  15563. // load the property from an inline slot before.
  15564. IR::Opnd * opndSrc = instrLdFld->GetSrc1();
  15565. AssertMsg(opndSrc->IsSymOpnd() && opndSrc->AsSymOpnd()->IsPropertySymOpnd() && opndSrc->AsSymOpnd()->m_sym->IsPropertySym(), "Expected PropertySym as src of LdFld");
  15566. Assert(!instrLdFld->DoStackArgsOpt(this->m_func));
  15567. IR::PropertySymOpnd * propertySymOpnd = opndSrc->AsPropertySymOpnd();
  15568. PropertySym * propertySym = propertySymOpnd->m_sym->AsPropertySym();
  15569. PHASE_PRINT_TESTTRACE(
  15570. Js::ObjTypeSpecPhase,
  15571. this->m_func,
  15572. L"Field load: %s, property: %s, func: %s, cache ID: %d, cloned cache: false\n",
  15573. Js::OpCodeUtil::GetOpCodeName(instrLdFld->m_opcode),
  15574. this->m_func->GetScriptContext()->GetPropertyNameLocked(propertySym->m_propertyId)->GetBuffer(),
  15575. this->m_func->GetJnFunction()->GetDisplayName(),
  15576. propertySymOpnd->m_inlineCacheIndex);
  15577. Assert(pIsHelper != nullptr);
  15578. bool& isHelper = *pIsHelper;
  15579. Assert(pLabelHelper != nullptr);
  15580. IR::LabelInstr*& labelHelper = *pLabelHelper;
  15581. bool doLocal = true;
  15582. bool doProto = instrLdFld->m_opcode == Js::OpCode::LdMethodFld
  15583. || instrLdFld->m_opcode == Js::OpCode::LdRootMethodFld
  15584. || instrLdFld->m_opcode == Js::OpCode::ScopedLdMethodFld;
  15585. bool doProtoFirst = doProto;
  15586. bool doInlineSlots = true;
  15587. bool doAuxSlots = true;
  15588. if (!PHASE_OFF(Js::ProfileBasedFldFastPathPhase, this->m_func) && instrLdFld->IsProfiledInstr())
  15589. {
  15590. IR::ProfiledInstr * profiledInstrLdFld = instrLdFld->AsProfiledInstr();
  15591. if (profiledInstrLdFld->u.FldInfo().flags != Js::FldInfo_NoInfo)
  15592. {
  15593. doProto = !!(profiledInstrLdFld->u.FldInfo().flags & Js::FldInfo_FromProto);
  15594. doLocal = !!(profiledInstrLdFld->u.FldInfo().flags & Js::FldInfo_FromLocal);
  15595. if ((profiledInstrLdFld->u.FldInfo().flags & (Js::FldInfo_FromInlineSlots | Js::FldInfo_FromAuxSlots)) == Js::FldInfo_FromInlineSlots)
  15596. {
  15597. // If the inline slots flag is set and the aux slots flag is not, only generate the inline slots check
  15598. doAuxSlots = false;
  15599. }
  15600. else if ((profiledInstrLdFld->u.FldInfo().flags & (Js::FldInfo_FromInlineSlots | Js::FldInfo_FromAuxSlots)) == Js::FldInfo_FromAuxSlots)
  15601. {
  15602. // If the aux slots flag is set and the inline slots flag is not, only generate the aux slots check
  15603. doInlineSlots = false;
  15604. }
  15605. }
  15606. else if (!profiledInstrLdFld->u.FldInfo().valueType.IsUninitialized())
  15607. {
  15608. // We have value type info about the field but no flags. This means we shouldn't generate any
  15609. // fast paths for this field load.
  15610. doLocal = false;
  15611. doProto = false;
  15612. }
  15613. }
  15614. if (!doLocal && !doProto)
  15615. {
  15616. return false;
  15617. }
  15618. IR::LabelInstr * labelFallThru = instrLdFld->GetOrCreateContinueLabel();
  15619. if (labelHelper == nullptr)
  15620. {
  15621. labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, isHelper);
  15622. }
  15623. IR::RegOpnd * opndBase = propertySymOpnd->CreatePropertyOwnerOpnd(m_func);
  15624. bool usePolymorphicInlineCache = !!propertySymOpnd->m_runtimePolymorphicInlineCache;
  15625. IR::RegOpnd * opndInlineCache = IR::RegOpnd::New(TyMachPtr, this->m_func);
  15626. if (usePolymorphicInlineCache)
  15627. {
  15628. LowererMD::CreateAssign(opndInlineCache, IR::AddrOpnd::New(propertySymOpnd->m_runtimePolymorphicInlineCache->GetInlineCaches(), IR::AddrOpndKindDynamicInlineCache, this->m_func, true), instrLdFld);
  15629. }
  15630. else
  15631. {
  15632. LowererMD::CreateAssign(opndInlineCache, this->LoadRuntimeInlineCacheOpnd(instrLdFld, propertySymOpnd, isHelper), instrLdFld);
  15633. }
  15634. if (typeOpnd == nullptr)
  15635. {
  15636. typeOpnd = IR::RegOpnd::New(TyMachPtr, this->m_func);
  15637. GenerateObjectTestAndTypeLoad(instrLdFld, opndBase, typeOpnd, labelHelper);
  15638. }
  15639. if (usePolymorphicInlineCache)
  15640. {
  15641. LowererMD::GenerateLoadPolymorphicInlineCacheSlot(instrLdFld, opndInlineCache, typeOpnd, propertySymOpnd->m_runtimePolymorphicInlineCache->GetSize());
  15642. }
  15643. IR::LabelInstr * labelNext = nullptr;
  15644. IR::Opnd * opndDst = instrLdFld->GetDst();
  15645. IR::RegOpnd * opndTaggedType = nullptr;
  15646. IR::BranchInstr * labelNextBranchToPatch = nullptr;
  15647. if (doProto && doProtoFirst)
  15648. {
  15649. if (doInlineSlots)
  15650. {
  15651. labelNext = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, isHelper);
  15652. labelNextBranchToPatch = LowererMD::GenerateProtoInlineCacheCheck(instrLdFld, typeOpnd, opndInlineCache, labelNext);
  15653. LowererMD::GenerateLdFldFromProtoInlineCache(instrLdFld, opndBase, opndDst, opndInlineCache, labelFallThru, true);
  15654. instrLdFld->InsertBefore(labelNext);
  15655. }
  15656. if (doAuxSlots)
  15657. {
  15658. if (opndTaggedType == nullptr)
  15659. {
  15660. opndTaggedType = IR::RegOpnd::New(TyMachPtr, this->m_func);
  15661. LowererMD::GenerateLoadTaggedType(instrLdFld, typeOpnd, opndTaggedType);
  15662. }
  15663. labelNext = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, isHelper);
  15664. labelNextBranchToPatch = LowererMD::GenerateProtoInlineCacheCheck(instrLdFld, opndTaggedType, opndInlineCache, labelNext);
  15665. LowererMD::GenerateLdFldFromProtoInlineCache(instrLdFld, opndBase, opndDst, opndInlineCache, labelFallThru, false);
  15666. instrLdFld->InsertBefore(labelNext);
  15667. }
  15668. }
  15669. if (doLocal)
  15670. {
  15671. if (doInlineSlots)
  15672. {
  15673. labelNext = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, isHelper);
  15674. labelNextBranchToPatch = LowererMD::GenerateLocalInlineCacheCheck(instrLdFld, typeOpnd, opndInlineCache, labelNext);
  15675. LowererMD::GenerateLdFldFromLocalInlineCache(instrLdFld, opndBase, opndDst, opndInlineCache, labelFallThru, true);
  15676. instrLdFld->InsertBefore(labelNext);
  15677. }
  15678. if (doAuxSlots)
  15679. {
  15680. if (opndTaggedType == nullptr)
  15681. {
  15682. opndTaggedType = IR::RegOpnd::New(TyMachPtr, this->m_func);
  15683. LowererMD::GenerateLoadTaggedType(instrLdFld, typeOpnd, opndTaggedType);
  15684. }
  15685. labelNext = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, isHelper);
  15686. labelNextBranchToPatch = LowererMD::GenerateLocalInlineCacheCheck(instrLdFld, opndTaggedType, opndInlineCache, labelNext);
  15687. LowererMD::GenerateLdFldFromLocalInlineCache(instrLdFld, opndBase, opndDst, opndInlineCache, labelFallThru, false);
  15688. instrLdFld->InsertBefore(labelNext);
  15689. }
  15690. }
  15691. if (doProto && !doProtoFirst)
  15692. {
  15693. if (doInlineSlots)
  15694. {
  15695. labelNext = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, isHelper);
  15696. labelNextBranchToPatch = LowererMD::GenerateProtoInlineCacheCheck(instrLdFld, typeOpnd, opndInlineCache, labelNext);
  15697. LowererMD::GenerateLdFldFromProtoInlineCache(instrLdFld, opndBase, opndDst, opndInlineCache, labelFallThru, true);
  15698. instrLdFld->InsertBefore(labelNext);
  15699. }
  15700. if (doAuxSlots)
  15701. {
  15702. if (opndTaggedType == nullptr)
  15703. {
  15704. opndTaggedType = IR::RegOpnd::New(TyMachPtr, this->m_func);
  15705. LowererMD::GenerateLoadTaggedType(instrLdFld, typeOpnd, opndTaggedType);
  15706. }
  15707. labelNext = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, isHelper);
  15708. labelNextBranchToPatch = LowererMD::GenerateProtoInlineCacheCheck(instrLdFld, opndTaggedType, opndInlineCache, labelNext);
  15709. LowererMD::GenerateLdFldFromProtoInlineCache(instrLdFld, opndBase, opndDst, opndInlineCache, labelFallThru, false);
  15710. instrLdFld->InsertBefore(labelNext);
  15711. }
  15712. }
  15713. Assert(labelNextBranchToPatch);
  15714. labelNextBranchToPatch->SetTarget(labelHelper);
  15715. labelNext->Remove();
  15716. // $helper:
  15717. // dst = CALL Helper(inlineCache, base, field, scriptContext)
  15718. // $fallthru:
  15719. isHelper = true;
  15720. // Return false to indicate the original instruction was not lowered. Caller will insert the helper label.
  15721. return false;
  15722. }
  15723. void
  15724. Lowerer::GenerateAuxSlotAdjustmentRequiredCheck(
  15725. IR::Instr * instrToInsertBefore,
  15726. IR::RegOpnd * opndInlineCache,
  15727. IR::LabelInstr * labelHelper)
  15728. {
  15729. // regSlotCap = MOV [&(inlineCache->u.local.rawUInt16)] // sized to 16 bits
  15730. IR::RegOpnd * regSlotCap = IR::RegOpnd::New(TyMachReg, instrToInsertBefore->m_func);
  15731. IR::IndirOpnd * memSlotCap = IR::IndirOpnd::New(opndInlineCache, (int32)offsetof(Js::InlineCache, u.local.rawUInt16), TyUint16, instrToInsertBefore->m_func);
  15732. InsertMove(regSlotCap, memSlotCap, instrToInsertBefore);
  15733. // SAR regSlotCap, Js::InlineCache::CacheLayoutSelectorBitCount
  15734. IR::IntConstOpnd * constSelectorBitCount = IR::IntConstOpnd::New(Js::InlineCache::CacheLayoutSelectorBitCount, TyUint16, instrToInsertBefore->m_func, /* dontEncode = */ true);
  15735. InsertShiftBranch(Js::OpCode::Shr_A, regSlotCap, regSlotCap, constSelectorBitCount, Js::OpCode::BrNeq_A, true, labelHelper, instrToInsertBefore);
  15736. }
  15737. void
  15738. Lowerer::GenerateSetObjectTypeFromInlineCache(
  15739. IR::Instr * instrToInsertBefore,
  15740. IR::RegOpnd * opndBase,
  15741. IR::RegOpnd * opndInlineCache,
  15742. bool isTypeTagged)
  15743. {
  15744. // regNewType = MOV [&(inlineCache->u.local.type)]
  15745. IR::RegOpnd * regNewType = IR::RegOpnd::New(TyMachReg, instrToInsertBefore->m_func);
  15746. IR::IndirOpnd * memNewType = IR::IndirOpnd::New(opndInlineCache, (int32)offsetof(Js::InlineCache, u.local.type), TyMachReg, instrToInsertBefore->m_func);
  15747. InsertMove(regNewType, memNewType, instrToInsertBefore);
  15748. // AND regNewType, ~InlineCacheAuxSlotTypeTag
  15749. if (isTypeTagged)
  15750. {
  15751. // On 64-bit platforms IntConstOpnd isn't big enough to hold TyMachReg values.
  15752. IR::AddrOpnd * constTypeTagComplement = IR::AddrOpnd::New((Js::Var)~InlineCacheAuxSlotTypeTag, IR::AddrOpndKindConstant, instrToInsertBefore->m_func, /* dontEncode = */ true);
  15753. InsertAnd(regNewType, regNewType, constTypeTagComplement, instrToInsertBefore);
  15754. }
  15755. // MOV base->type, regNewType
  15756. IR::IndirOpnd * memObjType = IR::IndirOpnd::New(opndBase, Js::RecyclableObject::GetOffsetOfType(), TyMachReg, instrToInsertBefore->m_func);
  15757. InsertMove(memObjType, regNewType, instrToInsertBefore);
  15758. }
  15759. bool
  15760. Lowerer::GenerateFastStFld(IR::Instr * const instrStFld, IR::JnHelperMethod helperMethod, IR::JnHelperMethod polymorphicHelperMethod, IR::LabelInstr ** labelBailOut, IR::RegOpnd* typeOpnd,
  15761. bool* pIsHelper, IR::LabelInstr** pLabelHelper, bool withPutFlags, Js::PropertyOperationFlags flags)
  15762. {
  15763. // Generates:
  15764. //
  15765. // r1 = object->type
  15766. // if (r1 is taggedInt) goto helper
  15767. // Load inline cache
  15768. // if monomorphic
  15769. // r2 = address of the monomorphic inline cache
  15770. // if polymorphic
  15771. // r2 = address of the polymorphic inline cache array
  15772. // r3 = (type >> PIC shift amount) & (PIC size - 1)
  15773. // r2 = r2 + r3
  15774. // Try store property using local cache
  15775. //
  15776. // Loading property using local cache:
  15777. // if (r1 == r2->u.local.type)
  15778. // store value to inline slot r2->u.local.slotIndex on r1
  15779. // goto fallthru
  15780. // if ((r1 | InlineCacheAuxSlotTypeTag) == r2->u.local.type)
  15781. // store value to aux slot r2->u.local.slotIndex on r1
  15782. // goto fallthru
  15783. //
  15784. // Storing to an inline slot:
  15785. // [r1 + slotIndex * sizeof(Var)] = value
  15786. //
  15787. // Storing to an aux slot:
  15788. // slotArray = r1->auxSlots
  15789. // [slotArray + slotIndex * sizeof(Var)] = value
  15790. //
  15791. // We don't emit the type check with aux slot tag if the profile data indicates that we didn't
  15792. // store the property to an aux slot before.
  15793. // We don't emit the type check without an aux slot tag if the profile data indicates that we didn't
  15794. // store the property to an inline slot before.
  15795. IR::Opnd * opndSrc = instrStFld->GetSrc1();
  15796. IR::Opnd * opndDst = instrStFld->GetDst();
  15797. AssertMsg(opndDst->IsSymOpnd() && opndDst->AsSymOpnd()->IsPropertySymOpnd() && opndDst->AsSymOpnd()->m_sym->IsPropertySym(), "Expected PropertySym as dst of StFld");
  15798. IR::PropertySymOpnd * propertySymOpnd = opndDst->AsPropertySymOpnd();
  15799. PropertySym * propertySym = propertySymOpnd->m_sym->AsPropertySym();
  15800. PHASE_PRINT_TESTTRACE(
  15801. Js::ObjTypeSpecPhase,
  15802. this->m_func,
  15803. L"Field store: %s, property: %s, func: %s, cache ID: %d, cloned cache: false\n",
  15804. Js::OpCodeUtil::GetOpCodeName(instrStFld->m_opcode),
  15805. this->m_func->GetScriptContext()->GetPropertyNameLocked(propertySym->m_propertyId)->GetBuffer(),
  15806. this->m_func->GetJnFunction()->GetDisplayName(),
  15807. propertySymOpnd->m_inlineCacheIndex);
  15808. Assert(pIsHelper != nullptr);
  15809. bool& isHelper = *pIsHelper;
  15810. Assert(pLabelHelper != nullptr);
  15811. IR::LabelInstr*& labelHelper = *pLabelHelper;
  15812. bool doStore = true;
  15813. bool doAdd = false;
  15814. bool doInlineSlots = true;
  15815. bool doAuxSlots = true;
  15816. if (!PHASE_OFF(Js::ProfileBasedFldFastPathPhase, this->m_func) && instrStFld->IsProfiledInstr())
  15817. {
  15818. IR::ProfiledInstr * profiledInstrStFld = instrStFld->AsProfiledInstr();
  15819. if (profiledInstrStFld->u.FldInfo().flags != Js::FldInfo_NoInfo)
  15820. {
  15821. if (!(profiledInstrStFld->u.FldInfo().flags & (Js::FldInfo_FromLocal | Js::FldInfo_FromLocalWithoutProperty)))
  15822. {
  15823. return false;
  15824. }
  15825. if (!PHASE_OFF(Js::AddFldFastPathPhase, this->m_func))
  15826. {
  15827. // We always try to do the store field fast path, unless the profile specifically says we never set, but always add a property here.
  15828. if ((profiledInstrStFld->u.FldInfo().flags & (Js::FldInfo_FromLocal | Js::FldInfo_FromLocalWithoutProperty)) == Js::FldInfo_FromLocalWithoutProperty)
  15829. {
  15830. doStore = false;
  15831. }
  15832. // On the other hand, we only emit the add field fast path, if the profile explicitly says we do add properties here.
  15833. if (!!(profiledInstrStFld->u.FldInfo().flags & Js::FldInfo_FromLocalWithoutProperty))
  15834. {
  15835. doAdd = true;
  15836. }
  15837. }
  15838. else
  15839. {
  15840. #if ENABLE_DEBUG_CONFIG_OPTIONS
  15841. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  15842. #endif
  15843. PHASE_PRINT_TRACE(Js::AddFldFastPathPhase, this->m_func,
  15844. L"AddFldFastPath: function: %s(%s) property: %s(#%d) no fast path, because the phase is off.\n",
  15845. this->m_func->GetJnFunction()->GetDisplayName(), this->m_func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  15846. this->m_func->GetScriptContext()->GetPropertyNameLocked(propertySym->m_propertyId)->GetBuffer(), propertySym->m_propertyId);
  15847. }
  15848. if ((profiledInstrStFld->u.FldInfo().flags & (Js::FldInfo_FromInlineSlots | Js::FldInfo_FromAuxSlots)) == Js::FldInfo_FromInlineSlots)
  15849. {
  15850. // If the inline slots flag is set and the aux slots flag is not, only generate the inline slots check
  15851. doAuxSlots = false;
  15852. }
  15853. else if ((profiledInstrStFld->u.FldInfo().flags & (Js::FldInfo_FromInlineSlots | Js::FldInfo_FromAuxSlots)) == Js::FldInfo_FromAuxSlots)
  15854. {
  15855. // If the aux slots flag is set and the inline slots flag is not, only generate the aux slots check
  15856. doInlineSlots = false;
  15857. }
  15858. }
  15859. else if (!profiledInstrStFld->u.FldInfo().valueType.IsUninitialized())
  15860. {
  15861. // We have value type info about the field but no flags. This means we shouldn't generate any
  15862. // fast paths for this field store.
  15863. return false;
  15864. }
  15865. }
  15866. Assert(doStore || doAdd);
  15867. if (labelHelper == nullptr)
  15868. {
  15869. labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  15870. }
  15871. IR::LabelInstr * labelFallThru = instrStFld->GetOrCreateContinueLabel();
  15872. IR::RegOpnd * opndBase = propertySymOpnd->CreatePropertyOwnerOpnd(m_func);
  15873. bool usePolymorphicInlineCache = !!propertySymOpnd->m_runtimePolymorphicInlineCache;
  15874. if (doAdd)
  15875. {
  15876. #if ENABLE_DEBUG_CONFIG_OPTIONS
  15877. wchar_t debugStringBuffer[MAX_FUNCTION_BODY_DEBUG_STRING_SIZE];
  15878. #endif
  15879. PHASE_PRINT_TRACE(Js::AddFldFastPathPhase, this->m_func,
  15880. L"AddFldFastPath: function: %s(%s) property: %s(#%d) %s fast path for %s.\n",
  15881. this->m_func->GetJnFunction()->GetDisplayName(), this->m_func->GetJnFunction()->GetDebugNumberSet(debugStringBuffer),
  15882. this->m_func->GetScriptContext()->GetPropertyNameLocked(propertySym->m_propertyId)->GetBuffer(), propertySym->m_propertyId,
  15883. usePolymorphicInlineCache ? L"poly" : L"mono", doStore ? L"store and add" : L"add only");
  15884. }
  15885. IR::RegOpnd * opndInlineCache = IR::RegOpnd::New(TyMachPtr, this->m_func);
  15886. if (usePolymorphicInlineCache)
  15887. {
  15888. LowererMD::CreateAssign(opndInlineCache, IR::AddrOpnd::New(propertySymOpnd->m_runtimePolymorphicInlineCache->GetInlineCaches(), IR::AddrOpndKindDynamicInlineCache, this->m_func, true), instrStFld);
  15889. }
  15890. else
  15891. {
  15892. LowererMD::CreateAssign(opndInlineCache, this->LoadRuntimeInlineCacheOpnd(instrStFld, propertySymOpnd, isHelper), instrStFld);
  15893. }
  15894. if (typeOpnd == nullptr)
  15895. {
  15896. typeOpnd = IR::RegOpnd::New(TyMachPtr, this->m_func);
  15897. GenerateObjectTestAndTypeLoad(instrStFld, opndBase, typeOpnd, labelHelper);
  15898. }
  15899. if (usePolymorphicInlineCache)
  15900. {
  15901. LowererMD::GenerateLoadPolymorphicInlineCacheSlot(instrStFld, opndInlineCache, typeOpnd, propertySymOpnd->m_runtimePolymorphicInlineCache->GetSize());
  15902. }
  15903. IR::LabelInstr * labelNext = nullptr;
  15904. IR::RegOpnd * opndTaggedType = nullptr;
  15905. IR::BranchInstr * lastBranchToNext = nullptr;
  15906. if (doStore)
  15907. {
  15908. if (doInlineSlots)
  15909. {
  15910. labelNext = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, isHelper);
  15911. lastBranchToNext = LowererMD::GenerateLocalInlineCacheCheck(instrStFld, typeOpnd, opndInlineCache, labelNext);
  15912. LowererMD::GenerateStFldFromLocalInlineCache(instrStFld, opndBase, opndSrc, opndInlineCache, labelFallThru, true);
  15913. instrStFld->InsertBefore(labelNext);
  15914. }
  15915. if (doAuxSlots)
  15916. {
  15917. if (opndTaggedType == nullptr)
  15918. {
  15919. opndTaggedType = IR::RegOpnd::New(TyMachPtr, this->m_func);
  15920. LowererMD::GenerateLoadTaggedType(instrStFld, typeOpnd, opndTaggedType);
  15921. }
  15922. labelNext = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, isHelper);
  15923. lastBranchToNext = LowererMD::GenerateLocalInlineCacheCheck(instrStFld, opndTaggedType, opndInlineCache, labelNext);
  15924. LowererMD::GenerateStFldFromLocalInlineCache(instrStFld, opndBase, opndSrc, opndInlineCache, labelFallThru, false);
  15925. instrStFld->InsertBefore(labelNext);
  15926. }
  15927. }
  15928. if (doAdd)
  15929. {
  15930. if (doInlineSlots)
  15931. {
  15932. labelNext = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, isHelper);
  15933. lastBranchToNext = LowererMD::GenerateLocalInlineCacheCheck(instrStFld, typeOpnd, opndInlineCache, labelNext, true);
  15934. GenerateSetObjectTypeFromInlineCache(instrStFld, opndBase, opndInlineCache, false);
  15935. LowererMD::GenerateStFldFromLocalInlineCache(instrStFld, opndBase, opndSrc, opndInlineCache, labelFallThru, true);
  15936. instrStFld->InsertBefore(labelNext);
  15937. }
  15938. if (doAuxSlots)
  15939. {
  15940. if (opndTaggedType == nullptr)
  15941. {
  15942. opndTaggedType = IR::RegOpnd::New(TyMachPtr, this->m_func);
  15943. LowererMD::GenerateLoadTaggedType(instrStFld, typeOpnd, opndTaggedType);
  15944. }
  15945. labelNext = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  15946. lastBranchToNext = LowererMD::GenerateLocalInlineCacheCheck(instrStFld, opndTaggedType, opndInlineCache, labelNext, true);
  15947. GenerateAuxSlotAdjustmentRequiredCheck(instrStFld, opndInlineCache, labelHelper);
  15948. GenerateSetObjectTypeFromInlineCache(instrStFld, opndBase, opndInlineCache, true);
  15949. LowererMD::GenerateStFldFromLocalInlineCache(instrStFld, opndBase, opndSrc, opndInlineCache, labelFallThru, false);
  15950. instrStFld->InsertBefore(labelNext);
  15951. }
  15952. }
  15953. Assert(lastBranchToNext);
  15954. lastBranchToNext->SetTarget(labelHelper);
  15955. labelNext->Remove();
  15956. // $helper:
  15957. // CALL Helper(inlineCache, base, field, src, scriptContext)
  15958. // $fallthru:
  15959. isHelper = true;
  15960. // Return false to indicate the original instruction was not lowered. Caller will insert the helper label.
  15961. return false;
  15962. }
  15963. bool Lowerer::GenerateFastStFldForCustomProperty(IR::Instr *const instr, IR::LabelInstr * *const labelHelperRef)
  15964. {
  15965. Assert(instr);
  15966. Assert(labelHelperRef);
  15967. Assert(!*labelHelperRef);
  15968. switch(instr->m_opcode)
  15969. {
  15970. case Js::OpCode::StFld:
  15971. case Js::OpCode::StFldStrict:
  15972. break;
  15973. default:
  15974. return false;
  15975. }
  15976. IR::SymOpnd *const symOpnd = instr->GetDst()->AsSymOpnd();
  15977. PropertySym *const propertySym = symOpnd->m_sym->AsPropertySym();
  15978. if(propertySym->m_propertyId != Js::PropertyIds::lastIndex || !symOpnd->IsPropertySymOpnd())
  15979. {
  15980. return false;
  15981. }
  15982. const ValueType objectValueType(symOpnd->GetPropertyOwnerValueType());
  15983. if(!objectValueType.IsLikelyRegExp())
  15984. {
  15985. return false;
  15986. }
  15987. if(instr->HasBailOutInfo())
  15988. {
  15989. const IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  15990. if(!BailOutInfo::IsBailOutOnImplicitCalls(bailOutKind) || bailOutKind & IR::BailOutKindBits)
  15991. {
  15992. // Other bailout kinds will likely need bailout checks that would not be generated here. In particular, if a type
  15993. // check is necessary here to guard against downstream property accesses on the same object, the type check will
  15994. // fail and cause a bailout if the object is a RegExp object since the "lastIndex" property accesses are not cached.
  15995. return false;
  15996. }
  15997. }
  15998. Func *const func = instr->m_func;
  15999. IR::RegOpnd *const objectOpnd = symOpnd->CreatePropertyOwnerOpnd(func);
  16000. const IR::AutoReuseOpnd autoReuseObjectOpnd(objectOpnd, func);
  16001. IR::LabelInstr *labelHelper = nullptr;
  16002. if(!objectOpnd->IsNotTaggedValue())
  16003. {
  16004. // test object, 1
  16005. // jnz $helper
  16006. if(!labelHelper)
  16007. {
  16008. *labelHelperRef = labelHelper = IR::LabelInstr::New(Js::OpCode::Label, func, true);
  16009. }
  16010. m_lowererMD.GenerateObjectTest(objectOpnd, instr, labelHelper);
  16011. }
  16012. if(!objectValueType.IsObject())
  16013. {
  16014. // cmp [object], Js::JavascriptRegExp::vtable
  16015. // jne $helper
  16016. if(!labelHelper)
  16017. {
  16018. *labelHelperRef = labelHelper = IR::LabelInstr::New(Js::OpCode::Label, func, true);
  16019. }
  16020. InsertCompareBranch(
  16021. IR::IndirOpnd::New(objectOpnd, 0, TyMachPtr, func),
  16022. LoadVTableValueOpnd(instr, VTableValue::VtableJavascriptRegExp),
  16023. Js::OpCode::BrNeq_A,
  16024. labelHelper,
  16025. instr);
  16026. objectOpnd->SetValueType(objectValueType.ToDefiniteObject());
  16027. }
  16028. // mov [object + offset(lastIndexVar)], src
  16029. // mov [object + offset(lastIndexOrFlag)], Js::JavascriptRegExp::NotCachedValue
  16030. // jmp $done
  16031. InsertMove(
  16032. IR::IndirOpnd::New(objectOpnd, Js::JavascriptRegExp::GetOffsetOfLastIndexVar(), TyVar, func),
  16033. instr->GetSrc1(),
  16034. instr);
  16035. InsertMove(
  16036. IR::IndirOpnd::New(objectOpnd, Js::JavascriptRegExp::GetOffsetOfLastIndexOrFlag(), TyUint32, func),
  16037. IR::IntConstOpnd::New(Js::JavascriptRegExp::NotCachedValue, TyUint32, func, true),
  16038. instr);
  16039. InsertBranch(Js::OpCode::Br, instr->GetOrCreateContinueLabel(), instr);
  16040. return true;
  16041. }
  16042. IR::RegOpnd *
  16043. Lowerer::GenerateIsBuiltinRecyclableObject(IR::RegOpnd *regOpnd, IR::Instr *insertInstr, IR::LabelInstr *labelHelper, bool checkObjectAndDynamicObject, IR::LabelInstr *labelContinue)
  16044. {
  16045. // CMP [srcReg], Js::DynamicObject::`vtable'
  16046. // JEQ $fallThough
  16047. // MOV r1, [src1 + offset(type)] -- get the type id
  16048. // MOV r1, [r1 + offset(typeId)]
  16049. // ADD r1, ~TypeIds_LastStaticType -- if (typeId > TypeIds_LastStaticType && typeId <= TypeIds_LastBuiltinDynamicObject)
  16050. // CMP r1, (TypeIds_LastBuiltinDynamicObject - TypeIds_LastStaticType - 1)
  16051. // JA $helper
  16052. //fallThrough:
  16053. IR::LabelInstr *labelFallthrough = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  16054. if (checkObjectAndDynamicObject)
  16055. {
  16056. if (!regOpnd->IsNotTaggedValue())
  16057. {
  16058. m_lowererMD.GenerateObjectTest(regOpnd, insertInstr, labelHelper);
  16059. }
  16060. m_lowererMD.GenerateIsDynamicObject(regOpnd, insertInstr, labelFallthrough, true);
  16061. }
  16062. IR::RegOpnd * typeRegOpnd = IR::RegOpnd::New(TyMachReg, this->m_func);
  16063. IR::RegOpnd * typeIdRegOpnd = IR::RegOpnd::New(TyInt32, this->m_func);
  16064. IR::IndirOpnd *indirOpnd;
  16065. // MOV typeRegOpnd, [src1 + offset(type)]
  16066. indirOpnd = IR::IndirOpnd::New(regOpnd, Js::RecyclableObject::GetOffsetOfType(), TyMachReg, this->m_func);
  16067. m_lowererMD.CreateAssign(typeRegOpnd, indirOpnd, insertInstr);
  16068. // MOV typeIdRegOpnd, [typeRegOpnd + offset(typeId)]
  16069. indirOpnd = IR::IndirOpnd::New(typeRegOpnd, Js::Type::GetOffsetOfTypeId(), TyInt32, this->m_func);
  16070. m_lowererMD.CreateAssign(typeIdRegOpnd, indirOpnd, insertInstr);
  16071. // ADD typeIdRegOpnd, ~TypeIds_LastStaticType
  16072. InsertAdd(false, typeIdRegOpnd, typeIdRegOpnd,
  16073. IR::IntConstOpnd::New(~Js::TypeIds_LastStaticType, TyInt32, this->m_func, true), insertInstr);
  16074. // CMP typeIdRegOpnd, (TypeIds_LastBuiltinDynamicObject - TypeIds_LastStaticType - 1)
  16075. InsertCompare(
  16076. typeIdRegOpnd,
  16077. IR::IntConstOpnd::New(Js::TypeIds_LastBuiltinDynamicObject - Js::TypeIds_LastStaticType - 1, TyInt32, this->m_func),
  16078. insertInstr);
  16079. if (labelContinue)
  16080. {
  16081. // On success, go to continuation label.
  16082. InsertBranch(Js::OpCode::BrLe_A, true, labelContinue, insertInstr);
  16083. }
  16084. else
  16085. {
  16086. // On failure, go to helper.
  16087. InsertBranch(Js::OpCode::BrGt_A, true, labelHelper, insertInstr);
  16088. }
  16089. // $fallThrough
  16090. insertInstr->InsertBefore(labelFallthrough);
  16091. return typeRegOpnd;
  16092. }
  16093. bool Lowerer::GenerateFastBrEqLikely(IR::BranchInstr * instrBranch, bool *pNeedHelper)
  16094. {
  16095. IR::Opnd *src1 = instrBranch->GetSrc1();
  16096. IR::Opnd *src2 = instrBranch->GetSrc2();
  16097. IR::LabelInstr *targetInstr = instrBranch->GetTarget();
  16098. IR::LabelInstr *labelBooleanCmp = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  16099. IR::LabelInstr *labelTrue = instrBranch->GetOrCreateContinueLabel();
  16100. IR::LabelInstr *labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  16101. bool isStrictBr = false;
  16102. bool isStrictMode = this->m_func->GetJnFunction()->GetIsStrictMode();
  16103. *pNeedHelper = true;
  16104. switch (instrBranch->m_opcode)
  16105. {
  16106. case Js::OpCode::BrSrEq_A:
  16107. case Js::OpCode::BrSrNotNeq_A:
  16108. case Js::OpCode::BrSrNeq_A:
  16109. case Js::OpCode::BrSrNotEq_A:
  16110. isStrictBr = true;
  16111. break;
  16112. }
  16113. if (src1->GetValueType().IsLikelyBoolean() && src2->GetValueType().IsLikelyBoolean())
  16114. {
  16115. //
  16116. // Booleans
  16117. //
  16118. if (isStrictBr)
  16119. {
  16120. if (!src1->GetValueType().IsBoolean() && !src2->GetValueType().IsBoolean())
  16121. {
  16122. this->m_lowererMD.GenerateObjectTest(src2->AsRegOpnd(), instrBranch, labelHelper, false);
  16123. if (this->m_lowererMD.GenerateJSBooleanTest(src2->AsRegOpnd(), instrBranch, labelBooleanCmp, true))
  16124. {
  16125. instrBranch->InsertBefore(IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, labelHelper, this->m_func));
  16126. }
  16127. }
  16128. else
  16129. {
  16130. *pNeedHelper = false;
  16131. }
  16132. }
  16133. else
  16134. {
  16135. this->m_lowererMD.GenerateObjectTest(src1->AsRegOpnd(), instrBranch, labelHelper, false);
  16136. this->m_lowererMD.GenerateJSBooleanTest(src1->AsRegOpnd(), instrBranch, labelHelper, false);
  16137. this->m_lowererMD.GenerateObjectTest(src2->AsRegOpnd(), instrBranch, labelHelper, false);
  16138. if (this->m_lowererMD.GenerateJSBooleanTest(src2->AsRegOpnd(), instrBranch, labelBooleanCmp, true))
  16139. {
  16140. instrBranch->InsertBefore(IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, labelHelper, this->m_func));
  16141. }
  16142. }
  16143. }
  16144. else if (src1->GetValueType().IsLikelyObject() && src2->GetValueType().IsLikelyObject())
  16145. {
  16146. //
  16147. // Objects
  16148. //
  16149. IR::LabelInstr *labelTypeIdCheck = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  16150. if (!isStrictBr)
  16151. {
  16152. // If not strictBr, verify both sides are dynamic objects
  16153. this->m_lowererMD.GenerateObjectTest(src1->AsRegOpnd(), instrBranch, labelHelper, false);
  16154. this->m_lowererMD.GenerateObjectTest(src2->AsRegOpnd(), instrBranch, labelHelper, false);
  16155. this->m_lowererMD.GenerateIsDynamicObject(src1->AsRegOpnd(), instrBranch, labelTypeIdCheck, false);
  16156. }
  16157. else
  16158. {
  16159. this->m_lowererMD.GenerateObjectTest(src2->AsRegOpnd(), instrBranch, labelHelper, false);
  16160. }
  16161. this->m_lowererMD.GenerateIsDynamicObject(src2->AsRegOpnd(), instrBranch, labelBooleanCmp, true);
  16162. instrBranch->InsertBefore(labelTypeIdCheck);
  16163. if (isStrictMode)
  16164. {
  16165. labelTypeIdCheck->isOpHelper = true;
  16166. IR::BranchInstr *branchToHelper = IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, labelHelper, this->m_func);
  16167. instrBranch->InsertBefore(branchToHelper);
  16168. }
  16169. else
  16170. {
  16171. if (!ExternalLowerer::TryGenerateFastExternalEqTest(src1, src2, instrBranch, labelHelper, labelBooleanCmp, this, isStrictBr))
  16172. {
  16173. if (!isStrictBr)
  16174. {
  16175. GenerateIsBuiltinRecyclableObject(src1->AsRegOpnd(), instrBranch, labelHelper, false /*checkObjectAndDynamicObject*/);
  16176. }
  16177. GenerateIsBuiltinRecyclableObject(src2->AsRegOpnd(), instrBranch, labelHelper, false /*checkObjectAndDynamicObject*/);
  16178. }
  16179. }
  16180. }
  16181. else
  16182. {
  16183. return false;
  16184. }
  16185. instrBranch->InsertBefore(labelBooleanCmp);
  16186. IR::BranchInstr *newBranch = IR::BranchInstr::New(instrBranch->m_opcode, targetInstr, src1, src2, this->m_func);
  16187. instrBranch->InsertBefore(newBranch);
  16188. this->m_lowererMD.LowerCondBranch(newBranch);
  16189. newBranch = IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, labelTrue, this->m_func);
  16190. instrBranch->InsertBefore(newBranch);
  16191. instrBranch->InsertBefore(labelHelper);
  16192. return true;
  16193. }
  16194. bool Lowerer::GenerateFastBrBool(IR::BranchInstr *const instr)
  16195. {
  16196. Assert(instr);
  16197. Assert(instr->m_opcode == Js::OpCode::BrFalse_A || instr->m_opcode == Js::OpCode::BrTrue_A);
  16198. Func *const func = instr->m_func;
  16199. if(!instr->GetSrc1()->IsRegOpnd())
  16200. {
  16201. LowererMD::ChangeToAssign(instr->HoistSrc1(Js::OpCode::Ld_A));
  16202. }
  16203. IR::RegOpnd *const src = instr->GetSrc1()->Copy(func)->AsRegOpnd();
  16204. const IR::AutoReuseOpnd autoReuseSrc(src, func);
  16205. const ValueType srcOriginalValueType(src->GetValueType());
  16206. ValueType srcValueType(srcOriginalValueType);
  16207. IR::LabelInstr *const labelTarget = instr->GetTarget();
  16208. IR::LabelInstr *const labelFallthrough = instr->GetOrCreateContinueLabel();
  16209. if(labelTarget == labelFallthrough)
  16210. {
  16211. // Nothing to do
  16212. instr->Remove();
  16213. return false;
  16214. }
  16215. const bool branchOnFalse = instr->m_opcode == Js::OpCode::BrFalse_A;
  16216. IR::LabelInstr *const labelFalse = branchOnFalse ? labelTarget : labelFallthrough;
  16217. IR::LabelInstr *const labelTrue = branchOnFalse ? labelFallthrough : labelTarget;
  16218. const Js::OpCode compareWithFalseBranchToTargetOpCode = branchOnFalse ? Js::OpCode::BrEq_A : Js::OpCode::BrNeq_A;
  16219. IR::LabelInstr *lastLabelBeforeHelper = nullptr;
  16220. /// Typespec'd float
  16221. if (instr->GetSrc1()->GetType() == TyFloat64)
  16222. {
  16223. InsertFloatCheckForZeroOrNanBranch(instr->GetSrc1(), branchOnFalse, labelTarget, labelFallthrough, instr);
  16224. Lowerer::InsertBranch(Js::OpCode::Br, labelFallthrough, instr);
  16225. instr->Remove();
  16226. return false;
  16227. }
  16228. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  16229. // Null fast path
  16230. if (srcValueType.HasBeenNull() || srcOriginalValueType.IsUninitialized())
  16231. {
  16232. if(srcValueType.IsNull())
  16233. {
  16234. // jmp $false
  16235. InsertBranch(Js::OpCode::Br, labelFalse, instr);
  16236. // Skip lowering call to helper
  16237. Assert(instr->m_prev->IsBranchInstr());
  16238. instr->Remove();
  16239. return false;
  16240. }
  16241. // cmp src, null
  16242. // je $false
  16243. InsertCompareBranch(
  16244. src,
  16245. LoadLibraryValueOpnd(instr, LibraryValue::ValueNull),
  16246. Js::OpCode::BrEq_A,
  16247. labelFalse,
  16248. instr);
  16249. src->SetValueType(srcValueType = srcValueType.SetIsNotAnyOf(ValueType::Null));
  16250. }
  16251. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  16252. // Undefined fast path
  16253. if(srcValueType.HasBeenUndefined() || srcOriginalValueType.IsUninitialized())
  16254. {
  16255. if(srcValueType.IsUndefined())
  16256. {
  16257. // jmp $false
  16258. InsertBranch(Js::OpCode::Br, labelFalse, instr);
  16259. // Skip lowering call to helper
  16260. Assert(instr->m_prev->IsBranchInstr());
  16261. instr->Remove();
  16262. return false;
  16263. }
  16264. // cmp src, undefined
  16265. // je $false
  16266. InsertCompareBranch(
  16267. src,
  16268. LoadLibraryValueOpnd(instr, LibraryValue::ValueUndefined),
  16269. Js::OpCode::BrEq_A,
  16270. labelFalse,
  16271. instr);
  16272. src->SetValueType(srcValueType = srcValueType.SetIsNotAnyOf(ValueType::Undefined));
  16273. }
  16274. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  16275. // Tagged int fast path
  16276. const bool isNotInt = src->IsNotInt();
  16277. bool checkedForTaggedInt = isNotInt;
  16278. if( (
  16279. srcValueType.HasBeenInt() ||
  16280. srcValueType.HasBeenUnknownNumber() ||
  16281. srcOriginalValueType.IsUninitialized()
  16282. ) && !isNotInt)
  16283. {
  16284. checkedForTaggedInt = true;
  16285. IR::LabelInstr *notTaggedIntLabel = nullptr;
  16286. if(!src->IsTaggedInt())
  16287. {
  16288. // test src, 1
  16289. // jz $notTaggedInt
  16290. notTaggedIntLabel = IR::LabelInstr::New(Js::OpCode::Label, func);
  16291. m_lowererMD.GenerateSmIntTest(src, instr, notTaggedIntLabel);
  16292. }
  16293. // cmp src, tag(0)
  16294. // je/jne $target
  16295. m_lowererMD.GenerateTaggedZeroTest(src, instr);
  16296. Lowerer::InsertBranch(compareWithFalseBranchToTargetOpCode, labelTarget, instr);
  16297. if(src->IsTaggedInt())
  16298. {
  16299. // Skip lowering call to helper
  16300. Assert(instr->m_prev->IsBranchInstr());
  16301. instr->Remove();
  16302. return false;
  16303. }
  16304. // jmp $fallthrough
  16305. Lowerer::InsertBranch(Js::OpCode::Br, labelFallthrough, instr);
  16306. // $notTaggedInt:
  16307. if(notTaggedIntLabel)
  16308. {
  16309. instr->InsertBefore(notTaggedIntLabel);
  16310. lastLabelBeforeHelper = notTaggedIntLabel;
  16311. }
  16312. }
  16313. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  16314. // Float fast path
  16315. bool generateFloatTest = srcValueType.IsLikelyFloat();
  16316. #ifdef _M_IX86
  16317. if (!AutoSystemInfo::Data.SSE2Available())
  16318. {
  16319. generateFloatTest = false;
  16320. }
  16321. #endif
  16322. bool checkedForTaggedFloat =
  16323. #if FLOATVAR
  16324. srcValueType.IsNotNumber();
  16325. #else
  16326. true; // there are no tagged floats, indicate that it has been checked
  16327. #endif
  16328. if (generateFloatTest)
  16329. {
  16330. // if(srcValueType.IsFloat()) // skip tagged int check?
  16331. //
  16332. // ValueType::IsFloat() does not guarantee that the storage is not in a tagged int.
  16333. // The tagged int check is necessary. It does, however, guarantee that as long as the value is not
  16334. // stored in a tagged int, that it is definitely stored in a JavascriptNumber/TaggedFloat.
  16335. IR::LabelInstr *const notFloatLabel = IR::LabelInstr::New(Js::OpCode::Label, func);
  16336. if(!checkedForTaggedInt)
  16337. {
  16338. checkedForTaggedInt = true;
  16339. m_lowererMD.GenerateSmIntTest(src, instr, notFloatLabel, nullptr, true);
  16340. }
  16341. // cmp [src], JavascriptNumber::vtable
  16342. // jne $notFloat
  16343. #if FLOATVAR
  16344. checkedForTaggedFloat = true;
  16345. IR::RegOpnd *const floatOpnd = m_lowererMD.CheckFloatAndUntag(src, instr, notFloatLabel);
  16346. #else
  16347. m_lowererMD.GenerateFloatTest(src, instr, notFloatLabel);
  16348. IR::IndirOpnd *const floatOpnd = IR::IndirOpnd::New(src, Js::JavascriptNumber::GetValueOffset(), TyMachDouble, func);
  16349. #endif
  16350. // cmp src, 0.0
  16351. // jp $false
  16352. // je/jne $target
  16353. // jmp $fallthrough
  16354. InsertFloatCheckForZeroOrNanBranch(floatOpnd, branchOnFalse, labelTarget, labelFallthrough, instr);
  16355. Lowerer::InsertBranch(Js::OpCode::Br, labelFallthrough, instr);
  16356. // $notFloat:
  16357. instr->InsertBefore(notFloatLabel);
  16358. lastLabelBeforeHelper = notFloatLabel;
  16359. src->SetValueType(srcValueType = srcValueType.SetIsNotAnyOf(ValueType::AnyNumber));
  16360. }
  16361. IR::LabelInstr *labelHelper = nullptr;
  16362. bool _didObjectTest = checkedForTaggedInt && checkedForTaggedFloat;
  16363. const auto EnsureObjectTest = [&]()
  16364. {
  16365. if(_didObjectTest)
  16366. {
  16367. return;
  16368. }
  16369. if(!labelHelper)
  16370. {
  16371. labelHelper = IR::LabelInstr::New(Js::OpCode::Label, func, true);
  16372. }
  16373. m_lowererMD.GenerateObjectTest(src, instr, labelHelper);
  16374. _didObjectTest = true;
  16375. };
  16376. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  16377. // Boolean fast path
  16378. if (srcValueType.HasBeenBoolean() || srcOriginalValueType.IsUninitialized())
  16379. {
  16380. IR::LabelInstr *notBooleanLabel = nullptr;
  16381. if (!srcValueType.IsBoolean())
  16382. {
  16383. EnsureObjectTest();
  16384. // cmp [src], JavascriptBoolean::vtable
  16385. // jne $notBoolean
  16386. notBooleanLabel = IR::LabelInstr::New(Js::OpCode::Label, func);
  16387. InsertCompareBranch(
  16388. IR::IndirOpnd::New(src, 0, TyMachPtr, func),
  16389. LoadVTableValueOpnd(instr, VTableValue::VtableJavascriptBoolean),
  16390. Js::OpCode::BrNeq_A,
  16391. notBooleanLabel,
  16392. instr);
  16393. }
  16394. // cmp src, false
  16395. // je/jne $target
  16396. InsertCompareBranch(
  16397. src,
  16398. LoadLibraryValueOpnd(instr, LibraryValue::ValueFalse),
  16399. compareWithFalseBranchToTargetOpCode,
  16400. labelTarget,
  16401. instr);
  16402. if (srcValueType.IsBoolean())
  16403. {
  16404. // Skip lowering call to helper
  16405. Assert(!labelHelper);
  16406. Assert(instr->m_prev->IsBranchInstr());
  16407. instr->Remove();
  16408. return false;
  16409. }
  16410. // jmp $fallthrough
  16411. Lowerer::InsertBranch(Js::OpCode::Br, labelFallthrough, instr);
  16412. if (notBooleanLabel)
  16413. {
  16414. instr->InsertBefore(notBooleanLabel);
  16415. lastLabelBeforeHelper = notBooleanLabel;
  16416. }
  16417. src->SetValueType(srcValueType = srcValueType.SetIsNotAnyOf(ValueType::Boolean));
  16418. }
  16419. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  16420. // String fast path
  16421. if(srcValueType.HasBeenString())
  16422. {
  16423. IR::LabelInstr *notStringLabel = nullptr;
  16424. if(!srcValueType.IsString())
  16425. {
  16426. EnsureObjectTest();
  16427. notStringLabel = IR::LabelInstr::New(Js::OpCode::Label, func);
  16428. GenerateStringTest(src, instr, notStringLabel, nullptr, false);
  16429. }
  16430. // cmp [src + offset(length)], 0
  16431. // jeq/jne $target
  16432. InsertCompareBranch(
  16433. IR::IndirOpnd::New(src, Js::JavascriptString::GetOffsetOfcharLength(), TyUint32, func),
  16434. IR::IntConstOpnd::New(0, TyUint32, func, true),
  16435. compareWithFalseBranchToTargetOpCode,
  16436. labelTarget,
  16437. instr);
  16438. if(srcValueType.IsString())
  16439. {
  16440. // Skip lowering call to helper
  16441. Assert(!labelHelper);
  16442. Assert(instr->m_prev->IsBranchInstr());
  16443. instr->Remove();
  16444. return false;
  16445. }
  16446. // jmp $fallthrough
  16447. Lowerer::InsertBranch(Js::OpCode::Br, labelFallthrough, instr);
  16448. if(notStringLabel)
  16449. {
  16450. instr->InsertBefore(notStringLabel);
  16451. lastLabelBeforeHelper = notStringLabel;
  16452. }
  16453. src->SetValueType(srcValueType = srcValueType.SetIsNotAnyOf(ValueType::String));
  16454. }
  16455. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  16456. // Object fast path
  16457. if (srcValueType.IsLikelyObject())
  16458. {
  16459. if(srcValueType.IsObject())
  16460. {
  16461. if(srcValueType.GetObjectType() > ObjectType::Object)
  16462. {
  16463. // Specific object types that are tracked are equivalent to 'true'
  16464. // jmp $true
  16465. InsertBranch(Js::OpCode::Br, labelTrue, instr);
  16466. // Skip lowering call to helper
  16467. Assert(!labelHelper);
  16468. Assert(instr->m_prev->IsBranchInstr());
  16469. instr->Remove();
  16470. return false;
  16471. }
  16472. }
  16473. else
  16474. {
  16475. EnsureObjectTest();
  16476. }
  16477. // mov srcType, [src + offset(type)] -- load type
  16478. IR::RegOpnd *const srcType = IR::RegOpnd::New(TyMachPtr, func);
  16479. const IR::AutoReuseOpnd autoReuseR1(srcType, func);
  16480. InsertMove(srcType, IR::IndirOpnd::New(src, Js::RecyclableObject::GetOffsetOfType(), TyMachPtr, func), instr);
  16481. // test [srcType + offset(flags)], TypeFlagMask_IsFalsy -- check if falsy
  16482. // jnz $false
  16483. InsertTestBranch(
  16484. IR::IndirOpnd::New(srcType, Js::Type::GetOffsetOfFlags(), TyUint8, func),
  16485. IR::IntConstOpnd::New(TypeFlagMask_IsFalsy, TyUint8, func),
  16486. Js::OpCode::BrNeq_A,
  16487. labelFalse,
  16488. instr);
  16489. // cmp [srcType + offset(typeId)], TypeIds_LastJavascriptPrimitiveType -- check base TypeIds_LastJavascriptPrimitiveType
  16490. // ja $true
  16491. InsertCompareBranch(
  16492. IR::IndirOpnd::New(srcType, Js::Type::GetOffsetOfTypeId(), TyInt32, func),
  16493. IR::IntConstOpnd::New(Js::TypeIds_LastJavascriptPrimitiveType, TyInt32, func),
  16494. Js::OpCode::BrGt_A,
  16495. true /* isUnsigned */,
  16496. labelTrue,
  16497. instr);
  16498. if(!labelHelper)
  16499. {
  16500. labelHelper = IR::LabelInstr::New(Js::OpCode::Label, func, true);
  16501. }
  16502. lastLabelBeforeHelper = nullptr;
  16503. }
  16504. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  16505. // Helper call
  16506. // $helper:
  16507. if(lastLabelBeforeHelper)
  16508. {
  16509. Assert(instr->m_prev == lastLabelBeforeHelper);
  16510. lastLabelBeforeHelper->isOpHelper = true;
  16511. }
  16512. if (labelHelper)
  16513. {
  16514. Assert(labelHelper->isOpHelper);
  16515. instr->InsertBefore(labelHelper);
  16516. }
  16517. // call JavascriptConversion::ToBoolean
  16518. IR::RegOpnd *const toBoolDst = IR::RegOpnd::New(TyInt32, func);
  16519. const IR::AutoReuseOpnd autoReuseToBoolDst(toBoolDst, func);
  16520. IR::Instr *const callInstr = IR::Instr::New(Js::OpCode::Call, toBoolDst, instr->GetSrc1(), func);
  16521. instr->InsertBefore(callInstr);
  16522. LowerUnaryHelperMem(callInstr, IR::HelperConv_ToBoolean);
  16523. // test eax, eax
  16524. InsertTest(toBoolDst, toBoolDst, instr);
  16525. // je/jne $target
  16526. Assert(instr->IsBranchInstr());
  16527. instr->FreeSrc1();
  16528. instr->m_opcode = LowererMD::MDBranchOpcode(compareWithFalseBranchToTargetOpCode);
  16529. Assert(instr->AsBranchInstr()->GetTarget() == labelTarget);
  16530. // Skip lowering another call to helper
  16531. return false;
  16532. }
  16533. // Helper method used in LowerMD by all platforms.
  16534. // Creates HelperCallOpnd or DiagHelperCallOpnd, based on helperMethod and state.
  16535. // static
  16536. IR::HelperCallOpnd*
  16537. Lowerer::CreateHelperCallOpnd(IR::JnHelperMethod helperMethod, int helperArgCount, Func* func)
  16538. {
  16539. Assert(func);
  16540. IR::HelperCallOpnd* helperCallOpnd;
  16541. if (CONFIG_FLAG(EnableContinueAfterExceptionWrappersForHelpers) &&
  16542. func->IsJitInDebugMode() &&
  16543. HelperMethodAttributes::CanThrow(helperMethod))
  16544. {
  16545. // Create DiagHelperCallOpnd to indicate that it's needed to wrap original helper with try-catch wrapper,
  16546. // so that we can ignore exception and bailout to next stmt in debugger.
  16547. // For details, see: Lib\Runtime\Debug\DiagHelperMethodWrapper.{h,cpp}.
  16548. helperCallOpnd = IR::DiagHelperCallOpnd::New(helperMethod, func, helperArgCount);
  16549. }
  16550. else
  16551. {
  16552. helperCallOpnd = IR::HelperCallOpnd::New(helperMethod, func);
  16553. }
  16554. return helperCallOpnd;
  16555. }
  16556. bool
  16557. Lowerer::TryGenerateFastBrOrCmTypeOf(IR::Instr *instr, IR::Instr **prev, bool *pfNoLower)
  16558. {
  16559. Assert(prev);
  16560. Assert(instr->m_opcode == Js::OpCode::BrSrEq_A ||
  16561. instr->m_opcode == Js::OpCode::BrSrNeq_A ||
  16562. instr->m_opcode == Js::OpCode::BrSrNotEq_A ||
  16563. instr->m_opcode == Js::OpCode::BrSrNotNeq_A ||
  16564. instr->m_opcode == Js::OpCode::CmSrEq_A ||
  16565. instr->m_opcode == Js::OpCode::CmSrNeq_A ||
  16566. instr->m_opcode == Js::OpCode::BrEq_A ||
  16567. instr->m_opcode == Js::OpCode::BrNeq_A ||
  16568. instr->m_opcode == Js::OpCode::BrNotEq_A ||
  16569. instr->m_opcode == Js::OpCode::BrNotNeq_A ||
  16570. instr->m_opcode == Js::OpCode::CmEq_A ||
  16571. instr->m_opcode == Js::OpCode::CmNeq_A);
  16572. //
  16573. // instr - (Br/Cm)Sr(N)eq_A
  16574. // instr->m_prev - typeOf
  16575. //
  16576. IR::Instr *instrLd = instr->GetPrevRealInstrOrLabel();
  16577. bool skippedLoads = false;
  16578. //Skip intermediate Ld_A which might be inserted by flow graph peeps
  16579. while (instrLd && instrLd->m_opcode == Js::OpCode::Ld_A )
  16580. {
  16581. if (!(instrLd->GetDst()->IsRegOpnd() && instrLd->GetDst()->AsRegOpnd()->m_fgPeepTmp))
  16582. {
  16583. return false;
  16584. }
  16585. if (instrLd->HasBailOutInfo())
  16586. {
  16587. return false;
  16588. }
  16589. instrLd = instrLd->GetPrevRealInstrOrLabel();
  16590. skippedLoads = true;
  16591. }
  16592. IR::Instr *typeOf = instrLd;
  16593. if (typeOf && (typeOf->m_opcode == Js::OpCode::Typeof))
  16594. {
  16595. IR::RegOpnd *typeOfDst = typeOf->GetDst()->IsRegOpnd() ? typeOf->GetDst()->AsRegOpnd() : nullptr;
  16596. IR::RegOpnd *instrSrc1 = instr->GetSrc1()->IsRegOpnd() ? instr->GetSrc1()->AsRegOpnd() : nullptr;
  16597. IR::RegOpnd *instrSrc2 = instr->GetSrc2()->IsRegOpnd() ? instr->GetSrc2()->AsRegOpnd() : nullptr;
  16598. if (typeOfDst && instrSrc1 && instrSrc2)
  16599. {
  16600. if (instrSrc1->m_sym == typeOfDst->m_sym)
  16601. {
  16602. if (!instrSrc1->m_isTempLastUse)
  16603. {
  16604. return false;
  16605. }
  16606. if (!(instrSrc2->m_sym->m_isSingleDef && instrSrc2->m_sym->m_isStrConst))
  16607. {
  16608. return false;
  16609. }
  16610. // The second argument to [Cm|Br]TypeOf is the typeid.
  16611. IR::IntConstOpnd *typeIdOpnd = nullptr;
  16612. Assert(instrSrc2->m_sym->m_isSingleDef);
  16613. Assert(instrSrc2->m_sym->m_instrDef->GetSrc1()->IsAddrOpnd());
  16614. // We can't optimize non-javascript type strings.
  16615. Js::JavascriptString *typeNameJsString = Js::JavascriptString::FromVar(instrSrc2->m_sym->m_instrDef->GetSrc1()->AsAddrOpnd()->m_address);
  16616. const wchar_t *typeName = typeNameJsString->GetString();
  16617. Js::InternalString typeNameString(typeName, typeNameJsString->GetLength());
  16618. if (Js::InternalStringComparer::Equals(typeNameString, Js::Type::UndefinedTypeNameString))
  16619. {
  16620. typeIdOpnd = IR::IntConstOpnd::New(Js::TypeIds_Undefined, TyInt32, instr->m_func);
  16621. }
  16622. else if (Js::InternalStringComparer::Equals(typeNameString, Js::Type::ObjectTypeNameString))
  16623. {
  16624. typeIdOpnd = IR::IntConstOpnd::New(Js::TypeIds_Object, TyInt32, instr->m_func);
  16625. }
  16626. else if (Js::InternalStringComparer::Equals(typeNameString, Js::Type::BooleanTypeNameString))
  16627. {
  16628. typeIdOpnd = IR::IntConstOpnd::New(Js::TypeIds_Boolean, TyInt32, instr->m_func);
  16629. }
  16630. else if (Js::InternalStringComparer::Equals(typeNameString, Js::Type::NumberTypeNameString))
  16631. {
  16632. typeIdOpnd = IR::IntConstOpnd::New(Js::TypeIds_Number, TyInt32, instr->m_func);
  16633. }
  16634. else if (Js::InternalStringComparer::Equals(typeNameString, Js::Type::StringTypeNameString))
  16635. {
  16636. typeIdOpnd = IR::IntConstOpnd::New(Js::TypeIds_String, TyInt32, instr->m_func);
  16637. }
  16638. else if (Js::InternalStringComparer::Equals(typeNameString, Js::Type::FunctionTypeNameString))
  16639. {
  16640. typeIdOpnd = IR::IntConstOpnd::New(Js::TypeIds_Function, TyInt32, instr->m_func);
  16641. }
  16642. else
  16643. {
  16644. return false;
  16645. }
  16646. if (skippedLoads)
  16647. {
  16648. //validate none of dst of Ld_A overlaps with typeof src or dst
  16649. IR::Opnd* typeOfSrc = typeOf->GetSrc1();
  16650. instrLd = typeOf->GetNextRealInstr();
  16651. while (instrLd != instr)
  16652. {
  16653. if (instrLd->GetDst()->IsEqual(typeOfDst) || instrLd->GetDst()->IsEqual(typeOfSrc))
  16654. {
  16655. return false;
  16656. }
  16657. instrLd = instrLd->GetNextRealInstr();
  16658. }
  16659. typeOf->Unlink();
  16660. instr->InsertBefore(typeOf);
  16661. }
  16662. // The first argument to [Cm|Br]TypeOf is the first arg to the TypeOf instruction.
  16663. IR::Opnd *objectOpnd = typeOf->GetSrc1();
  16664. Assert(objectOpnd->IsRegOpnd());
  16665. // Now emit this instruction and remove the ldstr and typeOf.
  16666. *prev = typeOf->m_prev;
  16667. *pfNoLower = false;
  16668. if (instr->IsBranchInstr())
  16669. {
  16670. GenerateFastBrTypeOf(instr, objectOpnd->AsRegOpnd(), typeIdOpnd, typeOf, pfNoLower);
  16671. }
  16672. else
  16673. {
  16674. GenerateFastCmTypeOf(instr, objectOpnd->AsRegOpnd(), typeIdOpnd, typeOf, pfNoLower);
  16675. }
  16676. return true;
  16677. }
  16678. }
  16679. }
  16680. return false;
  16681. }
  16682. void
  16683. Lowerer::GenerateFalsyObjectTest(IR::Instr *insertInstr, IR::RegOpnd *TypeOpnd, Js::TypeId typeIdToCheck, IR::LabelInstr* target, IR::LabelInstr* done, bool isNeqOp)
  16684. {
  16685. if (!this->m_func->GetScriptContext()->GetThreadContext()->CanBeFalsy(typeIdToCheck) && typeIdToCheck != Js::TypeIds_Undefined)
  16686. {
  16687. // Don't need the check for falsy, the typeId we are looking for doesn't care
  16688. return;
  16689. }
  16690. IR::Opnd *flagsOpnd = IR::IndirOpnd::New(TypeOpnd, Js::Type::GetOffsetOfFlags(), TyInt32, this->m_func);
  16691. InsertTest(flagsOpnd, IR::IntConstOpnd::New(TypeFlagMask_IsFalsy, TyInt32, this->m_func), insertInstr);
  16692. if (typeIdToCheck == Js::TypeIds_Undefined)
  16693. {
  16694. //Falsy object returns true for undefined ((typeof falsyObj) == "undefined")
  16695. InsertBranch( Js::OpCode::BrNeq_A, true, isNeqOp ? done : target, insertInstr);
  16696. }
  16697. else
  16698. {
  16699. //Falsy object returns false for all other types ((typeof falsyObj) != "function")
  16700. InsertBranch( Js::OpCode::BrNeq_A, true, isNeqOp? target : done , insertInstr);
  16701. }
  16702. }
  16703. ///----------------------------------------------------------------------------
  16704. ///
  16705. /// LowererMD::GenerateFastBrTypeOf
  16706. ///
  16707. ///----------------------------------------------------------------------------
  16708. void
  16709. Lowerer::GenerateFastBrTypeOf(IR::Instr *branch, IR::RegOpnd *object, IR::IntConstOpnd *typeIdOpnd, IR::Instr *typeOf, bool *pfNoLower)
  16710. {
  16711. Js::TypeId typeId = static_cast<Js::TypeId>(typeIdOpnd->GetValue());
  16712. IR::LabelInstr *target = branch->AsBranchInstr()->GetTarget();
  16713. IR::LabelInstr *done = IR::LabelInstr::New(Js::OpCode::Label, m_func, false);
  16714. IR::LabelInstr *helper = IR::LabelInstr::New(Js::OpCode::Label, m_func, true);
  16715. IR::RegOpnd *typeRegOpnd = IR::RegOpnd::New(TyMachReg, m_func);
  16716. bool isNeqOp;
  16717. switch(branch->m_opcode)
  16718. {
  16719. case Js::OpCode::BrSrNeq_A:
  16720. case Js::OpCode::BrNeq_A:
  16721. case Js::OpCode::BrSrNotEq_A:
  16722. case Js::OpCode::BrNotEq_A:
  16723. isNeqOp = true;
  16724. break;
  16725. case Js::OpCode::BrSrEq_A:
  16726. case Js::OpCode::BrEq_A:
  16727. case Js::OpCode::BrSrNotNeq_A:
  16728. case Js::OpCode::BrNotNeq_A:
  16729. isNeqOp = false;
  16730. break;
  16731. default:
  16732. Assert(UNREACHED);
  16733. __assume(UNREACHED);
  16734. }
  16735. // JNE/BNE (typeId == Js::TypeIds_Number) ? $target : $done
  16736. IR::LabelInstr *label = (typeId == Js::TypeIds_Number) ? target : done;
  16737. if (isNeqOp)
  16738. label = (label == target) ? done : target;
  16739. m_lowererMD.GenerateObjectTest(object, branch, label);
  16740. // MOV typeRegOpnd, [object + offset(Type)]
  16741. InsertMove(typeRegOpnd,
  16742. IR::IndirOpnd::New(object, Js::RecyclableObject::GetOffsetOfType(), TyMachReg, m_func),
  16743. branch);
  16744. GenerateFalsyObjectTest(branch, typeRegOpnd, typeId, target, done, isNeqOp);
  16745. // MOV objTypeId, [typeRegOpnd + offset(TypeId)]
  16746. IR::RegOpnd* objTypeIdOpnd = IR::RegOpnd::New(TyInt32, m_func);
  16747. InsertMove(objTypeIdOpnd,
  16748. IR::IndirOpnd::New(typeRegOpnd, Js::Type::GetOffsetOfTypeId(), TyInt32, m_func),
  16749. branch);
  16750. // CMP objTypeId, typeId
  16751. // JEQ/JGE $done
  16752. if (typeId == Js::TypeIds_Object)
  16753. {
  16754. InsertCompareBranch(objTypeIdOpnd, typeIdOpnd, Js::OpCode::BrGe_A, isNeqOp ? done : target, branch);
  16755. }
  16756. else if (typeId == Js::TypeIds_Function)
  16757. {
  16758. InsertCompareBranch(objTypeIdOpnd, typeIdOpnd, Js::OpCode::BrEq_A, isNeqOp ? done : target, branch);
  16759. }
  16760. else if (typeId == Js::TypeIds_Number)
  16761. {
  16762. //Check for the typeIds between TypeIds_FirstNumberType <= typeIds <= TypeIds_LastNumberType
  16763. InsertSub(false, objTypeIdOpnd, objTypeIdOpnd, IR::IntConstOpnd::New(Js::TypeIds_FirstNumberType, TyInt32, branch->m_func),branch);
  16764. InsertCompare(objTypeIdOpnd, IR::IntConstOpnd::New(Js::TypeIds_LastNumberType - Js::TypeIds_FirstNumberType, TyInt32, branch->m_func), branch);
  16765. InsertBranch(isNeqOp ? Js::OpCode::BrGt_A : Js::OpCode::BrLe_A, true, target, branch);
  16766. }
  16767. else
  16768. {
  16769. InsertCompare(objTypeIdOpnd, typeIdOpnd, branch);
  16770. InsertBranch(isNeqOp ? Js::OpCode::BrNeq_A : Js::OpCode::BrEq_A, target, branch);
  16771. }
  16772. // This could be 'null' which, for historical reasons, has a TypeId < TypeIds_Object but
  16773. // is still a Javascript "object."
  16774. if (typeId == Js::TypeIds_Object)
  16775. {
  16776. // CMP object, 0xXXXXXXXX
  16777. // JEQ isNeqOp ? $done : $target
  16778. InsertCompareBranch(object,
  16779. LoadLibraryValueOpnd(branch, LibraryValue::ValueNull),
  16780. Js::OpCode::BrEq_A,
  16781. isNeqOp ? done : target,
  16782. branch);
  16783. }
  16784. branch->InsertAfter(done); // Get this label first
  16785. // "object" or "function" may come from HostDispatch. Needs helper if that's the case.
  16786. if (typeId == Js::TypeIds_Object || typeId == Js::TypeIds_Function)
  16787. {
  16788. // CMP objTypeId, TypeIds_Proxy. typeof proxy could be 'object' or 'function' depends on the target
  16789. // JNE isNeqOp ? $target : $done
  16790. InsertCompareBranch(objTypeIdOpnd,
  16791. IR::IntConstOpnd::New(Js::TypeIds_Proxy, TyInt32, m_func),
  16792. Js::OpCode::BrEq_A,
  16793. helper,
  16794. branch);
  16795. // CMP objTypeId, TypeIds_HostDispatch
  16796. // JNE isNeqOp ? $target : $done
  16797. InsertCompareBranch(objTypeIdOpnd,
  16798. IR::IntConstOpnd::New(Js::TypeIds_HostDispatch, TyInt32, m_func),
  16799. Js::OpCode::BrNeq_A,
  16800. isNeqOp ? target : done,
  16801. branch);
  16802. // Now emit Typeof and lower it like we would've for the helper call.
  16803. {
  16804. branch->InsertBefore(helper);
  16805. typeOf->Unlink();
  16806. branch->InsertBefore(typeOf);
  16807. LowerUnaryHelperMem(typeOf, IR::HelperOp_Typeof);
  16808. }
  16809. }
  16810. else // Other primitive types don't need helper
  16811. {
  16812. typeOf->Remove();
  16813. branch->Remove();
  16814. *pfNoLower = true;
  16815. }
  16816. // $done:
  16817. }
  16818. ///----------------------------------------------------------------------------
  16819. ///
  16820. /// LowererMD::GenerateFastCmTypeOf
  16821. ///
  16822. ///----------------------------------------------------------------------------
  16823. void
  16824. Lowerer::GenerateFastCmTypeOf(IR::Instr *compare, IR::RegOpnd *object, IR::IntConstOpnd *typeIdOpnd, IR::Instr *typeOf, bool *pfNoLower)
  16825. {
  16826. Assert(compare->m_opcode == Js::OpCode::CmSrEq_A ||
  16827. compare->m_opcode == Js::OpCode::CmEq_A ||
  16828. compare->m_opcode == Js::OpCode::CmSrNeq_A ||
  16829. compare->m_opcode == Js::OpCode::CmNeq_A);
  16830. Js::TypeId typeId = static_cast<Js::TypeId>(typeIdOpnd->GetValue());
  16831. IR::LabelInstr *movFalse = IR::LabelInstr::New(Js::OpCode::Label, m_func, false);
  16832. IR::LabelInstr *done = IR::LabelInstr::New(Js::OpCode::Label, m_func, false);
  16833. IR::LabelInstr *helper= IR::LabelInstr::New(Js::OpCode::Label, m_func, true);
  16834. IR::RegOpnd *dst = compare->GetDst()->IsRegOpnd() ? compare->GetDst()->AsRegOpnd() : nullptr;
  16835. IR::RegOpnd *typeRegOpnd = IR::RegOpnd::New(TyMachReg, m_func);
  16836. bool isNeqOp = compare->m_opcode == Js::OpCode::CmSrNeq_A ||
  16837. compare->m_opcode == Js::OpCode::CmNeq_A;
  16838. Assert(dst);
  16839. if (dst->IsEqual(object))
  16840. {
  16841. //dst same as the src of typeof. As we need to move true to dst first we need to save the src to a new opnd
  16842. IR::RegOpnd *newObject = IR::RegOpnd::New(object->GetType(), m_func);
  16843. InsertMove(newObject, object, compare); //Save src
  16844. object = newObject;
  16845. }
  16846. // mov dst, 'true'
  16847. InsertMove(dst,
  16848. LoadLibraryValueOpnd(compare, LibraryValue::ValueTrue),
  16849. compare);
  16850. // TEST object, 1
  16851. // JNE (typeId == Js::TypeIds_Number) ? $done : $movFalse
  16852. IR::LabelInstr *target = (typeId == Js::TypeIds_Number) ? done : movFalse;
  16853. if (isNeqOp)
  16854. {
  16855. target = (target == done) ? movFalse : done;
  16856. }
  16857. m_lowererMD.GenerateObjectTest(object, compare, target);
  16858. // MOV typeRegOpnd, [object + offset(Type)]
  16859. InsertMove(typeRegOpnd,
  16860. IR::IndirOpnd::New(object, Js::RecyclableObject::GetOffsetOfType(), TyMachReg, m_func),
  16861. compare);
  16862. GenerateFalsyObjectTest(compare, typeRegOpnd, typeId, done, movFalse, isNeqOp);
  16863. // MOV objTypeId, [typeRegOpnd + offset(TypeId)]
  16864. IR::RegOpnd* objTypeIdOpnd = IR::RegOpnd::New(TyInt32, m_func);
  16865. InsertMove(objTypeIdOpnd,
  16866. IR::IndirOpnd::New(typeRegOpnd, Js::Type::GetOffsetOfTypeId(), TyInt32, m_func),
  16867. compare);
  16868. // CMP objTypeId, typeId
  16869. // JEQ/JGE $done
  16870. if (typeId == Js::TypeIds_Object)
  16871. {
  16872. InsertCompareBranch(objTypeIdOpnd, typeIdOpnd, Js::OpCode::BrGe_A, isNeqOp ? movFalse : done, compare);
  16873. }
  16874. else if (typeId == Js::TypeIds_Function)
  16875. {
  16876. InsertCompareBranch(objTypeIdOpnd, typeIdOpnd, Js::OpCode::BrEq_A, isNeqOp ? movFalse : done, compare);
  16877. }
  16878. else if (typeId == Js::TypeIds_Number)
  16879. {
  16880. //Check for the typeIds between TypeIds_FirstNumberType <= typeIds <= TypeIds_LastNumberType
  16881. InsertCompareBranch(objTypeIdOpnd,
  16882. IR::IntConstOpnd::New(Js::TypeIds_LastNumberType, TyInt32, compare->m_func),
  16883. Js::OpCode::BrGt_A,
  16884. isNeqOp ? done : movFalse,
  16885. compare);
  16886. InsertCompareBranch(objTypeIdOpnd,
  16887. IR::IntConstOpnd::New(Js::TypeIds_FirstNumberType, TyInt32, compare->m_func),
  16888. isNeqOp? Js::OpCode::BrLt_A : Js::OpCode::BrGe_A,
  16889. done,
  16890. compare);
  16891. }
  16892. else
  16893. {
  16894. InsertCompareBranch(objTypeIdOpnd, typeIdOpnd, isNeqOp ? Js::OpCode::BrNeq_A : Js::OpCode::BrEq_A, done, compare);
  16895. }
  16896. // This could be 'null' which, for historical reasons, has a TypeId < TypeIds_Object but
  16897. // is still a Javascript "object."
  16898. if (typeId == Js::TypeIds_Object)
  16899. {
  16900. // CMP object, 0xXXXXXXXX
  16901. // JEQ isNeqOp ? $movFalse : $done
  16902. InsertCompareBranch(object,
  16903. LoadLibraryValueOpnd(compare, LibraryValue::ValueNull),
  16904. Js::OpCode::BrEq_A,
  16905. isNeqOp ? movFalse : done,
  16906. compare);
  16907. }
  16908. compare->InsertAfter(done); // Get this label first
  16909. // "object" or "function" may come from HostDispatch. Needs helper if that's the case.
  16910. if (typeId == Js::TypeIds_Object || typeId == Js::TypeIds_Function)
  16911. {
  16912. // CMP objTypeId, TypeIds_Proxy
  16913. // JNE isNeqOp ? $done : $movFalse
  16914. InsertCompareBranch(objTypeIdOpnd,
  16915. IR::IntConstOpnd::New(Js::TypeIds_Proxy, TyInt32, m_func),
  16916. Js::OpCode::BrEq_A,
  16917. helper,
  16918. compare);
  16919. // CMP objTypeId, TypeIds_HostDispatch
  16920. // JNE isNeqOp ? $done : $movFalse
  16921. InsertCompareBranch(objTypeIdOpnd,
  16922. IR::IntConstOpnd::New(Js::TypeIds_HostDispatch, TyInt32, m_func),
  16923. Js::OpCode::BrNeq_A,
  16924. isNeqOp ? done : movFalse,
  16925. compare);
  16926. // Now emit Typeof like we would've for the helper call.
  16927. {
  16928. compare->InsertBefore(helper);
  16929. typeOf->Unlink();
  16930. compare->InsertBefore(typeOf);
  16931. LowerUnaryHelperMem(typeOf, IR::HelperOp_Typeof);
  16932. }
  16933. // JMP/B $done
  16934. InsertBranch(Js::OpCode::Br, done, done);
  16935. }
  16936. else // Other primitive types don't need helper
  16937. {
  16938. typeOf->Remove();
  16939. compare->Remove();
  16940. *pfNoLower = true;
  16941. }
  16942. // $movFalse: (insert before $done)
  16943. done->InsertBefore(movFalse);
  16944. // MOV dst, 'false'
  16945. InsertMove(dst, LoadLibraryValueOpnd(done, LibraryValue::ValueFalse), done);
  16946. // $done:
  16947. }
  16948. void
  16949. Lowerer::GenerateCheckForCallFlagNew(IR::Instr* instrInsert)
  16950. {
  16951. Func *func = instrInsert->m_func;
  16952. IR::LabelInstr * labelDone = IR::LabelInstr::New(Js::OpCode::Label, func, false);
  16953. Assert(!func->IsInlinee());
  16954. // MOV s1, [ebp + 4] // s1 = call info
  16955. // AND s2, s1, Js::CallFlags_New // s2 = s1 & Js::CallFlags_New
  16956. // CMP s2, 0
  16957. // JNE $Done
  16958. // CALL RuntimeTypeError
  16959. // $Done
  16960. IR::SymOpnd* callInfoOpnd = Lowerer::LoadCallInfo(instrInsert);
  16961. Assert(Js::CallInfo::ksizeofCount == 24);
  16962. IR::RegOpnd* isNewFlagSetRegOpnd = IR::RegOpnd::New(TyUint32, func);
  16963. InsertAnd(isNewFlagSetRegOpnd, callInfoOpnd, IR::IntConstOpnd::New((IntConstType)Js::CallFlags_New << Js::CallInfo::ksizeofCount, TyUint32, func, true), instrInsert);
  16964. InsertTestBranch(isNewFlagSetRegOpnd, isNewFlagSetRegOpnd, Js::OpCode::BrNeq_A, labelDone, instrInsert);
  16965. IR::Instr *throwInstr = IR::Instr::New(
  16966. Js::OpCode::RuntimeTypeError,
  16967. IR::RegOpnd::New(TyMachReg, m_func),
  16968. IR::IntConstOpnd::New(SCODE_CODE(JSERR_ClassConstructorCannotBeCalledWithoutNew), TyInt32, m_func),
  16969. m_func);
  16970. instrInsert->InsertBefore(throwInstr);
  16971. this->LowerUnaryHelperMem(throwInstr, IR::HelperOp_RuntimeTypeError);
  16972. instrInsert->InsertBefore(labelDone);
  16973. instrInsert->Remove();
  16974. }
  16975. void
  16976. Lowerer::GenerateLoadNewTarget(IR::Instr* instrInsert)
  16977. {
  16978. Func *func = instrInsert->m_func;
  16979. IR::LabelInstr * labelDone = IR::LabelInstr::New(Js::OpCode::Label, func, false);
  16980. IR::LabelInstr * labelLoadArgNewTarget = IR::LabelInstr::New(Js::OpCode::Label, func, false);
  16981. IR::Opnd* opndUndefAddress = this->LoadLibraryValueOpnd(instrInsert, LibraryValue::ValueUndefined);
  16982. Assert(!func->IsInlinee());
  16983. if (func->GetJnFunction()->IsGenerator())
  16984. {
  16985. instrInsert->SetSrc1(opndUndefAddress);
  16986. LowererMD::ChangeToAssign(instrInsert);
  16987. return;
  16988. }
  16989. // MOV dst, undefined // dst = undefined
  16990. // MOV s1, [ebp + 4] // s1 = call info
  16991. // AND s2, s1, Js::CallFlags_NewTarget // s2 = s1 & Js::CallFlags_NewTarget
  16992. // CMP s2, 0
  16993. // JNE $LoadLastArgument
  16994. // AND s2, s1, Js::CallFlags_New // s2 = s1 & Js::CallFlags_New
  16995. // CMP s2, 0
  16996. // JE $Done
  16997. // MOV dst, [ebp + 8] // dst = function object
  16998. // JMP $Done
  16999. // $LoadLastArgument
  17000. // AND s2, s1, (0x00FFFFFF)
  17001. // MOV s3, ebp
  17002. // MOV dst, [s3 + 5 * sizeof(Var) + s2] // s3 = last argument
  17003. // $Done
  17004. IR::Opnd * dstOpnd = instrInsert->GetDst();
  17005. Assert(dstOpnd->IsRegOpnd());
  17006. LowererMD::CreateAssign(dstOpnd, opndUndefAddress, instrInsert);
  17007. IR::SymOpnd* callInfoOpnd = Lowerer::LoadCallInfo(instrInsert);
  17008. Assert(Js::CallInfo::ksizeofCount == 24);
  17009. IR::RegOpnd* isNewFlagSetRegOpnd = IR::RegOpnd::New(TyUint32, func);
  17010. InsertAnd(isNewFlagSetRegOpnd, callInfoOpnd, IR::IntConstOpnd::New((IntConstType)Js::CallFlags_NewTarget << Js::CallInfo::ksizeofCount, TyUint32, func, true), instrInsert);
  17011. InsertTestBranch(isNewFlagSetRegOpnd, isNewFlagSetRegOpnd, Js::OpCode::BrNeq_A, labelLoadArgNewTarget, instrInsert);
  17012. InsertAnd(isNewFlagSetRegOpnd, callInfoOpnd, IR::IntConstOpnd::New((IntConstType)Js::CallFlags_New << Js::CallInfo::ksizeofCount, TyUint32, func, true), instrInsert);
  17013. GenerateNotZeroTest(isNewFlagSetRegOpnd, labelDone, instrInsert);
  17014. IR::Instr* loadFuncInstr = IR::Instr::New(Js::OpCode::AND, func);
  17015. loadFuncInstr->SetDst(instrInsert->GetDst());
  17016. m_lowererMD.LoadFuncExpression(loadFuncInstr);
  17017. instrInsert->InsertBefore(loadFuncInstr);
  17018. InsertBranch(Js::OpCode::Br, labelDone, instrInsert);
  17019. instrInsert->InsertBefore(labelLoadArgNewTarget);
  17020. IR::RegOpnd* argCountOpnd = isNewFlagSetRegOpnd;
  17021. InsertAnd(argCountOpnd, callInfoOpnd, IR::IntConstOpnd::New(0x00FFFFFF, TyUint32, func, true), instrInsert);
  17022. IR::RegOpnd *baseOpnd = IR::RegOpnd::New(TyMachReg, func);
  17023. StackSym *paramSym = StackSym::New(TyMachReg, this->m_func);
  17024. instrInsert->InsertBefore(this->m_lowererMD.LoadStackAddress(paramSym, baseOpnd));
  17025. const BYTE indirScale = this->m_lowererMD.GetDefaultIndirScale();
  17026. IR::IndirOpnd* argIndirOpnd = IR::IndirOpnd::New(baseOpnd->AsRegOpnd(), argCountOpnd, indirScale, TyMachReg, this->m_func);
  17027. // Need to offset valueOpnd by 5. Instead of changing valueOpnd, we can just add an offset to the indir. Changing
  17028. // valueOpnd requires creation of a temp sym (if it's not already a temp) so that the value of the sym that
  17029. // valueOpnd represents is not changed.
  17030. uint16 actualOffset = GetFormalParamOffset() + 1; //5
  17031. argIndirOpnd->SetOffset(actualOffset << indirScale);
  17032. LowererMD::CreateAssign(dstOpnd, argIndirOpnd, instrInsert);
  17033. instrInsert->InsertBefore(labelDone);
  17034. instrInsert->Remove();
  17035. }
  17036. void
  17037. Lowerer::GenerateGetCurrentFunctionObject(IR::Instr * instr)
  17038. {
  17039. Func * func = this->m_func;
  17040. IR::Instr * insertBeforeInstr = instr->m_next;
  17041. IR::RegOpnd * functionObjectOpnd = instr->GetDst()->AsRegOpnd();
  17042. IR::Opnd * vtableAddressOpnd = this->LoadVTableValueOpnd(insertBeforeInstr, VTableValue::VtableStackScriptFunction);
  17043. IR::LabelInstr * labelDone = IR::LabelInstr::New(Js::OpCode::Label, func, false);
  17044. InsertCompareBranch(IR::IndirOpnd::New(functionObjectOpnd, 0, TyMachPtr, func), vtableAddressOpnd,
  17045. Js::OpCode::BrNeq_A, true, labelDone, insertBeforeInstr);
  17046. IR::RegOpnd * boxedFunctionObjectOpnd = IR::RegOpnd::New(TyMachPtr, func);
  17047. InsertMove(boxedFunctionObjectOpnd, IR::IndirOpnd::New(functionObjectOpnd,
  17048. Js::StackScriptFunction::GetOffsetOfBoxedScriptFunction(), TyMachPtr, func), insertBeforeInstr);
  17049. InsertTestBranch(boxedFunctionObjectOpnd, boxedFunctionObjectOpnd, Js::OpCode::BrEq_A, true, labelDone, insertBeforeInstr);
  17050. InsertMove(functionObjectOpnd, boxedFunctionObjectOpnd, insertBeforeInstr);
  17051. insertBeforeInstr->InsertBefore(labelDone);
  17052. }
  17053. IR::Opnd *
  17054. Lowerer::GetInlineCacheFromFuncObjectForRuntimeUse(IR::Instr * instr, IR::PropertySymOpnd * propSymOpnd, bool isHelper)
  17055. {
  17056. // MOV s1, [ebp + 8] //s1 = function object
  17057. // MOV s2, [s1 + offset(hasInlineCaches)]
  17058. // TEST s2, s2
  17059. // JE $L1
  17060. // MOV s3, [s1 + offset(m_inlineCaches)] //s3 = inlineCaches from function object
  17061. // MOV s4, [s3 + index*scale] //s4 = inlineCaches[index]
  17062. // JMP $L2
  17063. // $L1
  17064. // MOV s3, propSym->m_runtimeCache
  17065. // $L2
  17066. byte indirScale = this->m_lowererMD.GetDefaultIndirScale();
  17067. IR::RegOpnd * funcObjOpnd = IR::RegOpnd::New(TyMachPtr, this->m_func);
  17068. IR::Instr * funcObjInstr = IR::Instr::New(Js::OpCode::Ld_A, funcObjOpnd, instr->m_func);
  17069. instr->InsertBefore(funcObjInstr);
  17070. this->m_lowererMD.LoadFuncExpression(funcObjInstr);
  17071. IR::RegOpnd * funcObjHasInlineCachesOpnd = IR::RegOpnd::New(TyMachPtr, instr->m_func);
  17072. this->m_lowererMD.CreateAssign(funcObjHasInlineCachesOpnd, IR::IndirOpnd::New(funcObjOpnd, Js::ScriptFunction::GetOffsetOfHasInlineCaches(), TyUint8, instr->m_func), instr);
  17073. IR::LabelInstr * inlineCachesNullLabel = IR::LabelInstr::New(Js::OpCode::Label, instr->m_func, isHelper);
  17074. InsertTestBranch(funcObjHasInlineCachesOpnd, funcObjHasInlineCachesOpnd, Js::OpCode::BrEq_A, inlineCachesNullLabel, instr);
  17075. IR::RegOpnd * inlineCachesOpnd = IR::RegOpnd::New(TyMachPtr, instr->m_func);
  17076. Lowerer::InsertMove(inlineCachesOpnd, IR::IndirOpnd::New(funcObjOpnd, Js::ScriptFunctionWithInlineCache::GetOffsetOfInlineCaches(), TyMachPtr, instr->m_func), instr);
  17077. IR::RegOpnd * inlineCacheOpnd = IR::RegOpnd::New(TyMachPtr, instr->m_func);
  17078. IR::RegOpnd * indexOpnd = IR::RegOpnd::New(TyMachReg, instr->m_func);
  17079. int inlineCacheOffset;
  17080. if (!Int32Math::Mul(sizeof(Js::InlineCache *), propSymOpnd->m_inlineCacheIndex, &inlineCacheOffset))
  17081. {
  17082. Lowerer::InsertMove(inlineCacheOpnd, IR::IndirOpnd::New(inlineCachesOpnd, inlineCacheOffset, TyMachPtr, instr->m_func), instr);
  17083. }
  17084. else
  17085. {
  17086. Lowerer::InsertMove(indexOpnd, IR::IntConstOpnd::New(propSymOpnd->m_inlineCacheIndex, TyUint32, instr->m_func), instr);
  17087. Lowerer::InsertMove(inlineCacheOpnd, IR::IndirOpnd::New(inlineCachesOpnd, indexOpnd, indirScale, TyMachPtr, instr->m_func), instr);
  17088. }
  17089. IR::LabelInstr * continueLabel = IR::LabelInstr::New(Js::OpCode::Label, instr->m_func, isHelper);
  17090. InsertBranch(LowererMD::MDUncondBranchOpcode, continueLabel, instr);
  17091. IR::Instr * ldCacheFromPropSymOpndInstr = this->m_lowererMD.CreateAssign(inlineCacheOpnd, IR::AddrOpnd::New(propSymOpnd->m_runtimeInlineCache, IR::AddrOpndKindDynamicInlineCache, this->m_func), instr);
  17092. ldCacheFromPropSymOpndInstr->InsertBefore(inlineCachesNullLabel);
  17093. ldCacheFromPropSymOpndInstr->InsertAfter(continueLabel);
  17094. return inlineCacheOpnd;
  17095. }
  17096. IR::Instr *
  17097. Lowerer::LowerInitClass(IR::Instr * instr)
  17098. {
  17099. // scriptContext
  17100. IR::Instr * prevInstr = LoadScriptContext(instr);
  17101. // extends
  17102. if (instr->GetSrc2() != nullptr)
  17103. {
  17104. IR::Opnd * extendsOpnd = instr->UnlinkSrc2();
  17105. m_lowererMD.LoadHelperArgument(instr, extendsOpnd);
  17106. }
  17107. else
  17108. {
  17109. IR::AddrOpnd* extendsOpnd = IR::AddrOpnd::NewNull(this->m_func);
  17110. m_lowererMD.LoadHelperArgument(instr, extendsOpnd);
  17111. }
  17112. // constructor
  17113. IR::Opnd * ctorOpnd = instr->UnlinkSrc1();
  17114. m_lowererMD.LoadHelperArgument(instr, ctorOpnd);
  17115. // call
  17116. m_lowererMD.ChangeToHelperCall(instr, IR::HelperOP_InitClass);
  17117. return prevInstr;
  17118. }
  17119. void
  17120. Lowerer::LowerNewConcatStrMulti(IR::Instr * instr)
  17121. {
  17122. IR::IntConstOpnd * countOpnd = instr->UnlinkSrc1()->AsIntConstOpnd();
  17123. IR::RegOpnd * dstOpnd = instr->UnlinkDst()->AsRegOpnd();
  17124. uint8 count = (uint8)countOpnd->GetValue();
  17125. Assert(dstOpnd->GetValueType().IsString());
  17126. GenerateRecyclerAlloc(IR::HelperAllocMemForConcatStringMulti, Js::ConcatStringMulti::GetAllocSize(count), dstOpnd, instr);
  17127. GenerateRecyclerMemInit(dstOpnd, 0, this->LoadVTableValueOpnd(instr, VTableValue::VtableConcatStringMulti), instr);
  17128. GenerateRecyclerMemInit(dstOpnd, Js::ConcatStringMulti::GetOffsetOfType(),
  17129. this->LoadLibraryValueOpnd(instr, LibraryValue::ValueStringTypeStatic), instr);
  17130. GenerateRecyclerMemInitNull(dstOpnd, Js::ConcatStringMulti::GetOffsetOfpszValue(), instr);
  17131. GenerateRecyclerMemInit(dstOpnd, Js::ConcatStringMulti::GetOffsetOfcharLength(), 0, instr);
  17132. GenerateRecyclerMemInit(dstOpnd, Js::ConcatStringMulti::GetOffsetOfSlotCount(), countOpnd->AsUint32(), instr);
  17133. instr->Remove();
  17134. }
  17135. void
  17136. Lowerer::LowerNewConcatStrMultiBE(IR::Instr * instr)
  17137. {
  17138. // Lower
  17139. // t1 = SetConcatStrMultiBE s1
  17140. // t2 = SetConcatStrMultiBE s2, t1
  17141. // t3 = SetConcatStrMultiBE s3, t2
  17142. // s = NewConcatStrMultiBE 3, t3
  17143. // to
  17144. // s = new concat string
  17145. // s+0 = s1
  17146. // s+1 = s2
  17147. // s+2 = s3
  17148. Assert(instr->GetSrc1()->IsConstOpnd());
  17149. Assert(instr->GetDst()->IsRegOpnd());
  17150. IR::RegOpnd * newString = instr->GetDst()->AsRegOpnd();
  17151. IR::Opnd * newConcatItemOpnd = nullptr;
  17152. uint index = instr->GetSrc1()->AsIntConstOpnd()->AsUint32() - 1;
  17153. IR::Instr * concatItemInstr = nullptr;
  17154. IR::Opnd * linkOpnd = instr->GetSrc2();
  17155. while (linkOpnd)
  17156. {
  17157. Assert(linkOpnd->IsRegOpnd());
  17158. concatItemInstr = linkOpnd->GetStackSym()->GetInstrDef();
  17159. Assert(concatItemInstr->m_opcode == Js::OpCode::SetConcatStrMultiItemBE);
  17160. IR::Opnd * concatItemOpnd = concatItemInstr->GetSrc1();
  17161. Assert(concatItemOpnd->IsRegOpnd());
  17162. // If one of the concat items is equal to the dst of the concat expressions (s = s + a + b),
  17163. // hoist the load of that item to before the setting of the new string to the dst.
  17164. if (concatItemOpnd->IsEqual(newString))
  17165. {
  17166. if (!newConcatItemOpnd)
  17167. {
  17168. IR::Instr * hoistSrcInstr = concatItemInstr->HoistSrc1(Js::OpCode::Ld_A);
  17169. newConcatItemOpnd = hoistSrcInstr->GetDst();
  17170. }
  17171. concatItemOpnd = newConcatItemOpnd;
  17172. }
  17173. else
  17174. {
  17175. // If only some of the SetConcatStrMultiItemBE instructions were CSE'd and the rest, along with the NewConcatStrMultiBE
  17176. // instruction, were in a loop, the strings on the CSE'd Set*BE instructions will become live on back edge. Add them to
  17177. // addToLiveOnBackEdgeSyms here and clear when we reach the Set*BE instruction.
  17178. // Note that we are doing this only for string opnds which are not the same as the dst of the concat expression. Reasoning
  17179. // behind this is that if a loop has a concat expression with one of its sources same as the dst, the Set*BE instruction
  17180. // for the dst wouldn't have been CSE'd as the dst's value is changing in the loop and the backward pass should have set the
  17181. // symbol as live on backedge.
  17182. this->addToLiveOnBackEdgeSyms->Set(concatItemOpnd->GetStackSym()->m_id);
  17183. }
  17184. IR::Instr * newConcatItemInstr = IR::Instr::New(Js::OpCode::SetConcatStrMultiItem,
  17185. IR::IndirOpnd::New(newString, index, TyVar, instr->m_func),
  17186. concatItemOpnd,
  17187. instr->m_func);
  17188. instr->InsertAfter(newConcatItemInstr);
  17189. this->LowerSetConcatStrMultiItem(newConcatItemInstr);
  17190. linkOpnd = concatItemInstr->GetSrc2();
  17191. index--;
  17192. }
  17193. Assert(index == -1);
  17194. this->LowerNewConcatStrMulti(instr);
  17195. }
  17196. void
  17197. Lowerer::LowerSetConcatStrMultiItem(IR::Instr * instr)
  17198. {
  17199. Func * func = this->m_func;
  17200. IR::IndirOpnd * dstOpnd = instr->GetDst()->AsIndirOpnd();
  17201. IR::RegOpnd * concatStrOpnd = dstOpnd->GetBaseOpnd();
  17202. IR::RegOpnd * srcOpnd = instr->UnlinkSrc1()->AsRegOpnd();
  17203. Assert(concatStrOpnd->GetValueType().IsString());
  17204. Assert(srcOpnd->GetValueType().IsString());
  17205. srcOpnd = GenerateGetImmutableOrScriptUnreferencedString(srcOpnd, instr, IR::HelperOp_CompoundStringCloneForConcat);
  17206. instr->SetSrc1(srcOpnd);
  17207. IR::IndirOpnd * dstLength = IR::IndirOpnd::New(concatStrOpnd, Js::ConcatStringMulti::GetOffsetOfcharLength(), TyUint32, func);
  17208. IR::Opnd * srcLength;
  17209. if (srcOpnd->m_sym->m_isStrConst)
  17210. {
  17211. srcLength = IR::IntConstOpnd::New(Js::JavascriptString::FromVar(srcOpnd->m_sym->GetConstAddress())->GetLength(),
  17212. TyUint32, func);
  17213. }
  17214. else
  17215. {
  17216. srcLength = IR::RegOpnd::New(TyUint32, func);
  17217. InsertMove(srcLength, IR::IndirOpnd::New(srcOpnd, Js::ConcatStringMulti::GetOffsetOfcharLength(), TyUint32, func), instr);
  17218. }
  17219. InsertAdd(false, dstLength, dstLength, srcLength, instr);
  17220. dstOpnd->SetOffset(dstOpnd->GetOffset() * sizeof(Js::JavascriptString *) + Js::ConcatStringMulti::GetOffsetOfSlots());
  17221. this->m_lowererMD.ChangeToAssign(instr);
  17222. }
  17223. IR::RegOpnd *
  17224. Lowerer::GenerateGetImmutableOrScriptUnreferencedString(IR::RegOpnd * strOpnd, IR::Instr * insertBeforeInstr, IR::JnHelperMethod helperMethod, bool reloadDst)
  17225. {
  17226. if (strOpnd->m_sym->m_isStrConst)
  17227. {
  17228. return strOpnd;
  17229. }
  17230. Func * const func = this->m_func;
  17231. IR::RegOpnd *dstOpnd = reloadDst == true ? IR::RegOpnd::New(TyVar, func) : strOpnd;
  17232. IR::LabelInstr * helperLabel = IR::LabelInstr::New(Js::OpCode::Label, func, true);
  17233. IR::LabelInstr * doneLabel = IR::LabelInstr::New(Js::OpCode::Label, func);
  17234. if (!strOpnd->IsNotTaggedValue())
  17235. {
  17236. this->m_lowererMD.GenerateObjectTest(strOpnd, insertBeforeInstr, doneLabel);
  17237. }
  17238. // CMP [strOpnd], Js::CompoundString::`vtable'
  17239. // JEQ $helper
  17240. InsertCompareBranch(
  17241. IR::IndirOpnd::New(strOpnd, 0, TyMachPtr, func),
  17242. this->LoadVTableValueOpnd(insertBeforeInstr, VTableValue::VtableCompoundString),
  17243. Js::OpCode::BrEq_A,
  17244. helperLabel,
  17245. insertBeforeInstr);
  17246. if (reloadDst)
  17247. {
  17248. InsertMove(dstOpnd, strOpnd, insertBeforeInstr);
  17249. }
  17250. InsertBranch(Js::OpCode::Br, doneLabel, insertBeforeInstr);
  17251. insertBeforeInstr->InsertBefore(helperLabel);
  17252. this->m_lowererMD.LoadHelperArgument(insertBeforeInstr, strOpnd);
  17253. IR::Instr* callInstr = IR::Instr::New(Js::OpCode::Call, dstOpnd, func);
  17254. callInstr->SetSrc1(IR::HelperCallOpnd::New(helperMethod, func));
  17255. insertBeforeInstr->InsertBefore(callInstr);
  17256. this->m_lowererMD.LowerCall(callInstr, 0);
  17257. insertBeforeInstr->InsertBefore(doneLabel);
  17258. return dstOpnd;
  17259. }
  17260. void
  17261. Lowerer::LowerConvStrCommon(IR::JnHelperMethod helper, IR::Instr * instr)
  17262. {
  17263. IR::RegOpnd * src1Opnd = instr->UnlinkSrc1()->AsRegOpnd();
  17264. if (!src1Opnd->GetValueType().IsNotString())
  17265. {
  17266. IR::LabelInstr * helperLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func, true);
  17267. IR::LabelInstr * doneLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  17268. this->GenerateStringTest(src1Opnd, instr, helperLabel);
  17269. InsertMove(instr->GetDst(), src1Opnd, instr);
  17270. InsertBranch(Js::OpCode::Br, doneLabel, instr);
  17271. instr->InsertBefore(helperLabel);
  17272. instr->InsertAfter(doneLabel);
  17273. }
  17274. if (instr->GetSrc2())
  17275. {
  17276. this->m_lowererMD.LoadHelperArgument(instr, instr->UnlinkSrc2());
  17277. }
  17278. this->LoadScriptContext(instr);
  17279. this->m_lowererMD.LoadHelperArgument(instr, src1Opnd);
  17280. this->m_lowererMD.ChangeToHelperCall(instr, helper);
  17281. }
  17282. void
  17283. Lowerer::LowerConvStr(IR::Instr * instr)
  17284. {
  17285. LowerConvStrCommon(IR::HelperOp_ConvString, instr);
  17286. }
  17287. void
  17288. Lowerer::LowerCoerseStr(IR::Instr* instr)
  17289. {
  17290. LowerConvStrCommon(IR::HelperOp_CoerseString, instr);
  17291. }
  17292. ///----------------------------------------------------------------------------
  17293. ///
  17294. /// Lowerer::LowerCoerseStrOrRegex - This method is used for String.Replace(arg1, arg2)
  17295. /// where arg1 is regex or string
  17296. /// if arg1 is not regex, then do String.Replace(CoerseStr(arg1), arg2);
  17297. ///
  17298. /// CoerseStrOrRegex arg1
  17299. ///
  17300. /// if (value == regex) goto :done
  17301. /// else
  17302. ///helper:
  17303. /// ConvStr value
  17304. ///done:
  17305. ///----------------------------------------------------------------------------
  17306. void
  17307. Lowerer::LowerCoerseStrOrRegex(IR::Instr* instr)
  17308. {
  17309. IR::RegOpnd * src1Opnd = instr->GetSrc1()->AsRegOpnd();
  17310. IR::LabelInstr * helperLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func, true);
  17311. IR::LabelInstr * doneLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  17312. // if (value == regex) goto :done
  17313. if (!src1Opnd->IsNotTaggedValue())
  17314. {
  17315. this->m_lowererMD.GenerateObjectTest(src1Opnd, instr, helperLabel);
  17316. }
  17317. IR::Opnd * vtableOpnd = LoadVTableValueOpnd(instr, VTableValue::VtableJavascriptRegExp);
  17318. InsertCompareBranch(IR::IndirOpnd::New(src1Opnd, 0, TyMachPtr, instr->m_func),
  17319. vtableOpnd, Js::OpCode::BrNeq_A, helperLabel, instr);
  17320. InsertMove(instr->GetDst(), src1Opnd, instr);
  17321. InsertBranch(Js::OpCode::Br, doneLabel, instr);
  17322. instr->InsertBefore(helperLabel);
  17323. instr->InsertAfter(doneLabel);
  17324. // helper: ConvStr value
  17325. LowerConvStr(instr);
  17326. }
  17327. ///----------------------------------------------------------------------------
  17328. ///
  17329. /// Lowerer::LowerCoerseRegex - This method is used for String.Match(arg1)
  17330. /// if arg1 is regex, then pass CreateRegEx(arg1) to String.Match
  17331. ///
  17332. ///----------------------------------------------------------------------------
  17333. void
  17334. Lowerer::LowerCoerseRegex(IR::Instr* instr)
  17335. {
  17336. IR::LabelInstr * helperLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func, true);
  17337. IR::LabelInstr * doneLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  17338. IR::RegOpnd * src1Opnd = instr->UnlinkSrc1()->AsRegOpnd();
  17339. if (!src1Opnd->IsNotTaggedValue())
  17340. {
  17341. this->m_lowererMD.GenerateObjectTest(src1Opnd, instr, helperLabel);
  17342. }
  17343. IR::Opnd * vtableOpnd = LoadVTableValueOpnd(instr, VTableValue::VtableJavascriptRegExp);
  17344. InsertCompareBranch(IR::IndirOpnd::New(src1Opnd, 0, TyMachPtr, instr->m_func),
  17345. vtableOpnd, Js::OpCode::BrNeq_A, helperLabel, instr);
  17346. InsertMove(instr->GetDst(), src1Opnd, instr);
  17347. InsertBranch(Js::OpCode::Br, doneLabel, instr);
  17348. instr->InsertBefore(helperLabel);
  17349. instr->InsertAfter(doneLabel);
  17350. this->LoadScriptContext(instr);
  17351. this->m_lowererMD.LoadHelperArgument(instr, IR::AddrOpnd::NewNull(instr->m_func)); // option
  17352. this->m_lowererMD.LoadHelperArgument(instr, src1Opnd); // regex
  17353. this->m_lowererMD.ChangeToHelperCall(instr, IR::HelperOp_CoerseRegex);
  17354. }
  17355. void
  17356. Lowerer::LowerConvPrimStr(IR::Instr * instr)
  17357. {
  17358. LowerConvStrCommon(IR::HelperOp_ConvPrimitiveString, instr);
  17359. }
  17360. void
  17361. Lowerer::GenerateRecyclerAlloc(IR::JnHelperMethod allocHelper, size_t allocSize, IR::RegOpnd* newObjDst, IR::Instr* insertionPointInstr, bool inOpHelper)
  17362. {
  17363. size_t alignedSize = HeapInfo::GetAlignedSizeNoCheck(allocSize);
  17364. this->GenerateRecyclerAllocAligned(allocHelper, alignedSize, newObjDst, insertionPointInstr, inOpHelper);
  17365. }
  17366. void
  17367. Lowerer::GenerateMemInit(IR::RegOpnd * opnd, int32 offset, int value, IR::Instr * insertBeforeInstr, bool isZeroed)
  17368. {
  17369. IRType type = TyInt32;
  17370. if (isZeroed)
  17371. {
  17372. if (value == 0)
  17373. {
  17374. // Recycler memory are zero initialized
  17375. return;
  17376. }
  17377. if (value > 0 && value <= USHORT_MAX)
  17378. {
  17379. // Recycler memory are zero initialized, so we can just initialize the 8 or 16 bits of value
  17380. type = (value <= UCHAR_MAX)? TyUint8 : TyUint16;
  17381. }
  17382. }
  17383. Func * func = this->m_func;
  17384. InsertMove(IR::IndirOpnd::New(opnd, offset, type, func), IR::IntConstOpnd::New(value, type, func), insertBeforeInstr);
  17385. }
  17386. void
  17387. Lowerer::GenerateMemInit(IR::RegOpnd * opnd, int32 offset, uint32 value, IR::Instr * insertBeforeInstr, bool isZeroed)
  17388. {
  17389. IRType type = TyUint32;
  17390. if (isZeroed)
  17391. {
  17392. if (value == 0)
  17393. {
  17394. // Recycler memory are zero initialized
  17395. return;
  17396. }
  17397. if (value <= USHORT_MAX)
  17398. {
  17399. // Recycler memory are zero initialized, so we can just initialize the 8 or 16 bits of value
  17400. type = (value <= UCHAR_MAX)? TyUint8 : TyUint16;
  17401. }
  17402. }
  17403. Func * func = this->m_func;
  17404. InsertMove(IR::IndirOpnd::New(opnd, offset, type, func), IR::IntConstOpnd::New(value, type, func), insertBeforeInstr);
  17405. }
  17406. void
  17407. Lowerer::GenerateMemInitNull(IR::RegOpnd * opnd, int32 offset, IR::Instr * insertBeforeInstr, bool isZeroed)
  17408. {
  17409. if (isZeroed)
  17410. {
  17411. return;
  17412. }
  17413. GenerateMemInit(opnd, offset, IR::AddrOpnd::NewNull(m_func), insertBeforeInstr);
  17414. }
  17415. void
  17416. Lowerer::GenerateMemInit(IR::RegOpnd * opnd, int32 offset, IR::Opnd * value, IR::Instr * insertBeforeInstr, bool isZeroed)
  17417. {
  17418. IRType type = value->GetType();
  17419. Func * func = this->m_func;
  17420. InsertMove(IR::IndirOpnd::New(opnd, offset, type, func), value, insertBeforeInstr);
  17421. }
  17422. void
  17423. Lowerer::GenerateRecyclerMemInit(IR::RegOpnd * opnd, int32 offset, int32 value, IR::Instr * insertBeforeInstr)
  17424. {
  17425. GenerateMemInit(opnd, offset, value, insertBeforeInstr, true);
  17426. }
  17427. void
  17428. Lowerer::GenerateRecyclerMemInit(IR::RegOpnd * opnd, int32 offset, uint32 value, IR::Instr * insertBeforeInstr)
  17429. {
  17430. GenerateMemInit(opnd, offset, value, insertBeforeInstr, true);
  17431. }
  17432. void
  17433. Lowerer::GenerateRecyclerMemInitNull(IR::RegOpnd * opnd, int32 offset, IR::Instr * insertBeforeInstr)
  17434. {
  17435. GenerateMemInitNull(opnd, offset, insertBeforeInstr, true);
  17436. }
  17437. void
  17438. Lowerer::GenerateRecyclerMemInit(IR::RegOpnd * opnd, int32 offset, IR::Opnd * value, IR::Instr * insertBeforeInstr)
  17439. {
  17440. GenerateMemInit(opnd, offset, value, insertBeforeInstr, true);
  17441. }
  17442. void
  17443. Lowerer::GenerateMemCopy(IR::Opnd * dst, IR::Opnd * src, uint32 size, IR::Instr * insertBeforeInstr)
  17444. {
  17445. Func * func = this->m_func;
  17446. this->m_lowererMD.LoadHelperArgument(insertBeforeInstr, IR::IntConstOpnd::New(size, TyUint32, func));
  17447. this->m_lowererMD.LoadHelperArgument(insertBeforeInstr, src);
  17448. this->m_lowererMD.LoadHelperArgument(insertBeforeInstr, dst);
  17449. IR::Instr * memcpyInstr = IR::Instr::New(Js::OpCode::Call, func);
  17450. memcpyInstr->SetSrc1(IR::HelperCallOpnd::New(IR::HelperMemCpy, func));
  17451. insertBeforeInstr->InsertBefore(memcpyInstr);
  17452. m_lowererMD.LowerCall(memcpyInstr, 3);
  17453. }
  17454. bool
  17455. Lowerer::GenerateSimplifiedInt4Rem(
  17456. IR::Instr *const remInstr,
  17457. IR::LabelInstr *const skipBailOutLabel) const
  17458. {
  17459. Assert(remInstr);
  17460. Assert(remInstr->m_opcode == Js::OpCode::Rem_I4);
  17461. auto *dst = remInstr->GetDst(), *src1 = remInstr->GetSrc1(), *src2 = remInstr->GetSrc2();
  17462. Assert(src1 && src2);
  17463. Assert(dst->IsRegOpnd());
  17464. bool isModByPowerOf2 = (remInstr->HasBailOutInfo() && remInstr->GetBailOutKind() == IR::BailOnModByPowerOf2);
  17465. if (PHASE_OFF(Js::Phase::MathFastPathPhase, remInstr->m_func->GetTopFunc()) && !isModByPowerOf2)
  17466. return false;
  17467. if (!(src2->IsIntConstOpnd() && Math::IsPow2(src2->AsIntConstOpnd()->AsInt32())) && !isModByPowerOf2)
  17468. {
  17469. return false;
  17470. }
  17471. // We have:
  17472. // s3 = s1 % s2 , where s2 = +2^i
  17473. //
  17474. // Generate:
  17475. // test s1, s1
  17476. // js $slowPathLabel
  17477. // s3 = and s1, 0x00..fff (2^i - 1)
  17478. // jmp $doneLabel
  17479. // $slowPathLabel:
  17480. // (Slow path)
  17481. // (Neg zero check)
  17482. // (Bailout code)
  17483. // $doneLabel:
  17484. IR::LabelInstr *doneLabel = skipBailOutLabel, *slowPathLabel;
  17485. if (!doneLabel)
  17486. {
  17487. doneLabel = IR::LabelInstr::New(Js::OpCode::Label, remInstr->m_func);
  17488. remInstr->InsertAfter(doneLabel);
  17489. }
  17490. slowPathLabel = IR::LabelInstr::New(Js::OpCode::Label, remInstr->m_func, isModByPowerOf2);
  17491. remInstr->InsertBefore(slowPathLabel);
  17492. // test s1, s1
  17493. InsertTest(src1, src1, slowPathLabel);
  17494. // jsb $slowPathLabel
  17495. InsertBranch(LowererMD::MDCompareWithZeroBranchOpcode(Js::OpCode::BrLt_A), slowPathLabel, slowPathLabel);
  17496. // s3 = and s1, 0x00..fff (2^i - 1)
  17497. IR::Opnd* maskOpnd;
  17498. if(isModByPowerOf2)
  17499. {
  17500. Assert(isModByPowerOf2);
  17501. maskOpnd = IR::RegOpnd::New(TyInt32, remInstr->m_func);
  17502. // mov maskOpnd, s2
  17503. InsertMove(maskOpnd, src2, slowPathLabel);
  17504. // dec maskOpnd
  17505. InsertSub(/*needFlags*/ true, maskOpnd, maskOpnd, IR::IntConstOpnd::New(1, TyInt32, this->m_func, /*dontEncode*/true), slowPathLabel);
  17506. // maskOpnd < 0 goto $slowPath
  17507. InsertBranch(LowererMD::MDCompareWithZeroBranchOpcode(Js::OpCode::BrLt_A), slowPathLabel, slowPathLabel);
  17508. // TEST src2, maskOpnd
  17509. InsertTestBranch(src2, maskOpnd, Js::OpCode::BrNeq_A, slowPathLabel, slowPathLabel);
  17510. }
  17511. else
  17512. {
  17513. Assert(src2->IsIntConstOpnd());
  17514. int32 mask = src2->AsIntConstOpnd()->AsInt32() - 1;
  17515. maskOpnd = IR::IntConstOpnd::New(mask, TyInt32, remInstr->m_func);
  17516. }
  17517. // dst = src1 & maskOpnd
  17518. InsertAnd(dst, src1, maskOpnd, slowPathLabel);
  17519. // jmp $doneLabel
  17520. InsertBranch(Js::OpCode::Br, doneLabel, slowPathLabel);
  17521. return true;
  17522. }
  17523. #if DBG
  17524. bool
  17525. Lowerer::ValidOpcodeAfterLower(IR::Instr* instr, Func * func)
  17526. {
  17527. Js::OpCode opcode = instr->m_opcode;
  17528. if (opcode > Js::OpCode::MDStart)
  17529. {
  17530. return true;
  17531. }
  17532. switch (opcode)
  17533. {
  17534. case Js::OpCode::Label:
  17535. case Js::OpCode::StatementBoundary:
  17536. case Js::OpCode::DeletedNonHelperBranch:
  17537. case Js::OpCode::FunctionEntry:
  17538. case Js::OpCode::FunctionExit:
  17539. case Js::OpCode::TryCatch:
  17540. case Js::OpCode::TryFinally:
  17541. case Js::OpCode::Catch:
  17542. case Js::OpCode::GeneratorResumeJumpTable:
  17543. case Js::OpCode::Break:
  17544. #ifdef _M_X64
  17545. case Js::OpCode::PrologStart:
  17546. case Js::OpCode::PrologEnd:
  17547. #endif
  17548. #ifdef _M_IX86
  17549. case Js::OpCode::BailOutStackRestore:
  17550. #endif
  17551. return true;
  17552. case Js::OpCode::RestoreOutParam:
  17553. Assert(func->isPostRegAlloc);
  17554. return true;
  17555. // These may be removed by peep
  17556. case Js::OpCode::StartCall:
  17557. case Js::OpCode::LoweredStartCall:
  17558. case Js::OpCode::Nop:
  17559. case Js::OpCode::ArgOut_A_InlineBuiltIn:
  17560. return func && !func->isPostPeeps;
  17561. case Js::OpCode::InlineeStart:
  17562. case Js::OpCode::InlineeEnd:
  17563. return instr->m_func->m_hasInlineArgsOpt;
  17564. #ifdef _M_X64
  17565. case Js::OpCode::LdArgSize:
  17566. case Js::OpCode::LdSpillSize:
  17567. return func && !func->isPostFinalLower;
  17568. #endif
  17569. case Js::OpCode::Leave:
  17570. Assert(!func->IsLoopBodyInTry());
  17571. Assert(func->HasTry() && func->DoOptimizeTryCatch());
  17572. return func && !func->isPostFinalLower; //Lowered in FinalLower phase
  17573. };
  17574. return false;
  17575. }
  17576. #endif
  17577. void Lowerer::LowerProfiledBeginSwitch(IR::JitProfilingInstr* instr)
  17578. {
  17579. Assert(instr->isBeginSwitch);
  17580. m_lowererMD.LoadHelperArgument(instr, instr->UnlinkSrc1());
  17581. m_lowererMD.LoadHelperArgument(instr, IR::Opnd::CreateProfileIdOpnd(instr->profileId, m_func));
  17582. m_lowererMD.LoadHelperArgument(instr, CreateFunctionBodyOpnd(instr->m_func));
  17583. instr->SetSrc1(IR::HelperCallOpnd::New(IR::HelperSimpleProfiledSwitch, m_func));
  17584. m_lowererMD.LowerCall(instr, 0);
  17585. }
  17586. void Lowerer::LowerProfiledBinaryOp(IR::JitProfilingInstr* instr, IR::JnHelperMethod meth)
  17587. {
  17588. m_lowererMD.LoadHelperArgument(instr, instr->UnlinkSrc2());
  17589. m_lowererMD.LoadHelperArgument(instr, instr->UnlinkSrc1());
  17590. m_lowererMD.LoadHelperArgument(instr, IR::Opnd::CreateProfileIdOpnd(instr->profileId, m_func));
  17591. m_lowererMD.LoadHelperArgument(instr, CreateFunctionBodyOpnd(instr->m_func));
  17592. instr->SetSrc1(IR::HelperCallOpnd::New(meth, m_func));
  17593. m_lowererMD.LowerCall(instr, 0);
  17594. }
  17595. void Lowerer::GenerateNullOutGeneratorFrame(IR::Instr* insertInstr)
  17596. {
  17597. // null out frame pointer on generator object to signal completion to JavascriptGenerator::CallGenerator
  17598. // s = MOV prm1
  17599. // s[offset of JavascriptGenerator::frame] = MOV nullptr
  17600. StackSym *symSrc = StackSym::NewParamSlotSym(1, m_func);
  17601. m_func->SetArgOffset(symSrc, LowererMD::GetFormalParamOffset() * MachPtr);
  17602. IR::SymOpnd *srcOpnd = IR::SymOpnd::New(symSrc, TyMachPtr, m_func);
  17603. IR::RegOpnd *dstOpnd = IR::RegOpnd::New(TyMachReg, m_func);
  17604. m_lowererMD.CreateAssign(dstOpnd, srcOpnd, insertInstr);
  17605. IR::IndirOpnd *indirOpnd = IR::IndirOpnd::New(dstOpnd, Js::JavascriptGenerator::GetFrameOffset(), TyMachPtr, m_func);
  17606. IR::AddrOpnd *addrOpnd = IR::AddrOpnd::NewNull(m_func);
  17607. m_lowererMD.CreateAssign(indirOpnd, addrOpnd, insertInstr);
  17608. }
  17609. void Lowerer::LowerFunctionExit(IR::Instr* funcExit)
  17610. {
  17611. if (m_func->GetJnFunction()->IsGenerator())
  17612. {
  17613. GenerateNullOutGeneratorFrame(funcExit->m_prev);
  17614. }
  17615. if (!m_func->DoSimpleJitDynamicProfile())
  17616. {
  17617. return;
  17618. }
  17619. IR::Instr* callInstr = IR::Instr::New(Js::OpCode::Call, m_func);
  17620. callInstr->SetSrc1(IR::HelperCallOpnd::New(IR::HelperSimpleCleanImplicitCallFlags, m_func));
  17621. funcExit->m_prev->InsertBefore(callInstr);
  17622. m_lowererMD.LoadHelperArgument(callInstr, CreateFunctionBodyOpnd(funcExit->m_func));
  17623. m_lowererMD.LowerCall(callInstr, 0);
  17624. }
  17625. void Lowerer::LowerFunctionEntry(IR::Instr* funcEntry)
  17626. {
  17627. Assert(funcEntry->m_opcode == Js::OpCode::FunctionEntry);
  17628. //Don't do a body call increment for loops or asm.js
  17629. if (m_func->IsLoopBody() || m_func->GetJnFunction()->GetIsAsmjsMode())
  17630. {
  17631. return;
  17632. }
  17633. IR::Instr *const insertBeforeInstr = this->m_func->GetFunctionEntryInsertionPoint();
  17634. LowerFunctionBodyCallCountChange(insertBeforeInstr);
  17635. if (m_func->DoSimpleJitDynamicProfile())
  17636. {
  17637. const auto jn = m_func->GetJnFunction();
  17638. // Only generate the argument profiling if the function expects to have some arguments to profile and only if
  17639. // it has implicit ArgIns (the latter is a restriction imposed by the Interpreter, so it is mirrored in SimpleJit)
  17640. if (jn->GetInParamsCount() > 1 && jn->GetHasImplicitArgIns())
  17641. {
  17642. // Call out to the argument profiling helper
  17643. IR::Instr* callInstr = IR::Instr::New(Js::OpCode::Call, m_func);
  17644. callInstr->SetSrc1(IR::HelperCallOpnd::New(IR::HelperSimpleProfileParameters, m_func));
  17645. insertBeforeInstr->InsertBefore(callInstr);
  17646. m_lowererMD.LoadHelperArgument(callInstr, IR::Opnd::CreateFramePointerOpnd(m_func));
  17647. m_lowererMD.LowerCall(callInstr, 0);
  17648. }
  17649. // Clear existing ImplicitCallFlags
  17650. const auto starFlag = GetImplicitCallFlagsOpnd();
  17651. this->InsertMove(starFlag, CreateClearImplicitCallFlagsOpnd(), insertBeforeInstr);
  17652. }
  17653. }
  17654. void Lowerer::LowerFunctionBodyCallCountChange(IR::Instr *const insertBeforeInstr)
  17655. {
  17656. Assert(insertBeforeInstr);
  17657. Func *const func = insertBeforeInstr->m_func;
  17658. const bool isSimpleJit = func->IsSimpleJit();
  17659. if ((isSimpleJit && !func->GetTopFunc()->GetJnFunction()->DoFullJit()))
  17660. {
  17661. return;
  17662. }
  17663. // mov countAddress, <countAddress>
  17664. IR::RegOpnd *const countAddressOpnd = IR::RegOpnd::New(StackSym::New(TyMachPtr, func), TyMachPtr, func);
  17665. const IR::AutoReuseOpnd autoReuseCountAddressOpnd(countAddressOpnd, func);
  17666. InsertMove(
  17667. countAddressOpnd,
  17668. IR::AddrOpnd::New(func->GetCallsCountAddress(), IR::AddrOpndKindDynamicMisc, func, true),
  17669. insertBeforeInstr);
  17670. IR::IndirOpnd *const countOpnd = IR::IndirOpnd::New(countAddressOpnd, 0, TyUint8, func);
  17671. const IR::AutoReuseOpnd autoReuseCountOpnd(countOpnd, func);
  17672. if(!isSimpleJit)
  17673. {
  17674. // InsertIncUint8PreventOverflow [countAddress]
  17675. InsertIncUInt8PreventOverflow(countOpnd, countOpnd, insertBeforeInstr);
  17676. return;
  17677. }
  17678. // InsertDecUint8PreventOverflow [countAddress]
  17679. IR::Instr *onOverflowInsertBeforeInstr;
  17680. InsertDecUInt8PreventOverflow(
  17681. countOpnd,
  17682. countOpnd,
  17683. insertBeforeInstr,
  17684. &onOverflowInsertBeforeInstr);
  17685. // ($overflow:)
  17686. // TransitionFromSimpleJit(framePointer)
  17687. m_lowererMD.LoadHelperArgument(onOverflowInsertBeforeInstr, IR::Opnd::CreateFramePointerOpnd(func));
  17688. IR::Instr *const callInstr = IR::Instr::New(Js::OpCode::Call, func);
  17689. callInstr->SetSrc1(IR::HelperCallOpnd::New(IR::HelperTransitionFromSimpleJit, func));
  17690. onOverflowInsertBeforeInstr->InsertBefore(callInstr);
  17691. m_lowererMD.LowerCall(callInstr, 0);
  17692. }
  17693. IR::Opnd*
  17694. Lowerer::GetImplicitCallFlagsOpnd()
  17695. {
  17696. return GetImplicitCallFlagsOpnd(m_func);
  17697. }
  17698. IR::Opnd*
  17699. Lowerer::GetImplicitCallFlagsOpnd(Func * func)
  17700. {
  17701. return IR::MemRefOpnd::New(func->GetScriptContext()->GetThreadContext()->GetAddressOfImplicitCallFlags(), GetImplicitCallFlagsType(), func);
  17702. }
  17703. IR::Opnd*
  17704. Lowerer::CreateClearImplicitCallFlagsOpnd()
  17705. {
  17706. return IR::IntConstOpnd::New(Js::ImplicitCall_None, GetImplicitCallFlagsType(), m_func);
  17707. }
  17708. void
  17709. Lowerer::LowerSpreadArrayLiteral(IR::Instr *instr)
  17710. {
  17711. LoadScriptContext(instr);
  17712. IR::Opnd *src2Opnd = instr->UnlinkSrc2();
  17713. m_lowererMD.LoadHelperArgument(instr, src2Opnd);
  17714. IR::Opnd *src1Opnd = instr->UnlinkSrc1();
  17715. m_lowererMD.LoadHelperArgument(instr, src1Opnd);
  17716. this->m_lowererMD.ChangeToHelperCall(instr, IR::HelperSpreadArrayLiteral);
  17717. }
  17718. IR::Instr *
  17719. Lowerer::LowerSpreadCall(IR::Instr *instr, Js::CallFlags callFlags, bool setupProfiledVersion)
  17720. {
  17721. // Get the target function object, and emit function object test.
  17722. IR::RegOpnd * functionObjOpnd = instr->UnlinkSrc1()->AsRegOpnd();
  17723. functionObjOpnd->m_isCallArg = true;
  17724. if (!(callFlags & Js::CallFlags_New) && !setupProfiledVersion)
  17725. {
  17726. IR::LabelInstr* continueAfterExLabel = InsertContinueAfterExceptionLabelForDebugger(m_func, instr, false);
  17727. this->m_lowererMD.GenerateFunctionObjectTest(instr, functionObjOpnd, false, continueAfterExLabel);
  17728. }
  17729. IR::Instr *spreadIndicesInstr;
  17730. spreadIndicesInstr = GetLdSpreadIndicesInstr(instr);
  17731. Assert(spreadIndicesInstr->m_opcode == Js::OpCode::LdSpreadIndices);
  17732. // Get AuxArray
  17733. IR::Opnd *spreadIndicesOpnd = spreadIndicesInstr->UnlinkSrc1();
  17734. // Remove LdSpreadIndices from the argument chain
  17735. instr->ReplaceSrc2(spreadIndicesInstr->UnlinkSrc2());
  17736. // Emit the normal args
  17737. callFlags = (Js::CallFlags)(callFlags | (instr->GetDst() ? Js::CallFlags_Value : Js::CallFlags_NotUsed));
  17738. // Profiled helper call requires three more parameters, ArrayProfileId, profileId, and the frame pointer.
  17739. // This is just following the convention of HelperProfiledNewScObjArray call.
  17740. const unsigned short extraArgsCount = setupProfiledVersion ? 5 : 2; // function object and AuxArray
  17741. int32 argCount = this->m_lowererMD.LowerCallArgs(instr, (ushort)callFlags, extraArgsCount);
  17742. // Emit our extra (first) args for the Spread helper in reverse order
  17743. if (setupProfiledVersion)
  17744. {
  17745. IR::JitProfilingInstr* jitInstr = (IR::JitProfilingInstr*)instr;
  17746. m_lowererMD.LoadHelperArgument(instr, IR::Opnd::CreateProfileIdOpnd(jitInstr->arrayProfileId, m_func));
  17747. m_lowererMD.LoadHelperArgument(instr, IR::Opnd::CreateProfileIdOpnd(jitInstr->profileId, m_func));
  17748. m_lowererMD.LoadHelperArgument(instr, IR::Opnd::CreateFramePointerOpnd(m_func));
  17749. }
  17750. m_lowererMD.LoadHelperArgument(instr, functionObjOpnd);
  17751. m_lowererMD.LoadHelperArgument(instr, spreadIndicesOpnd);
  17752. // Change the call target to our helper
  17753. IR::HelperCallOpnd *helperOpnd = IR::HelperCallOpnd::New(setupProfiledVersion ? IR::HelperProfiledNewScObjArraySpread : IR::HelperSpreadCall, this->m_func);
  17754. instr->SetSrc1(helperOpnd);
  17755. return this->m_lowererMD.LowerCall(instr, (Js::ArgSlot)argCount);
  17756. }
  17757. void
  17758. Lowerer::LowerDivI4Common(IR::Instr * instr)
  17759. {
  17760. Assert(instr);
  17761. Assert(instr->m_opcode == Js::OpCode::Rem_I4 || instr->m_opcode == Js::OpCode::Div_I4);
  17762. Assert(m_func->GetJnFunction()->GetIsAsmjsMode());
  17763. // MIN_INT/-1 path is only needed for signed operations
  17764. // TEST src2, src2
  17765. // JEQ $div0
  17766. // CMP src1, MIN_INT
  17767. // JEQ $minInt
  17768. // JMP $div
  17769. // $div0: [helper]
  17770. // MOV dst, 0
  17771. // JMP $done
  17772. // $minInt: [helper]
  17773. // CMP src2, -1
  17774. // JNE $div
  17775. // dst = MOV src1 / 0
  17776. // JMP $done
  17777. // $div:
  17778. // dst = IDIV src2, src1
  17779. // $done:
  17780. IR::LabelInstr * div0Label = InsertLabel(true, instr);
  17781. IR::LabelInstr * divLabel = InsertLabel(false, instr);
  17782. IR::LabelInstr * doneLabel = InsertLabel(false, instr->m_next);
  17783. InsertTestBranch(instr->GetSrc2(), instr->GetSrc2(), Js::OpCode::BrEq_A, div0Label, div0Label);
  17784. InsertMove(instr->GetDst(), IR::IntConstOpnd::New(0, TyInt32, m_func), divLabel);
  17785. InsertBranch(Js::OpCode::Br, doneLabel, divLabel);
  17786. if (instr->GetSrc1()->GetType() == TyInt32)
  17787. {
  17788. IR::LabelInstr * minIntLabel = nullptr;
  17789. // we need to check for INT_MIN/-1 if divisor is either -1 or variable, and dividend is either INT_MIN or variable
  17790. bool needsMinOverNeg1Check = !(instr->GetSrc2()->IsIntConstOpnd() && instr->GetSrc2()->AsIntConstOpnd()->GetValue() != -1);
  17791. if (instr->GetSrc1()->IsIntConstOpnd())
  17792. {
  17793. if (needsMinOverNeg1Check && instr->GetSrc1()->AsIntConstOpnd()->GetValue() == INT_MIN)
  17794. {
  17795. minIntLabel = InsertLabel(true, divLabel);
  17796. InsertBranch(Js::OpCode::Br, minIntLabel, div0Label);
  17797. }
  17798. else
  17799. {
  17800. needsMinOverNeg1Check = false;
  17801. }
  17802. }
  17803. else if(needsMinOverNeg1Check)
  17804. {
  17805. minIntLabel = InsertLabel(true, divLabel);
  17806. InsertCompareBranch(instr->GetSrc1(), IR::IntConstOpnd::New(INT_MIN, TyInt32, m_func), Js::OpCode::BrEq_A, minIntLabel, div0Label);
  17807. }
  17808. if (needsMinOverNeg1Check)
  17809. {
  17810. Assert(minIntLabel);
  17811. Assert(!instr->GetSrc2()->IsIntConstOpnd() || instr->GetSrc2()->AsIntConstOpnd()->GetValue() == -1);
  17812. if (!instr->GetSrc2()->IsIntConstOpnd())
  17813. {
  17814. InsertCompareBranch(instr->GetSrc2(), IR::IntConstOpnd::New(-1, TyInt32, m_func), Js::OpCode::BrNeq_A, divLabel, divLabel);
  17815. }
  17816. InsertMove(instr->GetDst(), instr->m_opcode == Js::OpCode::Div_I4 ? instr->GetSrc1() : IR::IntConstOpnd::New(0, TyInt32, m_func), divLabel);
  17817. InsertBranch(Js::OpCode::Br, doneLabel, divLabel);
  17818. }
  17819. }
  17820. InsertBranch(Js::OpCode::Br, divLabel, div0Label);
  17821. m_lowererMD.EmitInt4Instr(instr);
  17822. }
  17823. void
  17824. Lowerer::LowerRemI4(IR::Instr * instr)
  17825. {
  17826. Assert(instr);
  17827. Assert(instr->m_opcode == Js::OpCode::Rem_I4);
  17828. if (m_func->GetJnFunction()->GetIsAsmjsMode())
  17829. {
  17830. LowerDivI4Common(instr);
  17831. }
  17832. else
  17833. {
  17834. m_lowererMD.EmitInt4Instr(instr);
  17835. }
  17836. }
  17837. void
  17838. Lowerer::LowerDivI4(IR::Instr * instr)
  17839. {
  17840. Assert(instr);
  17841. Assert(instr->m_opcode == Js::OpCode::Div_I4);
  17842. if (m_func->GetJnFunction()->GetIsAsmjsMode())
  17843. {
  17844. LowerDivI4Common(instr);
  17845. return;
  17846. }
  17847. if(!instr->HasBailOutInfo())
  17848. {
  17849. m_lowererMD.EmitInt4Instr(instr);
  17850. return;
  17851. }
  17852. Assert(!(instr->GetBailOutKind() & ~(IR::BailOnDivResultNotInt | IR::BailOutOnNegativeZero | IR::BailOutOnDivByZero | IR::BailOutOnDivOfMinInt)));
  17853. IR::BailOutKind bailOutKind = instr->GetBailOutKind();
  17854. // Split out and generate the bailout instruction
  17855. const auto nonBailOutInstr = IR::Instr::New(instr->m_opcode, instr->m_func);
  17856. instr->TransferTo(nonBailOutInstr);
  17857. instr->InsertBefore(nonBailOutInstr);
  17858. IR::LabelInstr * doneLabel = IR::LabelInstr::New(Js::OpCode::Label, instr->m_func);
  17859. instr->InsertAfter(doneLabel);
  17860. // Generate the bailout helper call. 'instr' will be changed to the CALL into the bailout function, so it can't be used for
  17861. // ordering instructions anymore.
  17862. IR::LabelInstr * bailOutLabel = GenerateBailOut(instr);
  17863. IR::Opnd * denominatorOpnd = nonBailOutInstr->GetSrc2();
  17864. IR::Opnd * nominatorOpnd = nonBailOutInstr->GetSrc1();
  17865. if (bailOutKind & IR::BailOutOnDivOfMinInt)
  17866. {
  17867. // Bailout if numerator is MIN_INT (could also check for denominator being -1
  17868. // before bailing out, but does not seem worth the extra code..)
  17869. InsertCompareBranch(nominatorOpnd, IR::IntConstOpnd::New(INT32_MIN, TyInt32, this->m_func, true), Js::OpCode::BrEq_A, bailOutLabel, nonBailOutInstr);
  17870. }
  17871. if (denominatorOpnd->IsIntConstOpnd() && Math::IsPow2(denominatorOpnd->AsIntConstOpnd()->AsInt32()))
  17872. {
  17873. Assert((bailOutKind & (IR::BailOutOnNegativeZero | IR::BailOutOnDivByZero)) == 0);
  17874. int pow2 = denominatorOpnd->AsIntConstOpnd()->AsInt32();
  17875. InsertTestBranch(nominatorOpnd, IR::IntConstOpnd::New(pow2 - 1, TyInt32, this->m_func, true),
  17876. Js::OpCode::BrNeq_A, bailOutLabel, nonBailOutInstr);
  17877. nonBailOutInstr->m_opcode = Js::OpCode::Shr_A;
  17878. nonBailOutInstr->ReplaceSrc2(IR::IntConstOpnd::New(Math::Log2(pow2), TyInt32, this->m_func, true));
  17879. LowererMD::ChangeToShift(nonBailOutInstr, false);
  17880. LowererMD::Legalize(nonBailOutInstr);
  17881. }
  17882. else
  17883. {
  17884. if (bailOutKind & IR::BailOutOnDivByZero)
  17885. {
  17886. // Bailout if denominator is 0
  17887. InsertTestBranch(denominatorOpnd, denominatorOpnd, Js::OpCode::BrEq_A, bailOutLabel, nonBailOutInstr);
  17888. }
  17889. // Lower the div and bailout if there is a reminder (machine specific)
  17890. IR::Instr * insertBeforeInstr = m_lowererMD.LowerDivI4AndBailOnReminder(nonBailOutInstr, bailOutLabel);
  17891. IR::Opnd * resultOpnd = nonBailOutInstr->GetDst();
  17892. if (bailOutKind & IR::BailOutOnNegativeZero)
  17893. {
  17894. // TEST result, result
  17895. // JNE skipNegDenominatorCheckLabel // Result not 0
  17896. // TEST denominator, denominator
  17897. // JNSB/BMI bailout // bail if negative
  17898. // skipNegDenominatorCheckLabel:
  17899. IR::LabelInstr * skipNegDenominatorCheckLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  17900. // Skip negative denominator check if the result is not 0
  17901. InsertTestBranch(resultOpnd, resultOpnd, Js::OpCode::BrNeq_A, skipNegDenominatorCheckLabel, insertBeforeInstr);
  17902. IR::LabelInstr * negDenominatorCheckLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func, true);
  17903. insertBeforeInstr->InsertBefore(negDenominatorCheckLabel);
  17904. // Jump to done if the denominator is not negative
  17905. InsertTestBranch(denominatorOpnd, denominatorOpnd,
  17906. LowererMD::MDCompareWithZeroBranchOpcode(Js::OpCode::BrLt_A), bailOutLabel, insertBeforeInstr);
  17907. insertBeforeInstr->InsertBefore(skipNegDenominatorCheckLabel);
  17908. }
  17909. }
  17910. // We are all fine, jump around the bailout to done
  17911. InsertBranch(Js::OpCode::Br, doneLabel, bailOutLabel);
  17912. }
  17913. void
  17914. Lowerer::LowerRemR8(IR::Instr * instr)
  17915. {
  17916. Assert(instr);
  17917. Assert(instr->m_opcode == Js::OpCode::Rem_A);
  17918. Assert(m_func->GetJnFunction()->GetIsAsmjsMode());
  17919. m_lowererMD.LoadDoubleHelperArgument(instr, instr->UnlinkSrc2());
  17920. m_lowererMD.LoadDoubleHelperArgument(instr, instr->UnlinkSrc1());
  17921. instr->SetSrc1(IR::HelperCallOpnd::New(IR::JnHelperMethod::HelperOp_Rem_Double, m_func));
  17922. m_lowererMD.LowerCall(instr, 0);
  17923. }
  17924. void
  17925. Lowerer::LowerNewScopeSlots(IR::Instr * instr, bool doStackSlots)
  17926. {
  17927. Func * func = m_func;
  17928. if (PHASE_OFF(Js::NewScopeSlotFastPathPhase, func))
  17929. {
  17930. this->LowerUnaryHelperMemWithFuncBody(instr, IR::HelperOP_NewScopeSlots);
  17931. return;
  17932. }
  17933. uint const count = instr->GetSrc1()->AsIntConstOpnd()->AsUint32();
  17934. uint const allocSize = count * sizeof(Js::Var);
  17935. uint const actualSlotCount = count - Js::ScopeSlots::FirstSlotIndex;
  17936. IR::RegOpnd * dst = instr->UnlinkDst()->AsRegOpnd();
  17937. // dst = RecyclerAlloc(allocSize)
  17938. // dst[EncodedSlotCountSlotIndex = EncodedSlotCountSlotIOndex];
  17939. // dst[ScopeMetadataSlotIndex] = FunctionBody;
  17940. // mov undefinedOpnd, undefined
  17941. // dst[FirstSlotIndex..count] = undefinedOpnd;
  17942. // Note: stack allocation of both scope slots and frame display are done together
  17943. // in lowering of NewStackFrameDisplay
  17944. if (!doStackSlots)
  17945. {
  17946. GenerateRecyclerAlloc(IR::HelperAllocMemForVarArray, allocSize, dst, instr);
  17947. }
  17948. GenerateMemInit(dst, Js::ScopeSlots::EncodedSlotCountSlotIndex * sizeof(Js::Var),
  17949. min<uint>(actualSlotCount, Js::ScopeSlots::MaxEncodedSlotCount), instr, !doStackSlots);
  17950. IR::Opnd * functionBodyOpnd = this->LoadFunctionBodyOpnd(instr);
  17951. GenerateMemInit(dst, Js::ScopeSlots::ScopeMetadataSlotIndex * sizeof(Js::Var),
  17952. functionBodyOpnd, instr, !doStackSlots);
  17953. IR::Opnd * undefinedOpnd = this->LoadLibraryValueOpnd(instr, LibraryValue::ValueUndefined);
  17954. const IR::AutoReuseOpnd autoReuseUndefinedOpnd(undefinedOpnd, func);
  17955. // avoid using a register for the undefined pointer if we are going to assign 1 or 2
  17956. if (actualSlotCount > 2 && !undefinedOpnd->IsRegOpnd())
  17957. {
  17958. // mov undefinedOpnd, undefined
  17959. IR::RegOpnd * regOpnd = IR::RegOpnd::New(TyVar, func);
  17960. InsertMove(regOpnd, undefinedOpnd, instr);
  17961. undefinedOpnd = regOpnd;
  17962. }
  17963. int const loopUnrollCount = 8;
  17964. if (actualSlotCount <= loopUnrollCount * 2)
  17965. {
  17966. // Just generate all the assignment in straight line code
  17967. // mov[dst + Js::FirstSlotIndex], undefinedOpnd
  17968. // ...
  17969. // mov[dst + count - 1], undefinedOpnd
  17970. for (unsigned int i = Js::ScopeSlots::FirstSlotIndex; i < count; i++)
  17971. {
  17972. GenerateMemInit(dst, sizeof(Js::Var) * i, undefinedOpnd, instr, !doStackSlots);
  17973. }
  17974. }
  17975. else
  17976. {
  17977. // Just generate all the assignment in loop of loopUnroolCount and the rest as straight line code
  17978. //
  17979. // lea currOpnd, [dst + sizeof(Var) * (loopAssignCount + Js::ScopeSlots::FirstSlotIndex - loopUnrollCount)];
  17980. // mov [currOpnd + loopUnrollCount + leftOverAssignCount - 1] , undefinedOpnd
  17981. // mov [currOpnd + loopUnrollCount + leftOverAssignCount - 2] , undefinedOpnd
  17982. // ...
  17983. // mov [currOpnd + loopUnrollCount], undefinedOpnd
  17984. // $LoopTop:
  17985. // mov [currOpnd + loopUnrollCount - 1], undefinedOpnd
  17986. // mov [currOpnd + loopUnrollCount - 2], undefinedOpnd
  17987. // ...
  17988. // mov [currOpnd], undefinedOpnd
  17989. // lea currOpnd, [currOpnd - loopUnrollCount]
  17990. // cmp dst, currOpnd
  17991. // jlt $Looptop
  17992. uint nLoop = actualSlotCount / loopUnrollCount;
  17993. uint loopAssignCount = nLoop * loopUnrollCount;
  17994. uint leftOverAssignCount = actualSlotCount - loopAssignCount; // The left over assignments
  17995. IR::RegOpnd * currOpnd = IR::RegOpnd::New(TyMachPtr, func);
  17996. const IR::AutoReuseOpnd autoReuseCurrOpnd(currOpnd, m_func);
  17997. InsertLea(
  17998. currOpnd,
  17999. IR::IndirOpnd::New(
  18000. dst,
  18001. sizeof(Js::Var) * (loopAssignCount + Js::ScopeSlots::FirstSlotIndex - loopUnrollCount),
  18002. TyMachPtr,
  18003. func),
  18004. instr);
  18005. for (unsigned int i = 0; i < leftOverAssignCount; i++)
  18006. {
  18007. GenerateMemInit(currOpnd, sizeof(Js::Var) * (loopUnrollCount + leftOverAssignCount - i - 1), undefinedOpnd, instr, !doStackSlots);
  18008. }
  18009. IR::LabelInstr * loopTop = IR::LabelInstr::New(Js::OpCode::Label, func);
  18010. instr->InsertBefore(loopTop);
  18011. loopTop->m_isLoopTop = true;
  18012. Loop *loop = JitAnew(func->m_alloc, Loop, func->m_alloc, this->m_func);
  18013. loopTop->SetLoop(loop);
  18014. loop->SetLoopTopInstr(loopTop);
  18015. loop->regAlloc.liveOnBackEdgeSyms = JitAnew(func->m_alloc, BVSparse<JitArenaAllocator>, func->m_alloc);
  18016. for (unsigned int i = 0; i < loopUnrollCount; i++)
  18017. {
  18018. GenerateMemInit(currOpnd, sizeof(Js::Var) * (loopUnrollCount - i - 1), undefinedOpnd, instr, !doStackSlots);
  18019. }
  18020. InsertLea(currOpnd, IR::IndirOpnd::New(currOpnd, -((int)sizeof(Js::Var) * loopUnrollCount), TyMachPtr, func), instr);
  18021. InsertCompareBranch(dst, currOpnd, Js::OpCode::BrLt_A, true, loopTop, instr);
  18022. loop->regAlloc.liveOnBackEdgeSyms->Set(currOpnd->m_sym->m_id);
  18023. loop->regAlloc.liveOnBackEdgeSyms->Set(dst->m_sym->m_id);
  18024. loop->regAlloc.liveOnBackEdgeSyms->Set(undefinedOpnd->AsRegOpnd()->m_sym->m_id);
  18025. }
  18026. if (!doStackSlots)
  18027. {
  18028. InsertMove(IR::RegOpnd::New(instr->m_func->GetLocalClosureSym(), TyMachPtr, func), dst, instr);
  18029. }
  18030. instr->Remove();
  18031. }
  18032. void Lowerer::LowerLdInnerFrameDisplay(IR::Instr *instr)
  18033. {
  18034. bool isStrict = instr->m_func->GetJnFunction()->GetIsStrictMode();
  18035. if (isStrict)
  18036. {
  18037. if (instr->GetSrc2())
  18038. {
  18039. this->LowerBinaryHelperMem(instr, IR::HelperScrObj_LdStrictInnerFrameDisplay);
  18040. }
  18041. else
  18042. {
  18043. #if DBG
  18044. instr->m_opcode = Js::OpCode::LdInnerFrameDisplayNoParent;
  18045. #endif
  18046. this->LowerUnaryHelperMem(instr, IR::HelperScrObj_LdStrictInnerFrameDisplayNoParent);
  18047. }
  18048. }
  18049. else
  18050. {
  18051. if (instr->GetSrc2())
  18052. {
  18053. this->LowerBinaryHelperMem(instr, IR::HelperScrObj_LdInnerFrameDisplay);
  18054. }
  18055. else
  18056. {
  18057. #if DBG
  18058. instr->m_opcode = Js::OpCode::LdInnerFrameDisplayNoParent;
  18059. #endif
  18060. this->LowerUnaryHelperMem(instr, IR::HelperScrObj_LdInnerFrameDisplayNoParent);
  18061. }
  18062. }
  18063. }
  18064. void Lowerer::LowerLdFrameDisplay(IR::Instr *instr, bool doStackFrameDisplay)
  18065. {
  18066. bool isStrict = instr->m_func->GetJnFunction()->GetIsStrictMode();
  18067. uint16 envDepth = instr->m_func->GetJnFunction()->GetEnvDepth();
  18068. Func *func = this->m_func;
  18069. // envDepth of -1 indicates unknown depth (eval expression or HTML event handler).
  18070. // We could still fast-path these by generating a loop over the (dynamically loaded) scope chain length,
  18071. // but I doubt it's worth it.
  18072. // If the dst opnd is a byte code temp, that indicates we're prepending a block scope or some such and
  18073. // shouldn't attempt to do this.
  18074. if (envDepth == (uint16)-1 ||
  18075. (!doStackFrameDisplay && instr->GetDst()->AsRegOpnd()->m_sym->IsTempReg(instr->m_func)) ||
  18076. PHASE_OFF(Js::FrameDisplayFastPathPhase, func))
  18077. {
  18078. if (isStrict)
  18079. {
  18080. if (instr->GetSrc2())
  18081. {
  18082. this->LowerBinaryHelperMem(instr, IR::HelperScrObj_LdStrictFrameDisplay);
  18083. }
  18084. else
  18085. {
  18086. #if DBG
  18087. instr->m_opcode = Js::OpCode::LdFrameDisplayNoParent;
  18088. #endif
  18089. this->LowerUnaryHelperMem(instr, IR::HelperScrObj_LdStrictFrameDisplayNoParent);
  18090. }
  18091. }
  18092. else
  18093. {
  18094. if (instr->GetSrc2())
  18095. {
  18096. this->LowerBinaryHelperMem(instr, IR::HelperScrObj_LdFrameDisplay);
  18097. }
  18098. else
  18099. {
  18100. #if DBG
  18101. instr->m_opcode = Js::OpCode::LdFrameDisplayNoParent;
  18102. #endif
  18103. this->LowerUnaryHelperMem(instr, IR::HelperScrObj_LdFrameDisplayNoParent);
  18104. }
  18105. }
  18106. return;
  18107. }
  18108. uint16 frameDispLength = envDepth + 1;
  18109. Assert(frameDispLength > 0);
  18110. IR::RegOpnd *dstOpnd = instr->UnlinkDst()->AsRegOpnd();
  18111. IR::RegOpnd *currentFrameOpnd = instr->UnlinkSrc1()->AsRegOpnd();
  18112. uint allocSize = sizeof(Js::FrameDisplay) + (frameDispLength * sizeof(Js::Var));
  18113. if (doStackFrameDisplay)
  18114. {
  18115. IR::Instr *insertInstr = func->GetFunctionEntryInsertionPoint();
  18116. // Initialize stack pointers for scope slots and frame display together at the top of the function
  18117. // (in case we bail out before executing the instructions).
  18118. IR::LabelInstr *labelNoStackFunc = IR::LabelInstr::New(Js::OpCode::Label, m_func, true);
  18119. IR::LabelInstr *labelDone = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  18120. // Check whether stack functions have been disabled since we jitted.
  18121. // If they have, then we must allocate closure memory on the heap.
  18122. InsertTestBranch(IR::MemRefOpnd::New(m_func->GetJnFunction()->GetAddressOfFlags(), TyInt8, m_func),
  18123. IR::IntConstOpnd::New(Js::FunctionBody::Flags_StackNestedFunc, TyInt8, m_func, true),
  18124. Js::OpCode::BrEq_A, labelNoStackFunc, insertInstr);
  18125. // allocSize is greater than TyMachPtr and hence changing the initial size to TyMisc
  18126. StackSym * stackSym = StackSym::New(TyMisc, instr->m_func);
  18127. m_func->StackAllocate(stackSym, allocSize);
  18128. InsertLea(dstOpnd, IR::SymOpnd::New(stackSym, TyMachPtr, func), insertInstr);
  18129. uint scopeSlotAllocSize =
  18130. (m_func->GetJnFunction()->scopeSlotArraySize + Js::ScopeSlots::FirstSlotIndex) * sizeof(Js::Var);
  18131. stackSym = StackSym::New(TyMisc, instr->m_func);
  18132. m_func->StackAllocate(stackSym, scopeSlotAllocSize);
  18133. InsertLea(currentFrameOpnd, IR::SymOpnd::New(stackSym, TyMachPtr, func), insertInstr);
  18134. InsertBranch(Js::OpCode::Br, labelDone, insertInstr);
  18135. insertInstr->InsertBefore(labelNoStackFunc);
  18136. GenerateRecyclerAlloc(IR::HelperAllocMemForFrameDisplay, allocSize, dstOpnd, insertInstr, true);
  18137. GenerateRecyclerAlloc(IR::HelperAllocMemForVarArray, scopeSlotAllocSize, currentFrameOpnd, insertInstr, true);
  18138. insertInstr->InsertBefore(labelDone);
  18139. m_lowererMD.CreateAssign(IR::SymOpnd::New(m_func->GetLocalFrameDisplaySym(), 0, TyMachReg, m_func), dstOpnd, insertInstr);
  18140. m_lowererMD.CreateAssign(IR::SymOpnd::New(m_func->GetLocalClosureSym(), 0, TyMachReg, m_func), currentFrameOpnd, insertInstr);
  18141. }
  18142. else
  18143. {
  18144. GenerateRecyclerAlloc(IR::HelperAllocMemForFrameDisplay, allocSize, dstOpnd, instr);
  18145. }
  18146. // Copy contents of environment
  18147. // Work back to front to leave the head element(s) in cache
  18148. if (envDepth > 0)
  18149. {
  18150. IR::RegOpnd *envOpnd = instr->UnlinkSrc2()->AsRegOpnd();
  18151. for (uint16 i = envDepth; i >= 1; i--)
  18152. {
  18153. IR::Opnd *scopeOpnd = IR::RegOpnd::New(TyMachReg, func);
  18154. IR::Opnd *envLoadOpnd =
  18155. IR::IndirOpnd::New(envOpnd, Js::FrameDisplay::GetOffsetOfScopes() + ((i - 1) * sizeof(Js::Var)), TyMachReg, func);
  18156. m_lowererMD.CreateAssign(scopeOpnd, envLoadOpnd, instr);
  18157. IR::Opnd *dstStoreOpnd =
  18158. IR::IndirOpnd::New(dstOpnd, Js::FrameDisplay::GetOffsetOfScopes() + (i * sizeof(Js::Var)), TyMachReg, func);
  18159. m_lowererMD.CreateAssign(dstStoreOpnd, scopeOpnd, instr);
  18160. }
  18161. }
  18162. // Assign current element.
  18163. m_lowererMD.CreateAssign(
  18164. IR::IndirOpnd::New(dstOpnd, Js::FrameDisplay::GetOffsetOfScopes(), TyMachReg, func),
  18165. currentFrameOpnd,
  18166. instr);
  18167. // Combine tag, strict mode flag, and length
  18168. uintptr_t bits = 1 |
  18169. (isStrict << (Js::FrameDisplay::GetOffsetOfStrictMode() * 8)) |
  18170. (frameDispLength << (Js::FrameDisplay::GetOffsetOfLength() * 8));
  18171. m_lowererMD.CreateAssign(
  18172. IR::IndirOpnd::New(dstOpnd, 0, TyMachReg, func),
  18173. IR::AddrOpnd::New((void*)bits, IR::AddrOpndKindConstant, func, true),
  18174. instr);
  18175. instr->Remove();
  18176. }
  18177. IR::AddrOpnd *Lowerer::CreateFunctionBodyOpnd(Func *const func) const
  18178. {
  18179. return CreateFunctionBodyOpnd(func->GetJnFunction());
  18180. }
  18181. IR::AddrOpnd *Lowerer::CreateFunctionBodyOpnd(Js::FunctionBody *const functionBody) const
  18182. {
  18183. return IR::AddrOpnd::New(functionBody, IR::AddrOpndKindDynamicFunctionBody, m_func, true);
  18184. }
  18185. bool
  18186. Lowerer::GenerateRecyclerOrMarkTempAlloc(IR::Instr * instr, IR::RegOpnd * dstOpnd, IR::JnHelperMethod allocHelper, size_t allocSize, IR::SymOpnd ** tempObjectSymOpnd)
  18187. {
  18188. if (instr->dstIsTempObject)
  18189. {
  18190. *tempObjectSymOpnd = GenerateMarkTempAlloc(dstOpnd, allocSize, instr);
  18191. return false;
  18192. }
  18193. this->GenerateRecyclerAlloc(allocHelper, allocSize, dstOpnd, instr);
  18194. *tempObjectSymOpnd = nullptr;
  18195. return true;
  18196. }
  18197. IR::SymOpnd *
  18198. Lowerer::GenerateMarkTempAlloc(IR::RegOpnd *const dstOpnd, const size_t allocSize, IR::Instr *const insertBeforeInstr)
  18199. {
  18200. Assert(dstOpnd);
  18201. Assert(allocSize != 0);
  18202. Assert(insertBeforeInstr);
  18203. Func *const func = insertBeforeInstr->m_func;
  18204. // Allocate stack space for the reg exp instance, and a slot for the boxed value
  18205. StackSym *const tempObjectSym = StackSym::New(TyMisc, func);
  18206. m_func->StackAllocate(tempObjectSym, (int)(allocSize + sizeof(void *)));
  18207. IR::SymOpnd * tempObjectOpnd = IR::SymOpnd::New(tempObjectSym, sizeof(void *), TyVar, func);
  18208. InsertLea(dstOpnd, tempObjectOpnd, insertBeforeInstr);
  18209. // Initialize the boxed instance slot
  18210. if (this->outerMostLoopLabel == nullptr)
  18211. {
  18212. GenerateMemInit(dstOpnd, -(int)sizeof(void *), IR::AddrOpnd::NewNull(func), insertBeforeInstr, false);
  18213. }
  18214. else if (!PHASE_OFF(Js::HoistMarkTempInitPhase, this->m_func))
  18215. {
  18216. InsertMove(IR::SymOpnd::New(tempObjectSym, TyMachPtr, func), IR::AddrOpnd::NewNull(func), this->outerMostLoopLabel, false);
  18217. }
  18218. return tempObjectOpnd;
  18219. }
  18220. void Lowerer::LowerBrFncCachedScopeEq(IR::Instr *instr)
  18221. {
  18222. Assert(instr->m_opcode == Js::OpCode::BrFncCachedScopeEq || instr->m_opcode == Js::OpCode::BrFncCachedScopeNeq);
  18223. Js::OpCode opcode = (instr->m_opcode == Js::OpCode::BrFncCachedScopeEq ? Js::OpCode::BrEq_A : Js::OpCode::BrNeq_A);
  18224. IR::RegOpnd *src1Reg = instr->UnlinkSrc1()->AsRegOpnd();
  18225. IR::IndirOpnd *indirOpnd = IR::IndirOpnd::New(src1Reg, Js::ScriptFunction::GetOffsetOfCachedScopeObj(), TyMachReg, this->m_func);
  18226. this->InsertCompareBranch(indirOpnd, instr->UnlinkSrc2(), opcode, false, instr->AsBranchInstr()->GetTarget(), instr->m_next);
  18227. instr->Remove();
  18228. }
  18229. IR::Instr* Lowerer::InsertLoweredRegionStartMarker(IR::Instr* instrToInsertBefore)
  18230. {
  18231. AssertMsg(instrToInsertBefore->m_prev != nullptr, "Can't insert lowered region start marker as the first instr in the func.");
  18232. IR::LabelInstr* startMarkerLabel = IR::LabelInstr::New(Js::OpCode::Label, instrToInsertBefore->m_func);
  18233. instrToInsertBefore->InsertBefore(startMarkerLabel);
  18234. return startMarkerLabel;
  18235. }
  18236. IR::Instr* Lowerer::RemoveLoweredRegionStartMarker(IR::Instr* startMarkerInstr)
  18237. {
  18238. AssertMsg(startMarkerInstr->m_prev != nullptr, "Lowered region start marker became the first instruction in the func after lowering?");
  18239. IR::Instr* prevInstr = startMarkerInstr->m_prev;
  18240. startMarkerInstr->Remove();
  18241. return prevInstr;
  18242. }
  18243. IR::Instr* Lowerer::GetLdSpreadIndicesInstr(IR::Instr *instr)
  18244. {
  18245. IR::Opnd *src2 = instr->GetSrc2();
  18246. if (!src2->IsSymOpnd())
  18247. {
  18248. return nullptr;
  18249. }
  18250. IR::SymOpnd * argLinkOpnd = src2->AsSymOpnd();
  18251. StackSym * argLinkSym = argLinkOpnd->m_sym->AsStackSym();
  18252. Assert(argLinkSym->IsSingleDef());
  18253. return argLinkSym->m_instrDef;
  18254. }
  18255. bool Lowerer::IsSpreadCall(IR::Instr *instr)
  18256. {
  18257. IR::Instr *lastInstr = GetLdSpreadIndicesInstr(instr);
  18258. return lastInstr && lastInstr->m_opcode == Js::OpCode::LdSpreadIndices;
  18259. }
  18260. // When under debugger, generate a new label to be used as safe place to jump after ignore exception,
  18261. // insert it after insertAfterInstr, and return the label inserted.
  18262. // Returns nullptr/NoOP for non-debugger code path.
  18263. //static
  18264. IR::LabelInstr* Lowerer::InsertContinueAfterExceptionLabelForDebugger(Func* func, IR::Instr* insertAfterInstr, bool isHelper)
  18265. {
  18266. Assert(func);
  18267. Assert(insertAfterInstr);
  18268. IR::LabelInstr* continueAfterExLabel = nullptr;
  18269. if (func->IsJitInDebugMode())
  18270. {
  18271. continueAfterExLabel = IR::LabelInstr::New(Js::OpCode::Label, func, isHelper);
  18272. insertAfterInstr->InsertAfter(continueAfterExLabel);
  18273. }
  18274. return continueAfterExLabel;
  18275. }
  18276. void Lowerer::GenerateSingleCharStrJumpTableLookup(IR::Instr * instr)
  18277. {
  18278. IR::MultiBranchInstr * multiBrInstr = instr->AsBranchInstr()->AsMultiBrInstr();
  18279. Func * func = instr->m_func;
  18280. IR::LabelInstr * helperLabel = IR::LabelInstr::New(Js::OpCode::Label, func, true);
  18281. IR::LabelInstr * continueLabel = IR::LabelInstr::New(Js::OpCode::Label, func);
  18282. // MOV strLengthOpnd, str->length
  18283. IR::RegOpnd * strLengthOpnd = IR::RegOpnd::New(TyUint32, func);
  18284. InsertMove(strLengthOpnd, IR::IndirOpnd::New(instr->GetSrc1()->AsRegOpnd(), Js::JavascriptString::GetOffsetOfcharLength(), TyUint32, func), instr);
  18285. // CMP strLengthOpnd, 1
  18286. // JNE defaultLabel
  18287. IR::LabelInstr * defaultLabelInstr = (IR::LabelInstr *)multiBrInstr->GetBranchJumpTable()->defaultTarget;
  18288. InsertCompareBranch(strLengthOpnd, IR::IntConstOpnd::New(1, TyUint32, func), Js::OpCode::BrNeq_A, defaultLabelInstr, instr);
  18289. // MOV strBuffer, str->psz
  18290. IR::RegOpnd * strBufferOpnd = IR::RegOpnd::New(TyMachPtr, func);
  18291. InsertMove(strBufferOpnd, IR::IndirOpnd::New(instr->GetSrc1()->AsRegOpnd(), Js::JavascriptString::GetOffsetOfpszValue(), TyMachPtr, func), instr);
  18292. // TST strBuffer, strBuffer
  18293. // JNE $continue
  18294. InsertTestBranch(strBufferOpnd, strBufferOpnd, Js::OpCode::BrNeq_A, continueLabel, instr);
  18295. // $helper:
  18296. // PUSH str
  18297. // CALL JavascriptString::GetSzHelper
  18298. // MOV strBuffer, eax
  18299. // $continue:
  18300. instr->InsertBefore(helperLabel);
  18301. m_lowererMD.LoadHelperArgument(instr, instr->GetSrc1());
  18302. IR::Instr * instrCall = IR::Instr::New(Js::OpCode::Call, strBufferOpnd, IR::HelperCallOpnd::New(IR::HelperString_GetSz, func), func);
  18303. instr->InsertBefore(instrCall);
  18304. m_lowererMD.LowerCall(instrCall, 0);
  18305. instr->InsertBefore(continueLabel);
  18306. // MOV charOpnd, [strBuffer]
  18307. IR::RegOpnd * charOpnd = IR::RegOpnd::New(TyUint32, func);
  18308. InsertMove(charOpnd, IR::IndirOpnd::New(strBufferOpnd, 0, TyUint16, func), instr);
  18309. if (multiBrInstr->m_baseCaseValue != 0)
  18310. {
  18311. // SUB charOpnd, baseIndex
  18312. InsertSub(false, charOpnd, charOpnd, IR::IntConstOpnd::New(multiBrInstr->m_baseCaseValue, TyUint32, func), instr);
  18313. }
  18314. // CMP charOpnd, lastCaseIndex - baseCaseIndex
  18315. // JA defaultLabel
  18316. InsertCompareBranch(charOpnd, IR::IntConstOpnd::New(multiBrInstr->m_lastCaseValue - multiBrInstr->m_baseCaseValue, TyUint32, func, true),
  18317. Js::OpCode::BrGt_A, true, defaultLabelInstr, instr);
  18318. instr->UnlinkSrc1();
  18319. LowerJumpTableMultiBranch(multiBrInstr, charOpnd);
  18320. }
  18321. void Lowerer::GenerateSwitchStringLookup(IR::Instr * instr)
  18322. {
  18323. /* Collect information about string length in all the case*/
  18324. charcount_t minLength = UINT_MAX;
  18325. charcount_t maxLength = 0;
  18326. BVUnit32 bvLength;
  18327. instr->AsBranchInstr()->AsMultiBrInstr()->GetBranchDictionary()->dictionary.Map([&](Js::JavascriptString * str, void *)
  18328. {
  18329. charcount_t len = str->GetLength();
  18330. minLength = min(minLength, str->GetLength());
  18331. maxLength = max(maxLength, str->GetLength());
  18332. if (len < 32)
  18333. {
  18334. bvLength.Set(len);
  18335. }
  18336. });
  18337. Func * func = instr->m_func;
  18338. IR::RegOpnd * strLengthOpnd = IR::RegOpnd::New(TyUint32, func);
  18339. InsertMove(strLengthOpnd, IR::IndirOpnd::New(instr->GetSrc1()->AsRegOpnd(), Js::JavascriptString::GetOffsetOfcharLength(), TyUint32, func), instr);
  18340. IR::LabelInstr * defaultLabelInstr = (IR::LabelInstr *)instr->AsBranchInstr()->AsMultiBrInstr()->GetBranchDictionary()->defaultTarget;
  18341. if (minLength == maxLength)
  18342. {
  18343. // Generate single length filter
  18344. InsertCompareBranch(strLengthOpnd, IR::IntConstOpnd::New(minLength, TyUint32, func), Js::OpCode::BrNeq_A, defaultLabelInstr, instr);
  18345. }
  18346. else if (maxLength < 32)
  18347. {
  18348. // Generate bit filter
  18349. // Jump to default label if the bit is not on for the length % 32
  18350. IR::IntConstOpnd * lenBitMaskOpnd = IR::IntConstOpnd::New(bvLength.GetWord(), TyUint32, func);
  18351. InsertBitTestBranch(lenBitMaskOpnd, strLengthOpnd, false, defaultLabelInstr, instr);
  18352. // Jump to default label if the bit is > 32
  18353. InsertTestBranch(strLengthOpnd, IR::IntConstOpnd::New(UINT32_MAX ^ 31, TyUint32, func), Js::OpCode::BrNeq_A, defaultLabelInstr, instr);
  18354. }
  18355. else
  18356. {
  18357. // CONSIDER: Generate range filter
  18358. }
  18359. this->LowerMultiBr(instr, IR::HelperOp_SwitchStringLookUp);
  18360. }
  18361. IR::Instr *
  18362. Lowerer::LowerTry(IR::Instr* instr, bool tryCatch)
  18363. {
  18364. if (this->m_func->hasBailout)
  18365. {
  18366. this->EnsureBailoutReturnValueSym();
  18367. }
  18368. this->EnsureHasBailedOutSym();
  18369. IR::SymOpnd * hasBailedOutOpnd = IR::SymOpnd::New(this->m_func->m_hasBailedOutSym, TyUint32, this->m_func);
  18370. IR::Instr * setInstr = IR::Instr::New(LowererMD::GetStoreOp(TyUint32), hasBailedOutOpnd, IR::IntConstOpnd::New(0, TyUint32, this->m_func), this->m_func);
  18371. instr->InsertBefore(setInstr);
  18372. LowererMD::Legalize(setInstr);
  18373. return m_lowererMD.LowerTry(instr, tryCatch ? IR::HelperOp_TryCatch : IR::HelperOp_TryFinally);
  18374. }
  18375. void
  18376. Lowerer::EnsureBailoutReturnValueSym()
  18377. {
  18378. if (this->m_func->m_bailoutReturnValueSym == nullptr)
  18379. {
  18380. this->m_func->m_bailoutReturnValueSym = StackSym::New(TyVar, this->m_func);
  18381. this->m_func->StackAllocate(this->m_func->m_bailoutReturnValueSym, sizeof(Js::Var));
  18382. }
  18383. }
  18384. void
  18385. Lowerer::EnsureHasBailedOutSym()
  18386. {
  18387. if (this->m_func->m_hasBailedOutSym == nullptr)
  18388. {
  18389. this->m_func->m_hasBailedOutSym = StackSym::New(TyUint32, this->m_func);
  18390. this->m_func->StackAllocate(this->m_func->m_hasBailedOutSym, MachRegInt);
  18391. }
  18392. }
  18393. void
  18394. Lowerer::InsertReturnThunkForRegion(Region* region, IR::LabelInstr* restoreLabel)
  18395. {
  18396. Assert(this->m_func->isPostLayout);
  18397. Assert(region->GetType() == RegionTypeTry || region->GetType() == RegionTypeCatch);
  18398. if (!region->returnThunkEmitted)
  18399. {
  18400. this->m_func->m_exitInstr->InsertAfter(region->GetBailoutReturnThunkLabel());
  18401. bool newLastInstrInserted = false;
  18402. IR::Instr * insertBeforeInstr = region->GetBailoutReturnThunkLabel()->m_next;
  18403. if (insertBeforeInstr == nullptr)
  18404. {
  18405. Assert(this->m_func->m_exitInstr == this->m_func->m_tailInstr);
  18406. insertBeforeInstr = IR::Instr::New(Js::OpCode::Nop, this->m_func);
  18407. newLastInstrInserted = true;
  18408. region->GetBailoutReturnThunkLabel()->InsertAfter(insertBeforeInstr);
  18409. this->m_func->m_tailInstr = insertBeforeInstr;
  18410. }
  18411. IR::LabelOpnd * continuationAddr;
  18412. if (region->GetParent()->GetType() != RegionTypeRoot)
  18413. {
  18414. continuationAddr = IR::LabelOpnd::New(region->GetParent()->GetBailoutReturnThunkLabel(), this->m_func);
  18415. }
  18416. else
  18417. {
  18418. continuationAddr = IR::LabelOpnd::New(restoreLabel, this->m_func);
  18419. }
  18420. IR::Instr * lastInstr = m_lowererMD.LowerEHRegionReturn(insertBeforeInstr, continuationAddr);
  18421. if (newLastInstrInserted)
  18422. {
  18423. Assert(this->m_func->m_tailInstr == insertBeforeInstr);
  18424. insertBeforeInstr->Remove();
  18425. this->m_func->m_tailInstr = lastInstr;
  18426. }
  18427. region->returnThunkEmitted = true;
  18428. }
  18429. }
  18430. void
  18431. Lowerer::SetHasBailedOut(IR::Instr * bailoutInstr)
  18432. {
  18433. Assert(this->m_func->isPostLayout);
  18434. IR::SymOpnd * hasBailedOutOpnd = IR::SymOpnd::New(this->m_func->m_hasBailedOutSym, TyUint32, this->m_func);
  18435. IR::Instr * setInstr = IR::Instr::New(LowererMD::GetStoreOp(TyUint32), hasBailedOutOpnd, IR::IntConstOpnd::New(1, TyUint32, this->m_func), this->m_func);
  18436. bailoutInstr->InsertBefore(setInstr);
  18437. LowererMD::Legalize(setInstr, true);
  18438. }
  18439. IR::Instr*
  18440. Lowerer::EmitEHBailoutStackRestore(IR::Instr * bailoutInstr)
  18441. {
  18442. Assert(this->m_func->isPostLayout);
  18443. #ifdef _M_IX86
  18444. BailOutInfo * bailoutInfo = bailoutInstr->GetBailOutInfo();
  18445. if (bailoutInfo->startCallCount != 0)
  18446. {
  18447. uint totalStackToBeRestored = 0;
  18448. uint stackAlignmentAdjustment = 0;
  18449. for (uint i = 0; i < bailoutInfo->startCallCount; i++)
  18450. {
  18451. uint startCallOutParamCount = bailoutInfo->GetStartCallOutParamCount(i);
  18452. if ((Math::Align<int32>(startCallOutParamCount * MachPtr, MachStackAlignment) - (startCallOutParamCount * MachPtr)) != 0)
  18453. {
  18454. stackAlignmentAdjustment++;
  18455. }
  18456. }
  18457. totalStackToBeRestored = (bailoutInfo->totalOutParamCount + stackAlignmentAdjustment) * MachPtr;
  18458. IR::RegOpnd * espOpnd = IR::RegOpnd::New(NULL, LowererMD::GetRegStackPointer(), TyMachReg, this->m_func);
  18459. IR::Opnd * opnd = IR::IndirOpnd::New(espOpnd, totalStackToBeRestored, TyMachReg, this->m_func);
  18460. IR::Instr * stackRestoreInstr = IR::Instr::New(Js::OpCode::LEA, espOpnd, opnd, this->m_func);
  18461. bailoutInstr->InsertAfter(stackRestoreInstr);
  18462. return stackRestoreInstr;
  18463. }
  18464. #endif
  18465. return bailoutInstr;
  18466. }
  18467. void
  18468. Lowerer::EmitSaveEHBailoutReturnValueAndJumpToRetThunk(IR::Instr * insertAfterInstr)
  18469. {
  18470. Assert(this->m_func->isPostLayout);
  18471. // After the CALL SaveAllRegistersAndBailout instruction, emit
  18472. //
  18473. // MOV bailoutReturnValueSym, eax
  18474. // JMP $currentRegion->bailoutReturnThunkLabel
  18475. IR::SymOpnd * bailoutReturnValueSymOpnd = IR::SymOpnd::New(this->m_func->m_bailoutReturnValueSym, TyVar, this->m_func);
  18476. IR::RegOpnd *eaxOpnd = IR::RegOpnd::New(NULL, LowererMD::GetRegReturn(TyMachReg), TyMachReg, this->m_func);
  18477. IR::Instr * movInstr = IR::Instr::New(LowererMD::GetStoreOp(TyVar), bailoutReturnValueSymOpnd, eaxOpnd, this->m_func);
  18478. insertAfterInstr->InsertAfter(movInstr);
  18479. LowererMD::Legalize(movInstr, true);
  18480. IR::BranchInstr * jumpInstr = IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, this->currentRegion->GetBailoutReturnThunkLabel(), this->m_func);
  18481. movInstr->InsertAfter(jumpInstr);
  18482. }
  18483. void
  18484. Lowerer::EmitRestoreReturnValueFromEHBailout(IR::LabelInstr * restoreLabel, IR::LabelInstr * epilogLabel)
  18485. {
  18486. Assert(this->m_func->isPostLayout);
  18487. // JMP $epilog
  18488. // $restore:
  18489. // MOV eax, bailoutReturnValueSym
  18490. // $epilog:
  18491. IR::SymOpnd * bailoutReturnValueSymOpnd = IR::SymOpnd::New(this->m_func->m_bailoutReturnValueSym, TyVar, this->m_func);
  18492. IR::RegOpnd * eaxOpnd = IR::RegOpnd::New(NULL, LowererMD::GetRegReturn(TyMachReg), TyMachReg, this->m_func);
  18493. IR::Instr * movInstr = IR::Instr::New(LowererMD::GetLoadOp(TyVar), eaxOpnd, bailoutReturnValueSymOpnd, this->m_func);
  18494. epilogLabel->InsertBefore(restoreLabel);
  18495. epilogLabel->InsertBefore(movInstr);
  18496. LowererMD::Legalize(movInstr, true);
  18497. restoreLabel->InsertBefore(IR::BranchInstr::New(LowererMD::MDUncondBranchOpcode, epilogLabel, this->m_func));
  18498. }
  18499. void
  18500. Lowerer::InsertBitTestBranch(IR::Opnd * bitMaskOpnd, IR::Opnd * bitIndex, bool jumpIfBitOn, IR::LabelInstr * targetLabel, IR::Instr * insertBeforeInstr)
  18501. {
  18502. #if defined(_M_IX86) || defined(_M_AMD64)
  18503. // Generate bit test and branch
  18504. // BT bitMaskOpnd, bitIndex
  18505. // JB/JAE targetLabel
  18506. Func * func = this->m_func;
  18507. IR::Instr * instr = IR::Instr::New(Js::OpCode::BT, func);
  18508. instr->SetSrc1(bitMaskOpnd);
  18509. instr->SetSrc2(bitIndex);
  18510. insertBeforeInstr->InsertBefore(instr);
  18511. if (!(bitMaskOpnd->IsRegOpnd() || bitMaskOpnd->IsIndirOpnd() || bitMaskOpnd->IsMemRefOpnd()))
  18512. {
  18513. instr->HoistSrc1(Js::OpCode::MOV);
  18514. }
  18515. InsertBranch(jumpIfBitOn ? Js::OpCode::JB : Js::OpCode::JAE, targetLabel, insertBeforeInstr);
  18516. #elif defined(_M_ARM)
  18517. // ARM don't have bit test instruction, so just generated
  18518. // MOV r1, 1
  18519. // SHL r1, bitIndex
  18520. // TEST bitMaskOpnd, r1
  18521. // BEQ/BNEQ targetLabel
  18522. Func * func = this->m_func;
  18523. IR::RegOpnd * lenBitOpnd = IR::RegOpnd::New(TyUint32, func);
  18524. InsertMove(lenBitOpnd, IR::IntConstOpnd::New(1, TyUint32, this->m_func), insertBeforeInstr);
  18525. InsertShift(Js::OpCode::Shl_I4, false, lenBitOpnd, lenBitOpnd, bitIndex, insertBeforeInstr);
  18526. InsertTestBranch(lenBitOpnd, bitMaskOpnd, jumpIfBitOn? Js::OpCode::BrNeq_A :Js::OpCode::BrEq_A, targetLabel, insertBeforeInstr);
  18527. #else
  18528. AssertMsg(false, "Not implemented");
  18529. #endif
  18530. }
  18531. //
  18532. // Generates an object test and then a string test with the static string type
  18533. //
  18534. void
  18535. Lowerer::GenerateStringTest(IR::RegOpnd *srcReg, IR::Instr *insertInstr, IR::LabelInstr *labelHelper, IR::LabelInstr * continueLabel, bool generateObjectCheck)
  18536. {
  18537. Assert(srcReg);
  18538. if (!srcReg->GetValueType().IsString())
  18539. {
  18540. if (generateObjectCheck && !srcReg->IsNotTaggedValue())
  18541. {
  18542. this->m_lowererMD.GenerateObjectTest(srcReg, insertInstr, labelHelper);
  18543. }
  18544. // CMP [regSrcStr + offset(type)] , static string type -- check base string type
  18545. // BrEq/BrNeq labelHelper.
  18546. IR::IndirOpnd * src1 = IR::IndirOpnd::New(srcReg, Js::RecyclableObject::GetOffsetOfType(), TyMachReg, m_func);
  18547. IR::Opnd * src2 = this->LoadLibraryValueOpnd(insertInstr, LibraryValue::ValueStringTypeStatic);
  18548. if (continueLabel)
  18549. {
  18550. InsertCompareBranch(src1, src2, Js::OpCode::BrEq_A, continueLabel, insertInstr);
  18551. }
  18552. else
  18553. {
  18554. InsertCompareBranch(src1, src2, Js::OpCode::BrNeq_A, labelHelper, insertInstr);
  18555. }
  18556. }
  18557. }
  18558. void
  18559. Lowerer::LowerConvNum(IR::Instr *instrLoad, bool noMathFastPath)
  18560. {
  18561. if (PHASE_OFF(Js::OtherFastPathPhase, this->m_func) || noMathFastPath || !instrLoad->GetSrc1()->IsRegOpnd())
  18562. {
  18563. this->LowerUnaryHelperMemWithTemp2(instrLoad, IR_HELPER_OP_FULL_OR_INPLACE(ConvNumber));
  18564. return;
  18565. }
  18566. // MOV dst, src1
  18567. // TEST src1, 1
  18568. // JNE $done
  18569. // call ToNumber
  18570. //$done:
  18571. bool isInt = false;
  18572. bool isNotInt = false;
  18573. IR::RegOpnd *src1 = instrLoad->GetSrc1()->AsRegOpnd();
  18574. IR::LabelInstr *labelDone = NULL;
  18575. IR::Instr *instr;
  18576. if (src1->IsTaggedInt())
  18577. {
  18578. isInt = true;
  18579. }
  18580. else if (src1->IsNotInt())
  18581. {
  18582. isNotInt = true;
  18583. }
  18584. if (!isNotInt)
  18585. {
  18586. // MOV dst, src1
  18587. instr = LowererMD::CreateAssign(instrLoad->GetDst(), src1, instrLoad);
  18588. if (!isInt)
  18589. {
  18590. labelDone = IR::LabelInstr::New(Js::OpCode::Label, this->m_func);
  18591. bool didTest = m_lowererMD.GenerateObjectTest(src1, instrLoad, labelDone);
  18592. if (didTest)
  18593. {
  18594. // This label is needed only to mark the helper block
  18595. IR::LabelInstr * labelHelper = IR::LabelInstr::New(Js::OpCode::Label, this->m_func, true);
  18596. instrLoad->InsertBefore(labelHelper);
  18597. }
  18598. }
  18599. }
  18600. if (!isInt)
  18601. {
  18602. if (labelDone)
  18603. {
  18604. instrLoad->InsertAfter(labelDone);
  18605. }
  18606. this->LowerUnaryHelperMemWithTemp2(instrLoad, IR_HELPER_OP_FULL_OR_INPLACE(ConvNumber));
  18607. }
  18608. else
  18609. {
  18610. instrLoad->Remove();
  18611. }
  18612. }
  18613. IR::Opnd *
  18614. Lowerer::LoadSlotArrayWithCachedLocalType(IR::Instr * instrInsert, IR::PropertySymOpnd *propertySymOpnd)
  18615. {
  18616. IR::RegOpnd *opndBase = propertySymOpnd->CreatePropertyOwnerOpnd(m_func);
  18617. if (propertySymOpnd->UsesAuxSlot())
  18618. {
  18619. // If we use the auxiliary slot array, load it and return it
  18620. IR::RegOpnd *opndSlotArray = IR::RegOpnd::New(TyMachReg, this->m_func);
  18621. IR::Opnd *opndIndir = IR::IndirOpnd::New(opndBase, Js::DynamicObject::GetOffsetOfAuxSlots(), TyMachReg, this->m_func);
  18622. LowererMD::CreateAssign(opndSlotArray, opndIndir, instrInsert);
  18623. return opndSlotArray;
  18624. }
  18625. else
  18626. {
  18627. // If we use inline slot return the address to the object header
  18628. return opndBase;
  18629. }
  18630. }
  18631. IR::Opnd *
  18632. Lowerer::LoadSlotArrayWithCachedProtoType(IR::Instr * instrInsert, IR::PropertySymOpnd *propertySymOpnd)
  18633. {
  18634. // Get the prototype object from the cache
  18635. Js::RecyclableObject *prototypeObject = propertySymOpnd->GetProtoObject();
  18636. Assert(prototypeObject != nullptr);
  18637. if (propertySymOpnd->UsesAuxSlot())
  18638. {
  18639. // If we use the auxiliary slot array, load it from the prototype object and return it
  18640. IR::RegOpnd *opndSlotArray = IR::RegOpnd::New(TyMachReg, this->m_func);
  18641. IR::Opnd *opnd = IR::MemRefOpnd::New((char*)prototypeObject + Js::DynamicObject::GetOffsetOfAuxSlots(), TyMachReg, this->m_func, IR::AddrOpndKindDynamicAuxSlotArrayRef);
  18642. LowererMD::CreateAssign(opndSlotArray, opnd, instrInsert);
  18643. return opndSlotArray;
  18644. }
  18645. else
  18646. {
  18647. // If we use inline slot return the address of the prototype object
  18648. return IR::MemRefOpnd::New(prototypeObject, TyMachReg, this->m_func);
  18649. }
  18650. }
  18651. IR::Instr *
  18652. Lowerer::LowerLdAsmJsEnv(IR::Instr * instr)
  18653. {
  18654. Assert(m_func->GetJnFunction()->GetIsAsmJsFunction());
  18655. IR::Opnd * functionObjOpnd;
  18656. IR::Instr * instrPrev = this->m_lowererMD.LoadFunctionObjectOpnd(instr, functionObjOpnd);
  18657. Assert(!instr->GetSrc1());
  18658. IR::IndirOpnd *indirOpnd = IR::IndirOpnd::New(functionObjOpnd->AsRegOpnd(), Js::AsmJsScriptFunction::GetOffsetOfModuleMemory(), TyMachPtr, m_func);
  18659. instr->SetSrc1(indirOpnd);
  18660. LowererMD::ChangeToAssign(instr);
  18661. return instrPrev;
  18662. }
  18663. IR::Instr *
  18664. Lowerer::LowerLdEnv(IR::Instr * instr)
  18665. {
  18666. IR::Opnd * src1 = instr->GetSrc1();
  18667. IR::Opnd * functionObjOpnd;
  18668. IR::Instr * instrPrev = this->m_lowererMD.LoadFunctionObjectOpnd(instr, functionObjOpnd);
  18669. Assert(!instr->GetSrc1());
  18670. if (src1 == nullptr || functionObjOpnd->IsRegOpnd())
  18671. {
  18672. IR::IndirOpnd *indirOpnd = IR::IndirOpnd::New(functionObjOpnd->AsRegOpnd(),
  18673. Js::ScriptFunction::GetOffsetOfEnvironment(), TyMachPtr, m_func);
  18674. instr->SetSrc1(indirOpnd);
  18675. }
  18676. else
  18677. {
  18678. Assert(functionObjOpnd->IsAddrOpnd());
  18679. IR::AddrOpnd* functionObjAddrOpnd = functionObjOpnd->AsAddrOpnd();
  18680. IR::MemRefOpnd* functionEnvMemRefOpnd = IR::MemRefOpnd::New((void *)((intptr)functionObjAddrOpnd->m_address + Js::ScriptFunction::GetOffsetOfEnvironment()),
  18681. TyMachPtr, this->m_func, IR::AddrOpndKindDynamicFunctionEnvironmentRef);
  18682. instr->SetSrc1(functionEnvMemRefOpnd);
  18683. }
  18684. LowererMD::ChangeToAssign(instr);
  18685. return instrPrev;
  18686. }
  18687. IR::Instr *
  18688. Lowerer::LowerFrameDisplayCheck(IR::Instr * instr)
  18689. {
  18690. IR::Instr *instrPrev = instr->m_prev;
  18691. IR::Instr *insertInstr = instr->m_next;
  18692. IR::AddrOpnd *addrOpnd = instr->UnlinkSrc2()->AsAddrOpnd();
  18693. FrameDisplayCheckRecord *record = (FrameDisplayCheckRecord*)addrOpnd->m_address;
  18694. IR::LabelInstr *errorLabel = nullptr;
  18695. IR::LabelInstr *continueLabel = nullptr;
  18696. IR::RegOpnd *envOpnd = instr->GetDst()->AsRegOpnd();
  18697. uint32 frameDisplayOffset = Js::FrameDisplay::GetOffsetOfScopes()/sizeof(Js::Var);
  18698. if (record->slotId != (uint32)-1 && record->slotId > frameDisplayOffset)
  18699. {
  18700. // Check that the frame display has enough scopes in it to satisfy the code.
  18701. errorLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func, true);
  18702. continueLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  18703. IR::IndirOpnd * indirOpnd = IR::IndirOpnd::New(envOpnd,
  18704. Js::FrameDisplay::GetOffsetOfLength(),
  18705. TyUint16, m_func, true);
  18706. IR::IntConstOpnd *slotIdOpnd = IR::IntConstOpnd::New(record->slotId - frameDisplayOffset, TyUint16, m_func);
  18707. InsertCompareBranch(indirOpnd, slotIdOpnd, Js::OpCode::BrLe_A, true, errorLabel, insertInstr);
  18708. }
  18709. if (record->table)
  18710. {
  18711. // Check the size of each of the slot arrays in the scope chain.
  18712. FOREACH_HASHTABLE_ENTRY(uint32, bucket, record->table)
  18713. {
  18714. uint32 slotId = bucket.element;
  18715. if (slotId != (uint32)-1 && slotId > Js::ScopeSlots::FirstSlotIndex)
  18716. {
  18717. if (errorLabel == nullptr)
  18718. {
  18719. errorLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func, true);
  18720. continueLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  18721. }
  18722. IR::IndirOpnd * indirOpnd = IR::IndirOpnd::New(envOpnd,
  18723. bucket.value * sizeof(Js::Var),
  18724. TyVar, m_func, true);
  18725. IR::RegOpnd * slotArrayOpnd = IR::RegOpnd::New(TyVar, m_func);
  18726. InsertMove(slotArrayOpnd, indirOpnd, insertInstr);
  18727. indirOpnd = IR::IndirOpnd::New(slotArrayOpnd,
  18728. Js::ScopeSlots::EncodedSlotCountSlotIndex * sizeof(Js::Var),
  18729. TyUint32, m_func, true);
  18730. IR::IntConstOpnd * slotIdOpnd = IR::IntConstOpnd::New(slotId - Js::ScopeSlots::FirstSlotIndex,
  18731. TyUint32, m_func);
  18732. InsertCompareBranch(indirOpnd, slotIdOpnd, Js::OpCode::BrLe_A, true, errorLabel, insertInstr);
  18733. }
  18734. }
  18735. NEXT_HASHTABLE_ENTRY;
  18736. }
  18737. if (errorLabel)
  18738. {
  18739. InsertBranch(Js::OpCode::Br, continueLabel, insertInstr);
  18740. insertInstr->InsertBefore(errorLabel);
  18741. IR::Instr * instrHelper = IR::Instr::New(Js::OpCode::Call, m_func);
  18742. insertInstr->InsertBefore(instrHelper);
  18743. m_lowererMD.ChangeToHelperCall(instrHelper, IR::HelperOp_FatalInternalError);
  18744. insertInstr->InsertBefore(continueLabel);
  18745. }
  18746. m_lowererMD.ChangeToAssign(instr);
  18747. return instrPrev;
  18748. }
  18749. IR::Instr *
  18750. Lowerer::LowerSlotArrayCheck(IR::Instr * instr)
  18751. {
  18752. IR::Instr *instrPrev = instr->m_prev;
  18753. IR::Instr *insertInstr = instr->m_next;
  18754. IR::RegOpnd *slotArrayOpnd = instr->GetDst()->AsRegOpnd();
  18755. StackSym *stackSym = slotArrayOpnd->m_sym;
  18756. IR::IntConstOpnd *slotIdOpnd = instr->UnlinkSrc2()->AsIntConstOpnd();
  18757. uint32 slotId = (uint32)slotIdOpnd->GetValue();
  18758. Assert(slotId != (uint32)-1 && slotId >= Js::ScopeSlots::FirstSlotIndex);
  18759. if (slotId > Js::ScopeSlots::FirstSlotIndex)
  18760. {
  18761. if (m_func->DoStackFrameDisplay() && stackSym->m_id == m_func->GetLocalClosureSym()->m_id)
  18762. {
  18763. // The pointer we loaded points to the reserved/known address where the slot array can be boxed.
  18764. // Deref to get the real value.
  18765. IR::IndirOpnd * srcOpnd = IR::IndirOpnd::New(IR::RegOpnd::New(stackSym, TyVar, m_func), 0, TyVar, m_func);
  18766. IR::RegOpnd * dstOpnd = IR::RegOpnd::New(TyVar, m_func);
  18767. InsertMove(dstOpnd, srcOpnd, insertInstr);
  18768. stackSym = dstOpnd->m_sym;
  18769. }
  18770. IR::LabelInstr *errorLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func, true);
  18771. IR::LabelInstr *continueLabel = IR::LabelInstr::New(Js::OpCode::Label, m_func);
  18772. IR::IndirOpnd * indirOpnd = IR::IndirOpnd::New(IR::RegOpnd::New(stackSym, TyVar, m_func),
  18773. Js::ScopeSlots::EncodedSlotCountSlotIndex * sizeof(Js::Var),
  18774. TyUint32, m_func, true);
  18775. slotIdOpnd->SetValue(slotId - Js::ScopeSlots::FirstSlotIndex);
  18776. InsertCompareBranch(indirOpnd, slotIdOpnd, Js::OpCode::BrGt_A, true, continueLabel, insertInstr);
  18777. insertInstr->InsertBefore(errorLabel);
  18778. IR::Instr * instrHelper = IR::Instr::New(Js::OpCode::Call, m_func);
  18779. insertInstr->InsertBefore(instrHelper);
  18780. m_lowererMD.ChangeToHelperCall(instrHelper, IR::HelperOp_FatalInternalError);
  18781. insertInstr->InsertBefore(continueLabel);
  18782. }
  18783. m_lowererMD.ChangeToAssign(instr);
  18784. return instrPrev;
  18785. }
  18786. IR::RegOpnd *
  18787. Lowerer::LoadIndexFromLikelyFloat(
  18788. IR::RegOpnd *indexOpnd,
  18789. const bool skipNegativeCheck,
  18790. IR::LabelInstr *const notIntLabel,
  18791. IR::LabelInstr *const negativeLabel,
  18792. IR::Instr *const insertBeforeInstr)
  18793. {
  18794. #ifdef _M_IX86
  18795. // We should only generate this if sse2 is available
  18796. Assert(AutoSystemInfo::Data.SSE2Available());
  18797. #endif
  18798. Func *func = insertBeforeInstr->m_func;
  18799. IR::LabelInstr * convertToUint = IR::LabelInstr::New(Js::OpCode::Label, func);
  18800. IR::LabelInstr * fallThrough = IR::LabelInstr::New(Js::OpCode::Label, func);
  18801. // First generate test for tagged int even though profile data says likely float. Indices are usually int and we need a fast path before we try to convert float to int
  18802. // mov intIndex, index
  18803. // sar intIndex, 1
  18804. // jae convertToInt
  18805. IR::RegOpnd *int32IndexOpnd = GenerateUntagVar(indexOpnd, convertToUint, insertBeforeInstr, !indexOpnd->IsTaggedInt());
  18806. if (!skipNegativeCheck)
  18807. {
  18808. // test index, index
  18809. // js $notTaggedIntOrNegative
  18810. InsertTestBranch(int32IndexOpnd, int32IndexOpnd, LowererMD::MDCompareWithZeroBranchOpcode(Js::OpCode::BrLt_A), negativeLabel, insertBeforeInstr);
  18811. }
  18812. InsertBranch(Js::OpCode::Br, fallThrough, insertBeforeInstr);
  18813. insertBeforeInstr->InsertBefore(convertToUint);
  18814. // try to convert float to int in a fast path
  18815. #if FLOATVAR
  18816. IR::RegOpnd* floatIndexOpnd = m_lowererMD.CheckFloatAndUntag(indexOpnd, insertBeforeInstr, notIntLabel);
  18817. #else
  18818. m_lowererMD.GenerateFloatTest(indexOpnd, insertBeforeInstr, notIntLabel);
  18819. IR::IndirOpnd * floatIndexOpnd = IR::IndirOpnd::New(indexOpnd, Js::JavascriptNumber::GetValueOffset(), TyMachDouble, this->m_func);
  18820. #endif
  18821. IR::LabelInstr * doneConvUint32 = IR::LabelInstr::New(Js::OpCode::Label, func);
  18822. IR::LabelInstr * helperConvUint32 = IR::LabelInstr::New(Js::OpCode::Label, func, true /*helper*/);
  18823. m_lowererMD.ConvertFloatToInt32(int32IndexOpnd, floatIndexOpnd, helperConvUint32, doneConvUint32, insertBeforeInstr);
  18824. // helper path
  18825. insertBeforeInstr->InsertBefore(helperConvUint32);
  18826. m_lowererMD.LoadDoubleHelperArgument(insertBeforeInstr, floatIndexOpnd);
  18827. IR::Instr * helperCall = IR::Instr::New(Js::OpCode::Call, int32IndexOpnd, this->m_func);
  18828. insertBeforeInstr->InsertBefore(helperCall);
  18829. m_lowererMD.ChangeToHelperCall(helperCall, IR::HelperConv_ToUInt32Core);
  18830. // main path
  18831. insertBeforeInstr->InsertBefore(doneConvUint32);
  18832. //Convert uint32 to back to float for comparison that conversion was indeed successful
  18833. IR::RegOpnd *floatOpndFromUint32 = IR::RegOpnd::New(TyFloat64, func);
  18834. m_lowererMD.EmitUIntToFloat(floatOpndFromUint32, int32IndexOpnd, insertBeforeInstr);
  18835. // compare with float from the original indexOpnd, we need floatIndex == (float64)(uint32)floatIndex
  18836. InsertCompareBranch(floatOpndFromUint32, floatIndexOpnd, Js::OpCode::BrNeq_A, notIntLabel, insertBeforeInstr, false);
  18837. insertBeforeInstr->InsertBefore(fallThrough);
  18838. return int32IndexOpnd;
  18839. }
  18840. #if DBG
  18841. void
  18842. Lowerer::LegalizeVerifyRange(IR::Instr * instrStart, IR::Instr * instrLast)
  18843. {
  18844. FOREACH_INSTR_IN_RANGE(verifyLegalizeInstr, instrStart, instrLast)
  18845. {
  18846. LowererMD::Legalize<true>(verifyLegalizeInstr);
  18847. }
  18848. NEXT_INSTR_IN_RANGE;
  18849. }
  18850. #endif